Programs & Examples On #Farpoint spread

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

Use jquery attr method. It works in all browsers.

var hiddenInput = document.createElement("input");
$(hiddenInput).attr({
    'id':'uniqueIdentifier',
    'type': 'hidden',
    'value': ID,
    'class': 'ListItem'
});

Or you could use folowing code:

var e = $('<input id = "uniqueIdentifier" type="hidden" value="' + ID + '" class="ListItem" />');

How do I read the source code of shell commands?

Actually more sane sources are provided by http://suckless.org look at their sbase repository:

git clone git://git.suckless.org/sbase

They are clearer, smarter, simpler and suckless, eg ls.c has just 369 LOC

After that it will be easier to understand more complicated GNU code.

How to print a float with 2 decimal places in Java?

To print a float up to 2 decimal places in Java:

    float f = (float)11/3;
    System.out.print(String.format("%.2f",f));

OUTPUT: 3.67

> use %.3f for up to three decimal places.

Convert Iterable to Stream using Java 8 JDK

If you happen to use Vavr(formerly known as Javaslang), this can be as easy as:

Iterable i = //...
Stream.ofAll(i);

Text in HTML Field to disappear when clicked?

Use the placeholder attribute. The text disappears when the user starts typing. This is an example of a project I am working on:

<div class="" id="search-form">
    <input type="text" name="" value="" class="form-control" placeholder="Search..." >
</div>

Node.js get file extension

It's a lot more efficient to use the substr() method instead of split() & pop()

Have a look at the performance differences here: http://jsperf.com/remove-first-character-from-string

// returns: 'html'
var path = require('path');
path.extname('index.html').substr(1);

enter image description here

Update August 2019 As pointed out by @xentek in the comments; substr() is now considered a legacy function (MDN documentation). You can use substring() instead. The difference between substr() and substring() is that the second argument of substr() is the maximum length to return while the second argument of substring() is the index to stop at (without including that character). Also, substr() accepts negative start positions to be used as an offset from the end of the string while substring() does not.

Installing Node.js (and npm) on Windows 10

Edit: It seems like new installers do not have this problem anymore, see this answer by Parag Meshram as my answer is likely obsolete now.

Original answer:

Follow these steps, closely:

  • http://nodejs.org/download/ download the 64 bits version, 32 is for hipsters
  • Install it anywhere you want, by default: C:\Program Files\nodejs
  • Control Panel -> System -> Advanced system settings -> Environment Variables
  • Select PATH and choose to edit it.

If the PATH variable is empty, change it to this: C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

If the PATH variable already contains C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm, append the following right after: ;C:\Program Files\nodejs

If the PATH variable contains information, but nothing regarding npm, append this to the end of the PATH: ;C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

Now that the PATH variable is set correctly, you will still encounter errors. Manually go into the AppData directory and you will find that there is no npm directory inside Roaming. Manually create this directory.

Re-start the command prompt and npm will now work.

How to change current working directory using a batch file

Try this

chdir /d D:\Work\Root

Enjoy rooting ;)

What is the difference between YAML and JSON?

If you don't need any features which YAML has and JSON doesn't, I would prefer JSON because it is very simple and is widely supported (has a lot of libraries in many languages). YAML is more complex and has less support. I don't think the parsing speed or memory use will be very much different, and maybe not a big part of your program's performance.

Excel VBA code to copy a specific string to clipboard

This macro uses late binding to copy text to the clipboard without requiring you to set references. You should be able to just paste and go:

Sub CopyText(Text As String)
    'VBA Macro using late binding to copy text to clipboard.
    'By Justin Kay, 8/15/2014
    Dim MSForms_DataObject As Object
    Set MSForms_DataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    MSForms_DataObject.SetText Text
    MSForms_DataObject.PutInClipboard
    Set MSForms_DataObject = Nothing
End Sub

Usage:

Sub CopySelection()
    CopyText Selection.Text
End Sub

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

How can moment.js be imported with typescript?

Not sure when this changed, but with the latest version of typescript, you just need to use import moment from 'moment'; and everything else should work as normal.

UPDATE:

Looks like moment recent fixed their import. As of at least 2.24.0 you'll want to use import * as moment from 'moment';

How to allow only numeric (0-9) in HTML inputbox using jQuery?

You can use the following code.

_x000D_
_x000D_
<input type="text" onkeypress="return event.charCode &gt;= 48 &amp;&amp; event.charCode &lt;= 57">
_x000D_
_x000D_
_x000D_

Android fastboot waiting for devices

In my case (on windows 10), it would connect fine to adb and I could type any adb commands. But as soon as it got to the bootloader using adb reboot bootloader I wasn't able to perform any fastboot commands.

What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID), and that fixed my waiting for device issue

how to convert binary string to decimal?

Slightly modified conventional binary conversion algorithm utilizing some more ES6 syntax and auto-features:

  1. Convert binary sequence string to Array (assuming it wasnt already passed as array)

  2. Reverse sequence to force 0 index to start at right-most binary digit as binary is calculated right-left

  3. 'reduce' Array function traverses array, performing summation of (2^index) per binary digit [only if binary digit === 1] (0 digit always yields 0)

NOTE: Binary conversion formula:

{where d=binary digit, i=array index, n=array length-1 (starting from right)}

n
? (d * 2^i)
i=0

let decimal = Array.from(binaryString).reverse().reduce((total, val, index)=>val==="1"?total + 2**index:total, 0);  

console.log(`Converted BINARY sequence (${binaryString}) to DECIMAL (${decimal}).`);

Set cookie and get cookie with JavaScript

I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.

This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Mozilla has some tests to prove this works in all cases.

There is an alternative snippet here:

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

I had this issue too. I deleted the extra images from my project's drawable folder.

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

How can I loop through a C++ map of maps?

You can use an iterator.

typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for(it_type iterator = m.begin(); iterator != m.end(); iterator++) {
    // iterator->first = key
    // iterator->second = value
    // Repeat if you also want to iterate through the second map.
}

What is a provisioning profile used for when developing iPhone applications?

You need it to install development iPhone applications on development devices.

Here's how to create one, and the reference for this answer:
http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone

Another link: http://iphone.timefold.com/provisioning.html

How to make grep only match if the entire line matches?

Here is what I do, though using anchors is the best way:

grep -w "ABB.log " a.tmp

SQL Server IF EXISTS THEN 1 ELSE 2

If you want to do it this way then this is the syntax you're after;

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.

Is there an equivalent of CSS max-width that works in HTML emails?

The short answer: no.

The long answer:

Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.

It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.

Flask raises TemplateNotFound error even though template file exists

I think Flask uses the directory templates by default. So your code should be like this

suppose this is your hello.py

from flask import Flask,render_template

app=Flask(__name__,template_folder='template')


@app.route("/")
def home():
    return render_template('home.html')

@app.route("/about/")
def about():
    return render_template('about.html')

if __name__=="__main__":
    app.run(debug=True)

And you work space structure like

project/
    hello.py        
    template/
         home.html
         about.html    
    static/
           js/
             main.js
           css/
               main.css

also you have create two html files with name of home.html and about.html and put those files in templates folder.

How do I make a matrix from a list of vectors in R?

Not straightforward, but it works:

> t(sapply(a, unlist))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Anaconda Navigator won't launch (windows 10)

I tried the following @janny loco's answer first and then reset anaconda to get it to work.

Step 1:

activate root
conda update -n root conda
conda update --all

Step 2:

anaconda-navigator --reset

After running the update commands in step 1 and not seeing any success, I reset anaconda by running the command above based on what I found here.

I am not sure if it was the combination of updating conda and reseting the navigator or just one of the two. So, please try accordingly.

How to confirm RedHat Enterprise Linux version?

I assume that you've run yum upgrade. That will in general update you to the newest minor release.

Your main resources for determining the version are /etc/redhat_release and lsb_release -a

How can I see the size of a GitHub repository before cloning it?

If you're trying to find out the size of your own repositories.

All you have to do is go to GitHub settings repositories and you see all the sizes right there in the browser no extra work needed.

https://github.com/settings/repositories

What's the proper way to "go get" a private repository?

You have one thing to configure. The example is based on GitHub but this shouldn't change the process:

$ git config --global [email protected]:.insteadOf https://github.com/
$ cat ~/.gitconfig
[url "[email protected]:"]
    insteadOf = https://github.com/
$ go get github.com/private/repo

For Go modules to work (with Go 1.11 or newer), you'll also need to set the GOPRIVATE variable, to avoid using the public servers to fetch the code:

export GOPRIVATE=github.com/private/repo

How do I make a stored procedure in MS Access?

Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).

If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.

For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.

For example:

screenshot

Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table alt text

Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.

How do you update a DateTime field in T-SQL?

When in doubt, be explicit about the data type conversion using CAST/CONVERT:

UPDATE TABLE
   SET EndDate = CAST('2009-05-25' AS DATETIME)
 WHERE Id = 1

jQuery How do you get an image to fade in on load?

window.onload is not that trustworthy.. I would use:

<script type="text/javascript">
    $(document).ready(function () {
        $('#logo').hide().fadeIn(3000);
    });
</script>

jQuery - Dynamically Create Button and Attach Event Handler

Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.

$("#myButton").click(function () {
    var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
        alert('hi');
    }).end();

    $("#nodeAttributeHeader").attr('style', 'display: table-row;');
    $("#addNodeTable tr:last").before(test);
});

Why do I need to override the equals and hashCode methods in Java?

String class and wrapper classes have different implementation of equals() and hashCode() methods than Object class. equals() method of Object class compares the references of the objects, not the contents. hashCode() method of Object class returns distinct hashcode for every single object whether the contents are same.

It leads problem when you use Map collection and the key is of Persistent type, StringBuffer/builder type. Since they don't override equals() and hashCode() unlike String class, equals() will return false when you compare two different objects even though both have same contents. It will make the hashMap storing same content keys. Storing same content keys means it is violating the rule of Map because Map doesnt allow duplicate keys at all. Therefore you override equals() as well as hashCode() methods in your class and provide the implementation(IDE can generate these methods) so that they work same as String's equals() and hashCode() and prevent same content keys.

You have to override hashCode() method along with equals() because equals() work according hashcode.

Moreover overriding hashCode() method along with equals() helps to intact the equals()-hashCode() contract: "If two objects are equal, then they must have the same hash code."

When do you need to write custom implementation for hashCode()?

As we know that internal working of HashMap is on principle of Hashing. There are certain buckets where entrysets get stored. You customize the hashCode() implementation according your requirement so that same category objects can be stored into same index. when you store the values into Map collection using put(k,v)method, the internal implementation of put() is:

put(k, v){
hash(k);
index=hash & (n-1);
}

Means, it generates index and the index is generated based on the hashcode of particular key object. So make this method generate hashcode according your requirement because same hashcode entrysets will be stored into same bucket or index.

That's it!

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the Java Virtual Machine – it actually runs Java ByteCode.

JRE is the Java Runtime Environment – it contains a JVM, among other things, and is what you need to run a Java program.

JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need to compile Java source code) and other programming tools added.

OpenJDK is a specific JDK implementation.

docker mounting volumes on host

This is from the Docker documentation itself, might be of help, simple and plain:

"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".

Writing a large resultset to an Excel file using POI

Using SXSSF poi 3.8

package example;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class SXSSFexample {


    public static void main(String[] args) throws Throwable {
        FileInputStream inputStream = new FileInputStream("mytemplate.xlsx");
        XSSFWorkbook wb_template = new XSSFWorkbook(inputStream);
        inputStream.close();

        SXSSFWorkbook wb = new SXSSFWorkbook(wb_template); 
        wb.setCompressTempFiles(true);

        SXSSFSheet sh = (SXSSFSheet) wb.getSheetAt(0);
        sh.setRandomAccessWindowSize(100);// keep 100 rows in memory, exceeding rows will be flushed to disk
    for(int rownum = 4; rownum < 100000; rownum++){
        Row row = sh.createRow(rownum);
        for(int cellnum = 0; cellnum < 10; cellnum++){
            Cell cell = row.createCell(cellnum);
            String address = new CellReference(cell).formatAsString();
            cell.setCellValue(address);
        }

    }


    FileOutputStream out = new FileOutputStream("tempsxssf.xlsx");
    wb.write(out);
    out.close();
}

}

It requires:

  • poi-ooxml-3.8.jar,
  • poi-3.8.jar,
  • poi-ooxml-schemas-3.8.jar,
  • stax-api-1.0.1.jar,
  • xml-apis-1.0.b2.jar,
  • xmlbeans-2.3.0.jar,
  • commons-codec-1.5.jar,
  • dom4j-1.6.1.jar

Useful link

ArrayList initialization equivalent to array initialization

Arrays.asList can help here:

new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

Can a local variable's memory be accessed outside its scope?

It works because the stack has not been altered (yet) since a was put there. Call a few other functions (which are also calling other functions) before accessing a again and you will probably not be so lucky anymore... ;-)

Determine path of the executing script

I couldn't get Suppressingfire's solution to work when 'source'ing from the R console.
I couldn't get hadley's solution to work when using Rscript.

Best of both worlds?

thisFile <- function() {
        cmdArgs <- commandArgs(trailingOnly = FALSE)
        needle <- "--file="
        match <- grep(needle, cmdArgs)
        if (length(match) > 0) {
                # Rscript
                return(normalizePath(sub(needle, "", cmdArgs[match])))
        } else {
                # 'source'd via R console
                return(normalizePath(sys.frames()[[1]]$ofile))
        }
}

Calling Member Functions within Main C++

You need to create an object since printInformation() is non-static. Try:

int main() {

MyClass o;
o.printInformation();

fgetc( stdin );
return(0);

}

Install specific version using laravel installer

Using composer you can specify the version you want easily by running

composer create-project laravel/laravel="5.1.*" myProject

Using the 5.1.* will ensure that you get all the latest patches in the 5.1 branch.

PHP shell_exec() vs exec()

shell_exec returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.

See

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

Git on Mac OS X v10.7 (Lion)

It's part of Xcode. You'll need to reinstall the developer tools.

How can I output UTF-8 from Perl?

You can use the open pragma.

For eg. below sets STDOUT, STDIN & STDERR to use UTF-8....

use open qw/:std :utf8/;

How to delete a specific file from folder using asp.net

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files. 
    foreach (string f in picList)
    {
        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path. 
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files. 
    foreach (string f in txtList)
    {

        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied. 
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied. 
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}

Makefile: How to correctly include header file and its directory?

Try INC_DIR=../ ../StdCUtil.

Then, set CCFLAGS=-c -Wall $(addprefix -I,$(INC_DIR))

EDIT: Also, modify your #include to be #include <StdCUtil/split.h> so that the compiler knows to use -I rather than local path of the .cpp using the #include.

How can I remove the extension of a filename in a shell script?

file1=/tmp/main.one.two.sh
t=$(basename "$file1")                        # output is main.one.two.sh
name=$(echo "$file1" | sed -e 's/\.[^.]*$//') # output is /tmp/main.one.two
name=$(echo "$t" | sed -e 's/\.[^.]*$//')     # output is main.one.two

use whichever you want. Here I assume that last . (dot) followed by text is extension.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.

Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):

int x = 0;
auto f1 = [=]() mutable {x = 42;};  // OK
auto f2 = [=]()         {x = 42;};  // Error: a by-value capture cannot be modified in a non-mutable lambda

Possible to iterate backwards through a foreach?

If you use a List<T>, you can also use this code:

List<string> list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Reverse();

This is a method that write the list reverse in itself.

Now the foreach:

foreach(string s in list)
{
    Console.WriteLine(s);
}

The output is:

3
2
1

Add line break within tooltips

Give \n between the text. It work on all browsers.

Example 
img.tooltip= " Your Text : \n"
img.tooltip += " Your text \n";

This will work for me and it's used in code behind.

Hope this will work for you

How to clear cache of Eclipse Indigo

Instructions

  1. Open Eclipse and navigate to the Window > Preferences.
  2. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. Select File Cache.
  3. Click the Clear Cached Files button in the File Cache window. Note that this will automatically close any open remote files on your computer.
  4. Press Apply and OK to save your changes and exit out of the Preferences window.

Insert Data Into Tables Linked by Foreign Key

Use stored procedures.

And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

Sample Code: To set Footer text programatically

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.Footer)
      {
         Label lbl = (Label)e.Row.FindControl("lblTotal");
         lbl.Text = grdTotal.ToString("c");
      }
   }

UPDATED CODE:

  decimal sumFooterValue = 0;
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
         string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
         string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
         string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
         string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
         string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
         decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
         e.Row.Cells[6].Text = totalvalue.ToString();
         sumFooterValue += totalvalue; 
        }

    if (e.Row.RowType == DataControlRowType.Footer)
        {
           Label lbl = (Label)e.Row.FindControl("lblTotal");
           lbl.Text = sumFooterValue.ToString();
        }

   }

In .aspx Page

 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
        AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4" 
        ForeColor="#333333" GridLines="None" ShowFooter="True" 
                onrowdatabound="GridView1_RowDataBound">
        <RowStyle BackColor="#EFF3FB" />
        <Columns>
            <asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" 
                        Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" 
                        Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" 
                        Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Total" SortExpression="total">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server"></asp:Label>
                </ItemTemplate>
                <ItemStyle Width="100px" />

            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />            
    </asp:GridView>

My Blog - Asp.net Gridview Article

Why does viewWillAppear not get called when an app comes back from the background?

viewWillAppear:animated:, one of the most confusing methods in the iOS SDKs in my opinion, is never be invoked in such a situation, i.e., application switching. That method is only invoked according to the relationship between the view controller's view and the application's window, i.e., the message is sent to a view controller only if its view appears on the application's window, not on the screen.

When your application goes background, obviously the topmost views of the application window are no longer visible to the user. In your application window's perspective, however, they are still the topmost views and therefore they did not disappear from the window. Rather, those views disappeared because the application window disappeared. They did not disappeared because they disappeared from the window.

Therefore, when the user switches back to your application, they obviously seem to appear on the screen, because the window appears again. But from the window's perspective, they haven't disappeared at all. Therefore the view controllers never get the viewWillAppear:animated message.

Nullable types: better way to check for null or zero in c#

You code sample will fail. If obj is null then the obj.ToString() will result in a null reference exception. I'd short cut the process and check for a null obj at the start of your helper function. As to your actual question, what's the type you're checking for null or zero? On String there's a great IsNullOrEmpty function, seems to me this would be a great use of extension methods to implement an IsNullOrZero method on the int? type.

Edit: Remember, the '?' is just compiler sugar for the INullable type, so you could probably take an INullable as the parm and then jsut compare it to null (parm == null) and if not null compare to zero.

How to cast an Object to an int

first check with instanceof keyword . if true then cast it.

Have log4net use application config file for configuration data

All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref .. section it is named as ConsoleAppender. They need to match.

You can add multiple appenders to your log config but you need to register each of them in the <root> section.

<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />

You can also refer to the apache documentation on configuring log4net.

Enabling/Disabling Microsoft Virtual WiFi Miniport

Try to add this hotfix: hotfixv4.microsoft.com/Windows%207/Windows%20Server2008%20R2%20SP1/sp2/Fix362872/7600/free/427221_intl_i386_zip.exe

How can I disable a button on a jQuery UI dialog?

You can also use the not now documented disabled attribute:

$("#element").dialog({
    buttons: [
    {
        text: "Confirm",
        disabled: true,
        id: "my-button-1"
    }, 
    {
        text: "Cancel",
        id: "my-button-2",
        click: function(){            
               $(this).dialog("close");
        }  

    }]
});

To enable after dialog has opened, use:

$("#my-button-1").attr('disabled', false);

JsFiddle: http://jsfiddle.net/xvt96e1p/4/

How do I perform query filtering in django templates

This can be solved with an assignment tag:

from django import template

register = template.Library()

@register.assignment_tag
def query(qs, **kwargs):
    """ template tag which allows queryset filtering. Usage:
          {% query books author=author as mybooks %}
          {% for book in mybooks %}
            ...
          {% endfor %}
    """
    return qs.filter(**kwargs)

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

Try to add ReactiveFormsModule in your component as well.

import { FormGroup, FormArray, FormBuilder,
          Validators,ReactiveFormsModule  } from '@angular/forms';

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How to check if a variable is empty in python?

Just use not:

if not your_variable:
    print("your_variable is empty")

and for your 0 as string use:

if your_variable == "0":
    print("your_variable is 0 (string)")

combine them:

if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python is about simplicity, so is this answer :)

HTML5 Audio stop function

I believe it would be good to check if the audio is playing state and reset the currentTime property.

if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
    sound.currentTime = 0;
}
sound.play();

How to return first 5 objects of Array in Swift?

The Prefix function is definitely the most efficient way of solving this problem, but you can also use for-in loops like the following:

let array = [1,2,3,4,5,6,7,8,9]
let maxNum = 5
var iterationNumber = 0
var firstNumbers = [Int()]
if array.count > maxNum{
  for i in array{
    iterationNumber += 1
    if iterationNumber <= maxNum{
      firstNumbers.append(i)
    }
  }
  firstNumbers.remove(at: 0)
  print(firstNumbers)
} else {
  print("There were not \(maxNum) items in the array.")
}

This solution takes up many lines of code but checks to see if there are enough items in the array to carry out the program, then continues and solves the problem. This solution uses many basic functions including array.count, which returns the amount of items in the array, not the position of last item in the array. It also uses array.append, which adds things onto the end of the array. Lastly, it uses array.remove, which removes the array's item that has a specified position.

I have tested it it and it works for at least swift 5.

jquery get all form elements: input, textarea & select

var $form_elements = $("#form_id").find(":input");

All the elements including the submit-button are now in the variable $form_elements.

Bootstrap 3 modal responsive

Old post. I ended up setting media queries and using max-width: YYpx; and width:auto; for each breakpoint. This will scale w/ images as well (per say you have an image that's 740px width on the md screen), the modal will scale down to 740px (excluding padding for the .modal-body, if applied)

<div class="modal fade" id="bs-button-info-modal" tabindex="-1" role="dialog" aria-labelledby="Button Information Modal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <div class="modal-body"></div>
        </div>
    </div>
</div>

Note that I'm using SCSS, bootstrap 3.3.7, and did not make any additional edits to the _modals.scss file that _bootstrap.scss imports. The CSS below is added to an additional SCSS file and imported AFTER _bootstrap.scss.

It is also important to note that the original bootstrap styles for .modal-dialog is not set for the default 992px breakpoint, only as high as the 768px breakpoint (which has a hard set width applied width: 600px;, hence why I overrode it w/ width: auto;.

@media (min-width: $screen-sm-min) { // this is the 768px breakpoint
    .modal-dialog {
        max-width: 600px;
        width: auto;
    }
}

@media (min-width: $screen-md-min) { // this is the 992px breakpoint
    .modal-dialog { 
        max-width: 800px;
    }
}

Example below of modal being responsive with an image.

enter image description here

SQL: IF clause within WHERE clause

You want the CASE statement

WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END

Limit the output of the TOP command to a specific process name

Suppose .. if we have more than 20 process running on the server with the same name ... this will not help

top -p pgrep oracle | head -n 20 | tr "\\n" "," | sed 's/,$//'

It will try to list and provide real time output of 20 process where we have good chance of missing other prcesses which consumes more resource ....

I am still looking for better option on this

How to change the Text color of Menu item in Android?

in Kotlin I wrote these extensions:

fun MenuItem.setTitleColor(color: Int) {
    val hexColor = Integer.toHexString(color).toUpperCase().substring(2)
    val html = "<font color='#$hexColor'>$title</font>"
    this.title = html.parseAsHtml()
}           



@Suppress("DEPRECATION")                                                                        
fun String.parseAsHtml(): Spanned {                                                             
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {                                
        Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)                                         
    } else {                                                                                    
        Html.fromHtml(this)                                                                     
    }                                                                                           
}  

and used like this:

menu.findItem(R.id.main_settings).setTitleColor(Color.RED)

Play audio with Python

Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.

pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()

You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation

How to include a Font Awesome icon in React's render()

In my case I was following the documentation for react-fontawesome package, but they aren't clear about how to call the icon when setting the icons into the library

this is was what I was doing:

App.js file

import {faCoffee} from "@fortawesome/pro-light-svg-icons";
library.add(faSearch, faFileSearch, faCoffee);

Component file

<FontAwesomeIcon icon={"coffee"} />

But I was getting this error

enter image description here Then I added the alias when passing the icon prop like:

<FontAwesomeIcon icon={["fal", "coffee"]} />

And it is working, you can find the prefix value in the icon.js file, in my case was: faCoffee.js

Join String list elements with a delimiter in one step

If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

Export javascript data to CSV file without server interaction

There's always the HTML5 download attribute :

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.

If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");
var a         = document.createElement('a');
a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
a.target      = '_blank';
a.download    = 'myFile.csv';

document.body.appendChild(a);
a.click();

FIDDLE

Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).

An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.


Apparently there is a hack for IE10 and IE11, which doesn't support the download attribute (Edge does however).

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvString]);
    window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
    var a         = document.createElement('a');
    a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
    a.target      = '_blank';
    a.download    = 'myFile.csv';
    document.body.appendChild(a);
    a.click();
}

Space between border and content? / Border distance from content?

Just wrap another div around it, which has the border and the padding you want.

Which version of MVC am I using?

Open web.config file and find the System.Web.Mvc assembly definition:

assembly="System.Web.Mvc, Version=3.0.0.0 ..."

It's an MVC3 as you see. Via web you can use MvcDiagnostics which is similar to phpinfo() functionality in PHP.

Reset push notification settings for app

Another just for testing solution to this is by simply changing your bundle id. Just don't forget to change it back once you're done!

len() of a numpy array in python

Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.

How do you change video src using jQuery?

The easiest way is using autoplay.

<video autoplay></video>

When you change src through javascript you don't need to mention load().

Running multiple commands in one line in shell

Another option is typing Ctrl+V Ctrl+J at the end of each command.

Example (replace # with Ctrl+V Ctrl+J):

$ echo 1#
echo 2#
echo 3

Output:

1
2
3

This will execute the commands regardless if previous ones failed.

Same as: echo 1; echo 2; echo 3

If you want to stop execution on failed commands, add && at the end of each line except the last one.

Example (replace # with Ctrl+V Ctrl+J):

$ echo 1 &&#
failed-command &&#
echo 2

Output:

1
failed-command: command not found

In zsh you can also use Alt+Enter or Esc+Enter instead of Ctrl+V Ctrl+J

Select a Column in SQL not in Group By

The direct answer is that you can't. You must select either an aggregate or something that you are grouping by.

So, you need an alternative approach.

1). Take you current query and join the base data back on it

SELECT
  cpe.*
FROM
  Filteredfmgcms_claimpaymentestimate cpe
INNER JOIN
  (yourQuery) AS lookup
    ON  lookup.MaxData           = cpe.createdOn
    AND lookup.fmgcms_cpeclaimid = cpe.fmgcms_cpeclaimid

2). Use a CTE to do it all in one go...

WITH
  sequenced_data AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARITION BY fmgcms_cpeclaimid ORDER BY CreatedOn DESC) AS sequence_id
  FROM
    Filteredfmgcms_claimpaymentestimate
  WHERE
    createdon < 'reportstartdate'
)
SELECT
  *
FROM
  sequenced_data
WHERE
  sequence_id = 1

NOTE: Using ROW_NUMBER() will ensure just one record per fmgcms_cpeclaimid. Even if multiple records are tied with the exact same createdon value. If you can have ties, and want all records with the same createdon value, use RANK() instead.

Characters allowed in GET parameter

I did a test using the Chrome address bar and a $QUERY_STRING in bash, and observed the following:

~!@$%^&*()-_=+[{]}\|;:',./? and grave (backtick) are passed through as plaintext.

, ", < and > are converted to %20, %22, %3C and %3E respectively.

# is ignored, since it is used by ye olde anchor.

Personally, I'd say bite the bullet and encode with base64 :)

How to nicely format floating numbers to string without unnecessary decimal 0's

public static String fmt(double d) {
    String val = Double.toString(d);
    String[] valArray = val.split("\\.");
    long valLong = 0;
    if(valArray.length == 2) {
        valLong = Long.parseLong(valArray[1]);
    }
     if (valLong == 0)
        return String.format("%d", (long) d);
    else
        return String.format("%s", d);
}

I had to use this because d == (long)d was giving me violation in a SonarQube report.

How to convert NSDate into unix timestamp iphone sdk?

If you want to store these time in a database or send it over the server...best is to use Unix timestamps. Here's a little snippet to get that:

+ (NSTimeInterval)getUTCFormateDate{

    NSDateComponents *comps = [[NSCalendar currentCalendar] 
                               components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit 
                               fromDate:[NSDate date]];
    [comps setHour:0];
    [comps setMinute:0];    
    [comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];

    return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];  
}

changing permission for files and folder recursively using shell command in mac

I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:

find . -type d -exec chmod 755 {} \+

but this also does the same thing:

chmod 755 `find . -type d`

and so does this:

chmod 755 $(find . -type d)

The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.

So I think in your case that the following will do what you want.

chmod 777 $(find "/Users/Test/Desktop/PATH")

Marquee text in Android

To get this to work, I had to use ALL three of the things (ellipsize, selected, and singleLine) mentioned already:

TextView tv = (TextView)findViewById(R.id.someTextView);
tv.setSelected(true);
tv.setEllipsize(TruncateAt.MARQUEE);
tv.setSingleLine(true):

How to correctly dismiss a DialogFragment?

I found that when my fragment was defined in the navigation graph with a <fragment> tag (for a full screen dialogfragment), the dialogfragment would not dismiss with the dismiss() command. Instead, I had to pop the back stack:

findNavController(getActivity(), R.id.nav_host_fragment).popBackStack();

However, if the same dialogfragment was defined in the navigation graph with a <dialog> tag, dismiss() works fine.

Using git commit -a with vim

See this thread for an explanation: VIM for Windows - What do I type to save and exit from a file?

As I wrote there: to learn Vimming, you could use one of the quick reference cards:

Also note How can I set up an editor to work with Git on Windows? if you're not comfortable in using Vim but want to use another editor for your commit messages.

If your commit message is not too long, you could also type

git commit -a -m "your message here"

how to inherit Constructor from super class to sub class

Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.

Here is an example of how this works:

class Foo {
    Foo(String str) { }
}

class Bar extends Foo {
    Bar(String str) {
        // Here I am explicitly calling the superclass 
        // constructor - since constructors are not inherited
        // you must chain them like this.
        super(str);
    }
}

Display encoded html with razor

Use Html.Raw(). Phil Haack posted a nice syntax guide at http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx.

<div class='content'>
    @Html.Raw( Model.Content )
</div>

What does cmd /C mean?

The part you should be interested in is the /? part, which should solve most other questions you have with the tool.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cmd /?
Starts a new instance of the Windows XP command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

Get selected row item in DataGrid WPF

Just discovered this one after i tried Fara's answer but it didn't work on my project. Just drag the column from the Data Sources window, and drop to the Label or TextBox.

Sublime Text 2: How do I change the color that the row number is highlighted?

If you have SublimeLinter installed, your theme (at least it ST3) may end up in .../Packages/User/SublimeLinter/[ your-chosen-theme ]

As mentioned above - find the nested 'settings' dict and edit or add the 'lineHighlight' entry with your desired #RRGGBB or #RRGGBBAA. I like #0000AA99 when on a black(ish) background.

Handy tool if you do not know your color combinations: RGBtoHEX and HEXtoRGB

Private Variables and Methods in Python

Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:

>>> class A(object):
...     def __foo(self):
...         pass
... 
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()

So therefore __ prefix is useful when you need the mangling to occur, for example to not clash with names up or below inheritance chain. For other uses, single underscore would be better, IMHO.

EDIT, regarding confusion on __, PEP-8 is quite clear on that:

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

So if you don't expect subclass to accidentally re-define own method with same name, don't use it.

How can I connect to Android with ADB over TCP?

To switch between TCP and USB modes with just one command, you can add this to /init.rc:

on property:service.adb.tcp.port=*
    restart adbd

on property:service.adb.tcp.enable=1
    setprop service.adb.tcp.port 5555

on property:service.adb.tcp.enable=0
    setprop service.adb.tcp.port -1

And now you can use property service.adb.tcp.enable to enable or disable listening on port 5555. Run netstat to check whether it's listening. As you can see it will also trigger if you do wish to change service.adb.tcp.port manually.

What difference does .AsNoTracking() make?

No Tracking LINQ to Entities queries

Usage of AsNoTracking() is recommended when your query is meant for read operations. In these scenarios, you get back your entities but they are not tracked by your context.This ensures minimal memory usage and optimal performance

Pros

  1. Improved performance over regular LINQ queries.
  2. Fully materialized objects.
  3. Simplest to write with syntax built into the programming language.

Cons

  1. Not suitable for CUD operations.
  2. Certain technical restrictions, such as: Patterns using DefaultIfEmpty for OUTER JOIN queries result in more complex queries than simple OUTER JOIN statements in Entity SQL.
  3. You still can’t use LIKE with general pattern matching.

More info available here:

Performance considerations for Entity Framework

Entity Framework and NoTracking

How to reliably open a file in the same directory as a Python script

I always use:

__location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))

The join() call prepends the current working directory, but the documentation says that if some path is absolute, all other paths left of it are dropped. Therefore, getcwd() is dropped when dirname(__file__) returns an absolute path.

Also, the realpath call resolves symbolic links if any are found. This avoids troubles when deploying with setuptools on Linux systems (scripts are symlinked to /usr/bin/ -- at least on Debian).

You may the use the following to open up files in the same folder:

f = open(os.path.join(__location__, 'bundled-resource.jpg'))
# ...

I use this to bundle resources with several Django application on both Windows and Linux and it works like a charm!

Convert string to title case with JavaScript

My list is based on three quick searches. One for a list of words not to be capitalized, and one for a full list of prepositions.

One final search made the suggestion that prepositions 5 letters or longer should be capitalized, which is something I liked. My purpose is for informal use. I left 'without' in their, because it's the obvious counterpart to with.

So it capitalizes acronyms, the first letter of the title, and the first letter of most words.

It is not intended to handle words in caps-lock. I wanted to leave those alone.

_x000D_
_x000D_
function camelCase(str) {_x000D_
  return str.replace(/((?:^|\.)\w|\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\b)\w)/g, function(character) {_x000D_
  return character.toUpperCase();_x000D_
})}_x000D_
    _x000D_
console.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));
_x000D_
_x000D_
_x000D_

How to get input type using jquery?

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
          $(".show-pwd").click(function(){
          alert();
            var x = $("#myInput");
            if (x[0].type === "password") {
              x[0].type = "text";
            } else {
              x[0].type = "password";
            }
          });
        });
    </script>
</head>

<body>
    <p>Click the radio button to toggle between password visibility:</p>Password:
    <input type="password" value="FakePSW" id="myInput">
    <br>
    <br>
    <input type="checkbox" class="show-pwd">Show Password</body>

</html>

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Edit the file xampp/mysql/bin/my.ini

Add

skip-grant-tables

under [mysqld]

OrderBy descending in Lambda expression?

Try this another way:

var qry = Employees
          .OrderByDescending (s => s.EmpFName)
          .ThenBy (s => s.Address)
          .Select (s => s.EmpCode);

Queryable.ThenBy

Qt: How do I handle the event of the user pressing the 'X' (close) button?

Well, I got it. One way is to override the QWidget::closeEvent(QCloseEvent *event) method in your class definition and add your code into that function. Example:

class foo : public QMainWindow
{
    Q_OBJECT
private:
    void closeEvent(QCloseEvent *bar);
    // ...
};


void foo::closeEvent(QCloseEvent *bar)
{
    // Do something
    bar->accept();
}

What is the difference between SessionState and ViewState?

Usage: If you're going to store information that you want to access on different web pages, you can use SessionState

If you want to store information that you want to access from the same page, then you can use Viewstate

Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.

The SessionState will clear in the following conditions

  1. Cleared by programmer
  2. Cleared by user
  3. Timeout

Flatten nested dictionaries, compressing keys

Variation of this Flatten nested dictionaries, compressing keys with max_level and custom reducer.

  def flatten(d, max_level=None, reducer='tuple'):
      if reducer == 'tuple':
          reducer_seed = tuple()
          reducer_func = lambda x, y: (*x, y)
      else:
          raise ValueError(f'Unknown reducer: {reducer}')

      def impl(d, pref, level):
        return reduce(
            lambda new_d, kv:
                (max_level is None or level < max_level)
                and isinstance(kv[1], dict)
                and {**new_d, **impl(kv[1], reducer_func(pref, kv[0]), level + 1)}
                or {**new_d, reducer_func(pref, kv[0]): kv[1]},
                d.items(),
            {}
        )

      return impl(d, reducer_seed, 0)

How do I change db schema to dbo

Way to do it for an individual thing:

alter schema dbo transfer jonathan.MovieData

Change default date time format on a single database in SQL Server

You do realize that format has nothing to do with how SQL Server stores datetime, right?

You can use set dateformat for each session. There is no setting for database only.

If you use parameters for data insert or update or where filtering you won't have any problems with that.

Calculating Time Difference

from time import time

start_time = time()
...

end_time = time()
seconds_elapsed = end_time - start_time

hours, rest = divmod(seconds_elapsed, 3600)
minutes, seconds = divmod(rest, 60)

Format Float to n decimal places

You may also pass the float value, and use:

String.format("%.2f", floatValue);

Documentation

Calculate the display width of a string in Java

I personally was searching for something to let me compute the multiline string area, so I could determine if given area is big enough to print the string - with preserving specific font.

private static Hashtable hash = new Hashtable();
private Font font;
private LineBreakMeasurer lineBreakMeasurer;
private int start, end;

public PixelLengthCheck(Font font) {
    this.font = font;
}

public boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {
    AttributedString attributedString = new AttributedString(textToMeasure, hash);
    attributedString.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator attributedCharacterIterator =
            attributedString.getIterator();
    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();

    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
            new FontRenderContext(null, false, false));

    float width = (float) areaToFit.width;
    float height = 0;
    lineBreakMeasurer.setPosition(start);

    while (lineBreakMeasurer.getPosition() < end) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
        height += textLayout.getAscent();
        height += textLayout.getDescent() + textLayout.getLeading();
    }

    boolean res = height <= areaToFit.getHeight();

    return res;
}

DBCC CHECKIDENT Sets Identity to 0

Change statement to

  DBCC CHECKIDENT('TableName', RESEED, 1)

This will start from 2 (or 1 when you recreate table), but it will never be 0.

Artisan migrate could not find driver

In Windows and PHP 7.4.5 go to php.ini and uncomment this line

extension=pdo_mysql

Eclipse: All my projects disappeared from Project Explorer

I had the same problem in Aptana, all of a sudden my projects were gone. Solved it by going to the drop-down menu in Project Explorer and going Top Level Elements -> Projects.

svn list of files that are modified in local copy

this should do it in Windows: svn stat | find "M"

How to search contents of multiple pdf files?

I made this destructive small script. Have fun with it.

function pdfsearch()
{
    find . -iname '*.pdf' | while read filename
    do
        #echo -e "\033[34;1m// === PDF Document:\033[33;1m $filename\033[0m"
        pdftotext -q -enc ASCII7 "$filename" "$filename."; grep -s -H --color=always -i $1 "$filename."
        # remove it!  rm -f "$filename."
    done
}

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Why do we always prefer using parameters in SQL statements?

You are right, this is related to SQL injection, which is a vulnerability that allows a malicioius user to execute arbitrary statements against your database. This old time favorite XKCD comic illustrates the concept:

Her daughter is named Help I'm trapped in a driver's license factory.


In your example, if you just use:

var query = "SELECT empSalary from employee where salary = " + txtSalary.Text;
// and proceed to execute this query

You are open to SQL injection. For example, say someone enters txtSalary:

1; UPDATE employee SET salary = 9999999 WHERE empID = 10; --
1; DROP TABLE employee; --
// etc.

When you execute this query, it will perform a SELECT and an UPDATE or DROP, or whatever they wanted. The -- at the end simply comments out the rest of your query, which would be useful in the attack if you were concatenating anything after txtSalary.Text.


The correct way is to use parameterized queries, eg (C#):

SqlCommand query =  new SqlCommand("SELECT empSalary FROM employee 
                                    WHERE salary = @sal;");
query.Parameters.AddWithValue("@sal", txtSalary.Text);

With that, you can safely execute the query.

For reference on how to avoid SQL injection in several other languages, check bobby-tables.com, a website maintained by a SO user.

Difference between parameter and argument

Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

double sqrt(double x)
{
    ...
    return x;
}

void other(void)
{
     double two = sqrt(2.0);
}

Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

The terms are often used at least somewhat interchangeably.

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

Why doesn't os.path.join() work in this case?

Note that a similar issue can bite you if you use os.path.join() to include an extension that already includes a dot, which is what happens automatically when you use os.path.splitext(). In this example:

components = os.path.splitext(filename)
prefix = components[0]
extension = components[1]
return os.path.join("avatars", instance.username, prefix, extension)

Even though extension might be .jpg you end up with a folder named "foobar" rather than a file called "foobar.jpg". To prevent this you need to append the extension separately:

return os.path.join("avatars", instance.username, prefix) + extension

How do you programmatically set an attribute?

let x be an object then you can do it two ways

x.attr_name = s 
setattr(x, 'attr_name', s)

How do I read the contents of a Node.js stream into a string variable?

What about something like a stream reducer ?

Here is an example using ES6 classes how to use one.

var stream = require('stream')

class StreamReducer extends stream.Writable {
  constructor(chunkReducer, initialvalue, cb) {
    super();
    this.reducer = chunkReducer;
    this.accumulator = initialvalue;
    this.cb = cb;
  }
  _write(chunk, enc, next) {
    this.accumulator = this.reducer(this.accumulator, chunk);
    next();
  }
  end() {
    this.cb(null, this.accumulator)
  }
}

// just a test stream
class EmitterStream extends stream.Readable {
  constructor(chunks) {
    super();
    this.chunks = chunks;
  }
  _read() {
    this.chunks.forEach(function (chunk) { 
        this.push(chunk);
    }.bind(this));
    this.push(null);
  }
}

// just transform the strings into buffer as we would get from fs stream or http request stream
(new EmitterStream(
  ["hello ", "world !"]
  .map(function(str) {
     return Buffer.from(str, 'utf8');
  })
)).pipe(new StreamReducer(
  function (acc, v) {
    acc.push(v);
    return acc;
  },
  [],
  function(err, chunks) {
    console.log(Buffer.concat(chunks).toString('utf8'));
  })
);

Command not found error in Bash variable assignment

I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.

#!/bin/bash
STR = "Hello World"
echo $STR

Didn't work because of the spaces around the equal sign. If you were to run...

#!/bin/bash
STR="Hello World"
echo $STR

It would work

Add php variable inside echo statement as href link address?

you can either use

echo '<a href="'.$link_address.'">Link</a>';

or

echo "<a href=\"$link_address\">Link</a>';

if you use double quotes you can insert the variable into the string and it will be parsed.

How to replace part of string by position?

Like other have mentioned the Substring() function is there for a reason:

static void Main(string[] args)
{
    string input = "ABCDEFGHIJ";

    string output = input.Overwrite(3, "ZX"); // 4th position has index 3
    // ABCZXFGHIJ
}

public static string Overwrite(this string text, int position, string new_text)
{
    return text.Substring(0, position) + new_text + text.Substring(position + new_text.Length);
}

Also I timed this against the StringBuilder solution and got 900 tics vs. 875. So it is slightly slower.

symfony2 twig path with parameter url creation

Make sure your routing.yml file has 'id' specified in it. In other words, it should look like:

_category:
    path: /category/{id}

Convert a string to a datetime

Try to use DateTime.ParseExact method, in which you can specify both of datetime mask and original parsed string. You can read about it here: MSDN: DateTime.ParseExact

How can I insert data into Database Laravel?

The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:

Route::post('test/register', array('uses'=>'TestController@create'));

Also, you need to hash your passwords:

public function create()
{
    $user = new User;

    $user->username = Input::get('username');
    $user->email = Input::get('email');
    $user->password = Hash::make(Input::get('password'));
    $user->save();

    return Redirect::back();
}

And I removed the line:

$user= Input::all();

Because in the next command you replace its contents with

$user = new User;

To debug your Input, you can, in the first line of your controller:

dd( Input::all() );

It will display all fields in the input.

Convert number of minutes into hours & minutes using PHP

Thanks to @Martin_Bean and @Mihail Velikov answers. I just took their answer snippet and added some modifications to check,

  1. If only Hours only available and minutes value empty, then it will display only hours.

  2. Same if only Minutes only available and hours value empty, then it will display only minutes.

  3. If minutes = 60, then it will display as 1 hour. Same if minute = 1, the output will be 1 minute.

Changes and edits are welcomed. Thanks. Here is the code.

function convertToHoursMins($time) {

            $hours    = floor($time / 60);
            $minutes  = ($time % 60);


            if($minutes == 0){

                if($hours == 1){

                    $output_format = '%02d hour ';

                }else{

                    $output_format = '%02d hours ';
                }


                $hoursToMinutes = sprintf($output_format, $hours);

            }else if($hours == 0){

                if ($minutes < 10) {
                        $minutes = '0' . $minutes;
                }

                if($minutes == 1){

                    $output_format  = ' %02d minute ';

                }else{

                    $output_format  = ' %02d minutes ';
                }

                $hoursToMinutes = sprintf($output_format,  $minutes);

            }else {

                if($hours == 1){

                    $output_format = '%02d hour %02d minutes';

                }else{

                    $output_format = '%02d hours %02d minutes';
                }

                $hoursToMinutes = sprintf($output_format, $hours, $minutes);
            }

            return $hoursToMinutes;
        }`

How can I run a html file from terminal?

Skip reading the html and use curl to POST whatever form data you want to submit to the server.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

After battling with this for a day on a new machine I came across the following links. I was missing the rewrite modules. This fixed everything.

http://forums.iis.net/t/1176834.aspx

http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/

MySQL Error #1133 - Can't find any matching row in the user table

If you're using PHPMyAdmin you have to be logged in as root to be able to change root password. in user put root than leave password blank than change your password.

Scrolling an iframe with JavaScript?

Or, you can set a margin-top on the iframe...a bit of a hack but works in FF so far.

#frame {
margin-top:200px;
}

Twig for loop for arrays with keys

There's this example in the SensioLab page on the for tag:

<h1>Members</h1>
<ul>
    {% for key, user in users %}
        <li>{{ key }}: {{ user.username|e }}</li>
    {% endfor %}
</ul>

http://twig.sensiolabs.org/doc/tags/for.html#iterating-over-keys

How to loop over a Class attributes in Java?

Here is a solution which sorts the properties alphabetically and prints them all together with their values:

public void logProperties() throws IllegalArgumentException, IllegalAccessException {
  Class<?> aClass = this.getClass();
  Field[] declaredFields = aClass.getDeclaredFields();
  Map<String, String> logEntries = new HashMap<>();

  for (Field field : declaredFields) {
    field.setAccessible(true);

    Object[] arguments = new Object[]{
      field.getName(),
      field.getType().getSimpleName(),
      String.valueOf(field.get(this))
    };

    String template = "- Property: {0} (Type: {1}, Value: {2})";
    String logMessage = System.getProperty("line.separator")
            + MessageFormat.format(template, arguments);

    logEntries.put(field.getName(), logMessage);
  }

  SortedSet<String> sortedLog = new TreeSet<>(logEntries.keySet());

  StringBuilder sb = new StringBuilder("Class properties:");

  Iterator<String> it = sortedLog.iterator();
  while (it.hasNext()) {
    String key = it.next();
    sb.append(logEntries.get(key));
  }

  System.out.println(sb.toString());
}

How do I define a method in Razor?

You can simply declare them as local functions in a razor block (i.e. @{}).

@{
    int Add(int x, int y)
    {
        return x + y;
    }
}

<div class="container">
    <p>
        @Add(2, 5)
    </p>
</div>

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Why is Thread.Sleep so harmful

The problems with calling Thread.Sleep are explained quite succinctly here:

Thread.Sleep has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.

Thread.Sleep(n) means block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more than n milliseconds. The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be. So, Thread.Sleep is pointless for timing.

Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.

The preferred solution: WaitHandles

The most-made-mistake is using Thread.Sleep with a while-construct (demo and answer, nice blog-entry)

EDIT:
I would like to enhance my answer:

We have 2 different use-cases:

  1. We are waiting because we know a specific timespan when we should continue (use Thread.Sleep, System.Threading.Timer or alikes)

  2. We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!

My answer mainly covers use-case 2

How to change options of <select> with jQuery?

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
    "Option 1":"option-1",
    "Option 2":"option-2"
};

var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
    $el.append($("<option></option>")
    .attr("value", value).text(key));
});

How to change plot background color?

Something like this? Use the axisbg keyword to subplot:

>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')

(Granted, not a scatter plot, and not a black background.)

enter image description here

javascript setTimeout() not working

Please change your code as follows:

<script>
    var button = document.getElementById("reactionTester");
    var start = document.getElementById("start");
    function init() {
        var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
        setTimeout(startTimer,startInterval); 
    }
    function startTimer(){
        document.write("hey");
    }
</script>

See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.

Raise an event whenever a property's value changed?

Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.

Cannot kill Python script with Ctrl-C

Ctrl+C terminates the main thread, but because your threads aren't in daemon mode, they keep running, and that keeps the process alive. We can make them daemons:

f = FirstThread()
f.daemon = True
f.start()
s = SecondThread()
s.daemon = True
s.start()

But then there's another problem - once the main thread has started your threads, there's nothing else for it to do. So it exits, and the threads are destroyed instantly. So let's keep the main thread alive:

import time
while True:
    time.sleep(1)

Now it will keep print 'first' and 'second' until you hit Ctrl+C.

Edit: as commenters have pointed out, the daemon threads may not get a chance to clean up things like temporary files. If you need that, then catch the KeyboardInterrupt on the main thread and have it co-ordinate cleanup and shutdown. But in many cases, letting daemon threads die suddenly is probably good enough.

Swift presentViewController

Swift 3 and Swift 4

let vc = self.storyboard?.instantiateViewController(withIdentifier: "idMyViewControllerName") as! MyViewControllerName
self.present(vc, animated: true, completion: nil)

How to pass parameters to a partial view in ASP.NET MVC?

Just:

@Html.Partial("PartialName", Model);

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Changing tab bar item image and text color iOS

Year: 2020 iOS 13.3

Copy below codes to AppDelegate.swift -> func didFinishLaunchingWithOptions

//Set Tab bar text/item fonts and size
let fontAttributes = [NSAttributedString.Key.font: UIFont(name: "YourFontName", size: 12.0)!]
UITabBarItem.appearance().setTitleTextAttributes(fontAttributes, for: .normal)
//Set Tab bar text/item color
UITabBar.appearance().tintColor = UIColor.init(named: "YourColorName")

How to get exception message in Python properly

from traceback import format_exc


try:
    fault = 10/0
except ZeroDivision:
    print(format_exc())

Another possibility is to use the format_exc() method from the traceback module.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

How do I return a char array from a function?

As you're using C++ you could use std::string.

AWK: Access captured group from line pattern

You can use GNU awk:

$ cat hta
RewriteCond %{HTTP_HOST} !^www\.mysite\.net$
RewriteRule (.*) http://www.mysite.net/$1 [R=301,L]

$ gawk 'match($0, /.*(http.*?)\$/, m) { print m[1]; }' < hta
http://www.mysite.net/

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

New to MongoDB Can not run command mongo

create folder structure data/db in the working directory and then starting up mongodb using "mongod --dbpath data/db" works just fine

Get type of all variables

lapply(your_dataframe, class) gives you something like:

$tikr [1] "factor"

$Date [1] "Date"

$Open [1] "numeric"

$High [1] "numeric"

... etc.

Change status bar color with AppCompat ActionBarActivity

There are various ways of changing the status bar color.

1) Using the styles.xml. You can use the android:statusBarColor attribute to do this the easy but static way.

Note: You can also use this attribute with the Material theme.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>

2) You can get it done dynamically using the setStatusBarColor(int) method in the Window class. But remember that this method is only available for API 21 or higher. So be sure to check that, or your app will surely crash in lower devices.

Here is a working example of this method.

if (Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(getResources().getColor(R.color.primaryDark));
}

where primaryDark is the 700 tint of the primary color I am using in my app. You can define this color in the colors.xml file.

Do give it a try and let me know if you have any questions. Hope it helps.

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

Exchange rate from Euro to NOK on the first of January 2016:

=INDEX(GOOGLEFINANCE("CURRENCY:EURNOK"; "close"; DATE(2016;1;1)); 2; 2)

The INDEX() function is used because GOOGLEFINANCE() function actually prints out in 4 separate cells (2x2) when you call it with these arguments, with it the result will only be one cell.

Best way to read a large file into a byte array in C#?

Use the BufferedStream class in C# to improve performance. A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Buffers improve read and write performance.

See the following for a code example and additional explanation: http://msdn.microsoft.com/en-us/library/system.io.bufferedstream.aspx

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

StringBuilder b = new StringBuilder();

Scanner s = new Scanner(System.in);
String n = s.nextLine();

for(int i = 0; i < n.length(); i++) {
    char c = n.charAt(i);

    if(Character.isLowerCase(c) == true) {
        b.append(String.valueOf(c).toUpperCase());
    }
    else {
        b.append(String.valueOf(c).toLowerCase());
    }
}

System.out.println(b);

Using str_replace so that it only acts on the first match?

For Loop Solution

<?php
echo replaceFirstMatchedChar("&", "?", "/property/details&id=202&test=123#tab-6");

function replaceFirstMatchedChar($searchChar, $replaceChar, $str)
{
    for ($i = 0; $i < strlen($str); $i++) {

        if ($str[$i] == $searchChar) {
            $str[$i] = $replaceChar;
            break;
        }
    }
    return $str;
}

How to convert an array into an object using stdClass()

or you can use this thing

$arr = [1,2,3];
$obj = json_decode(json_encode($arr));
print_r($obj);

C#: Looping through lines of multiline string

Here's a quick code snippet that will find the first non-empty line in a string:

string line1;
while (
    ((line1 = sr.ReadLine()) != null) &&
    ((line1 = line1.Trim()).Length == 0)
)
{ /* Do nothing - just trying to find first non-empty line*/ }

if(line1 == null){ /* Error - no non-empty lines in string */ }

How do I set the request timeout for one controller action in an asp.net mvc application

<location path="ControllerName/ActionName">
    <system.web>
        <httpRuntime executionTimeout="1000"/>
    </system.web>
</location>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

I had to move my routes on top of other routes that are catching the route parameters:

// require express and express router

const express = require("express");
const router = express.Router();

// move this `/post/like` route on top

router.put("/post/like", requireSignin, like);

// keep the route with route parameter `/:postId` below regular routes

router.get("/post/:postId", singlePost);

NameError: global name 'xrange' is not defined in Python 3

add xrange=range in your code :) It works to me.

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

Bootstrap 4 Center Vertical and Horizontal Alignment

flexbox can help you. info here

<div class="d-flex flex-row justify-content-center align-items-center" style="height: 100px;">
    <div class="p-2">
     1
    </div>
    <div class="p-2">
     2
    </div>
</div>

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

Compare a string using sh shell

I had this same problem, do this

if [ 'xyz' = 'abc' ]; then
  echo "match"
fi

Notice the whitespace. It is important that you use a whitespace in this case after and before the = sign.

Check out "Other Comparison Operators".

Drop all data in a pandas dataframe

You need to pass the labels to be dropped.

df.drop(df.index, inplace=True)

By default, it operates on axis=0.

You can achieve the same with

df.iloc[0:0]

which is much more efficient.

How to get the hostname of the docker host from inside a docker container on that host without env vars

I know it's an old question, but I needed this solution too, and I acme with another solution.

I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:

HOST=`hostname --fqdn`

Then, I used it across my entrypoint script:

echo "Value: $HOST"

Hope this helps

How to write new line character to a file in Java

Put this code wherever you want to insert a new line:

bufferedWriter.newLine();

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

It's been some time since I've used Matlab, but from memory it does provide (albeit with extra plugins) the ability to generate source to allow you to realise your algorithm on a DSP.

Since python is a general purpose programming language there is no reason why you couldn't do everything in python that you can do in matlab. However, matlab does provide a number of other tools - eg. a very broad array of dsp features, a broad array of S and Z domain features.

All of these could be hand coded in python (since it's a general purpose language), but if all you're after is the results perhaps spending the money on Matlab is the cheaper option?

These features have also been tuned for performance. eg. The documentation for Numpy specifies that their Fourier transform is optimised for power of 2 point data sets. As I understand Matlab has been written to use the most efficient Fourier transform to suit the size of the data set, not just power of 2.

edit: Oh, and in Matlab you can produce some sensational looking plots very easily, which is important when you're presenting your data. Again, certainly not impossible using other tools.

EXTRACT() Hour in 24 Hour format

select to_char(tran_datetime,'HH24') from test;

TO_CHAR(tran_datetime,'HH24')
------------------
16      

Why does my 'git branch' have no master?

If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status from your terminal you'd see which location you are. In some cases, you'd see origin/main.

If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.

example: git push heroku main

Maven Install on Mac OS X

Two ways to install Maven

Before installing maven check mvn -version to make sure maven is not install in system

Method 1:

brew install maven

Method 2:

  1. go to https://maven.apache.org/download.cgi
  2. Select any of Binary link
  3. Unzip the link
  4. Move to application folder
  5. Update .bash profile with exports
  6. run mvn -version

`export const` vs. `export default` in ES6

It's a named export vs a default export. export const is a named export that exports a const declaration or declarations.

To emphasize: what matters here is the export keyword as const is used to declare a const declaration or declarations. export may also be applied to other declarations such as class or function declarations.

Default Export (export default)

You can have one default export per file. When you import you have to specify a name and import like so:

import MyDefaultExport from "./MyFileWithADefaultExport";

You can give this any name you like.

Named Export (export)

With named exports, you can have multiple named exports per file. Then import the specific exports you want surrounded in braces:

// ex. importing multiple exports:
import { MyClass, MyOtherClass } from "./MyClass";
// ex. giving a named import a different name by using "as":
import { MyClass2 as MyClass2Alias } from "./MyClass2";

// use MyClass, MyOtherClass, and MyClass2Alias here

Or it's possible to use a default along with named imports in the same statement:

import MyDefaultExport, { MyClass, MyOtherClass} from "./MyClass";

Namespace Import

It's also possible to import everything from the file on an object:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass, MyClasses.MyOtherClass and MyClasses.default here

Notes

  • The syntax favours default exports as slightly more concise because their use case is more common (See the discussion here).
  • A default export is actually a named export with the name default so you are able to import it with a named import:

    import { default as MyDefaultExport } from "./MyFileWithADefaultExport";
    

Decimal number regular expression, where digit after decimal is optional

^\d+(()|(\.\d+)?)$

Came up with this. Allows both integer and decimal, but forces a complete decimal (leading and trailing numbers) if you decide to enter a decimal.

How to drop rows from pandas data frame that contains a particular string in a particular column?

Slight modification to the code. Having na=False will skip empty values. Otherwise you can get an error TypeError: bad operand type for unary ~: float

df[~df.C.str.contains("XYZ", na=False)]

Source: TypeError: bad operand type for unary ~: float

IntelliJ how to zoom in / out

Before User Shift + = or Shift - , you have to first set the key map as mentioned below enter image description here

How to remove part of a string?

Easiest way I think is:

var s = yourString.replace(/.*_/g,"_");

Get the difference between dates in terms of weeks, months, quarters, and years

Here the still lacking lubridate answer (although Gregor's function is built on this package)

The lubridate timespan documentation is very helpful for understanding the difference between periods and duration. I also like the lubridate cheatsheet and this very useful thread

library(lubridate)

dates <- c(dmy('14.01.2013'), dmy('26.03.2014'))

span <- dates[1] %--% dates[2] #creating an interval object

#creating period objects 
as.period(span, unit = 'year') 
#> [1] "1y 2m 12d 0H 0M 0S"
as.period(span, unit = 'month')
#> [1] "14m 12d 0H 0M 0S"
as.period(span, unit = 'day')
#> [1] "436d 0H 0M 0S"

Periods do not accept weeks as units. But you can convert durations to weeks:

as.duration(span)/ dweeks(1)
#makes duration object (in seconds) and divides by duration of a week (in seconds)
#> [1] 62.28571

Created on 2019-11-04 by the reprex package (v0.3.0)

How to print the data in byte array as characters?

If you want to print the bytes as chars you can use the String constructor.

byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));

MySQL SELECT only not null values

I found this solution:

This query select last not null value for each column.

Example


If you have a table:

id|title|body
1 |t1   |b1
2 |NULL |b2
3 |t3   |NULL

you get:

title|body
t3   |b2

Query


SELECT DISTINCT (

  SELECT title
  FROM test
  WHERE title IS NOT NULL 
  ORDER BY id DESC 
  LIMIT 1
) title, (

  SELECT body
  FROM test
  WHERE body IS NOT NULL 
  ORDER BY id DESC 
  LIMIT 1
) body
FROM test

I hope help you.

Why maven? What are the benefits?

Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.

Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.

And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).

So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.

On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.

And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).

Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.

First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.

Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).

So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

SQL Server: use CASE with LIKE

SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname, 
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname