Programs & Examples On #Achartengine

A charting software library for Android applications by Dan Dromereschi.

add maven repository to build.gradle

After

apply plugin: 'com.android.application'

You should add this:

  repositories {
        mavenCentral()
        maven {
            url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
        }
    }

@Benjamin explained the reason.

If you have a maven with authentication you can use:

repositories {
            mavenCentral()
            maven {
               credentials {
                   username xxx
                   password xxx
               }
               url    'http://mymaven/xxxx/repositories/releases/'
            }
}

It is important the order.

Android charting libraries

  • Achartengine: I have used this. Although for real time graph this might not give good performance if you do not tweak properly.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

Read line with Scanner

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

Concat strings by & and + in VB.Net

  • & is only used for string concatenation.
  • + is overloaded to do both string concatenation and arithmetic addition.

The double purpose of + leads to confusion, exactly like that in your question. Especially when Option Strict is Off, because the compiler will add implicit casts on your strings and integers to try to make sense of your code.

My recommendations

  • You should definitely turn Option Strict On, then the compiler will force you to add explicit casts where it thinks they are necessary.
  • You should avoid using + for concatenation because of the ambiguity with arithmetic addition.

Both these recommendations are also in the Microsoft Press book Practical Guidelines And Best Practises for VB and C# (sections 1.16, 21.2)

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

What is the most efficient way to create HTML elements using jQuery?

You'll have to understand that the significance of element creation performance is irrelevant in the context of using jQuery in the first place.

Keep in mind, there's no real purpose of creating an element unless you're actually going to use it.

You may be tempted to performance test something like $(document.createElement('div')) vs. $('<div>') and get great performance gains from using $(document.createElement('div')) but that's just an element that isn't in the DOM yet.

However, in the end of the day, you'll want to use the element anyway so the real test should include f.ex. .appendTo();

Let's see, if you test the following against each other:

var e = $(document.createElement('div')).appendTo('#target');
var e = $('<div>').appendTo('#target');
var e = $('<div></div>').appendTo('#target');
var e = $('<div/>').appendTo('#target');

You will notice the results will vary. Sometimes one way is better performing than the other. And this is only because the amount of background tasks on your computer change over time.

Test yourself here

So, in the end of the day, you do want to pick the smallest and most readable way of creating an element. That way, at least, your script files will be smallest possible. Probably a more significant factor on the performance point than the way of creating an element before you use it in the DOM.

How to change package name of Android Project in Eclipse?

One extremely important notice:

NEVER use a direct package names as in something similar to passing a string value containing the package name. Use the method getPackageName(). This will make the renaming dynamic. Do whatever to reach the method getPackageName().

In Eclipse Juno, the correct way of renaming is:

  1. Go and edit the manifest.
  2. Remove every old package name in the manifest.
  3. Put instead of the old package name, the new package name in every location inside the manifest. You might have classes (Activities that is) that need direct package name references.
  4. Save the manifest.
  5. Then right click the package name inside the project.
  6. Select "Refactor".
  7. Select "Rename".
  8. Type the new package name.
  9. Select "update references".
  10. Press OK and you're done and watch out also what should be done to replace the new name.
  11. Don't forget to also update the layout XML files with the new package name. You might have a custom View. Look for them.

npm start error with create-react-app

As Dan said correctly,

If you see this:

npm ERR! [email protected] start: `react-scripts start`
npm ERR! spawn ENOENT

It just means something went wrong when dependencies were installed the first time.

But I got something slightly different because running npm install -g npm@latest to update npm might sometimes leave you with this error:

npm ERR! code ETARGET
npm ERR! notarget No matching version found for npm@lates
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

so, instead of running npm install -g npm@latest, I suggest running the below steps:

 npm i -g npm //which will also update npm
 rm -rf node_modules/ && npm cache clean // to remove the existing modules and clean the cache.
 npm install //to re-install the project dependencies.

This should get you back on your feet.

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

Bash script prints "Command Not Found" on empty lines

You may want to update you .bashrc and .bash_profile files with aliases to recognize the command you are entering.

.bashrc and .bash_profile files are hidden files probably located on your C: drive where you save your program files.

Fastest way to check if a string is JSON in PHP?

I don't know about performance or elegance of my solution, but it's what I'm using:

if (preg_match('/^[\[\{]\"/', $string)) {
    $aJson = json_decode($string, true);
    if (!is_null($aJson)) {
       ... do stuff here ...
    }
}

Since all my JSON encoded strings start with {" it suffices to test for this with a RegEx. I'm not at all fluent with RegEx, so there might be a better way to do this. Also: strpos() might be quicker.

Just trying to give in my tuppence worth.

P.S. Just updated the RegEx string to /^[\[\{]\"/ to also find JSON array strings. So it now looks for either [" or {" at the beginning of the string.

How to read and write into file using JavaScript?

here's the mozilla proposal

http://www-archive.mozilla.org/js/js-file-object.html

this is implemented with a compilation switch in spidermonkey, and also in adobe's extendscript. Additionally (I think) you get the File object in firefox extensions.

rhino has a (rather rudementary) readFile function https://developer.mozilla.org/en/Rhino_Shell

for more complex file operations in rhino, you can use java.io.File methods.

you won't get any of this stuff in the browser though. For similar functionality in a browser you can use the SQL database functions from HTML5, clientside persistence, cookies, and flash storage objects.

JavaScript: What are .extend and .prototype used for?

  • .extends() create a class which is a child of another class.
    behind the scenes Child.prototype.__proto__ sets its value to Parent.prototype
    so methods are inherited.
  • .prototype inherit features from one to another.
  • .__proto__ is a getter/setter for Prototype.

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

SSIS Excel Connection Manager failed to Connect to the Source

I faced the same issue. I think @Rishit answer helped me. This issue is related to 32 bit/ 64 bit version of driver. I was trying to read .xlsx files to SQL Server tables using SSIS

  • My machine was pre-installed with Office 2016 64 bit on Win 10 machine along with MS Access
  • I was able to read excel 97-2003 (.xls) files using ssis, but unable to connect .xlsx files
  • My requirement was to read .xlsx files
  • Installed AccessDatabaseEngine_X64 to read xlsx, that given me the following error:

enter image description here

  • I uninstalled the AccessDatabaseEngine_X64 and installed AccessDatabaseEngine 32 bit, that resolved the issue

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

You can try,

<div asp-validation-summary="All" class="text-danger"></div>

Best practices for API versioning?

We found it practical and useful to put the version in the URL. It makes it easy to tell what you're using at a glance. We do alias /foo to /foo/(latest versions) for ease of use, shorter / cleaner URLs, etc, as the accepted answer suggests.

Keeping backwards compatibility forever is often cost-prohibitive and/or very difficult. We prefer to give advanced notice of deprecation, redirects like suggested here, docs, and other mechanisms.

Bootstrap table striped: How do I change the stripe background colour?

.table-striped > tbody > tr:nth-child(2n+1) > td, .table-striped > tbody > tr:nth-child(2n+1) > th {
   background-color: red;
}

change this line in bootstrap.css or you could use (odd) or (even) instead of (2n+1)

String comparison - Android

String g1="Male";
String g2="Female";
String salutation="";
String gender="Male";
if(gender.toLowerCase().trim().equals(g1.toLowerCase().trim()));
   salutation ="Mr.";
if(gender.toLowerCase().trim().equals(g2.toLowerCase().trim()));
   salutation ="Ms.";

logger configuration to log to file and print to stdout

For 2.7, try the following:

fh = logging.handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)

Delete a database in phpMyAdmin

Open the Terminal and run

 mysql -u root -p

Password is null or just enter your mysql password

Ater Just Run This Query

 DROP DATABASE DBname;

If you are using phpmyadmin then just run

 DROP DATABASE DBname;

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

From the Help:
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
IsEmpty only returns meaningful information for variants.

To check if a cell is empty, you can use cell(x,y) = "".
You might eventually save time by using Range("X:Y").SpecialCells(xlCellTypeBlanks) or xlCellTypeConstants or xlCellTypeFormulas

How do I copy the contents of one stream to another?

Unfortunately, there is no really simple solution. You can try something like that:

Stream s1, s2;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);
s1.Close(); s2.Close();

But the problem with that that different implementation of the Stream class might behave differently if there is nothing to read. A stream reading a file from a local harddrive will probably block until the read operaition has read enough data from the disk to fill the buffer and only return less data if it reaches the end of file. On the other hand, a stream reading from the network might return less data even though there are more data left to be received.

Always check the documentation of the specific stream class you are using before using a generic solution.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

Regular expression for matching latitude/longitude coordinates?

You can try this:

var latExp = /^(?=.)-?((8[0-5]?)|([0-7]?[0-9]))?(?:\.[0-9]{1,20})?$/;
var lngExp = /^(?=.)-?((0?[8-9][0-9])|180|([0-1]?[0-7]?[0-9]))?(?:\.[0-9]{1,20})?$/;

Response.Redirect to new window

I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes.

$(function () {
    //--- setup click event for elements that use a response.redirect in code behind but should open in a new window
    $(".new-window").on("click", function () {

        //--- change the form's target
        $("#aspnetForm").prop("target", "_blank");

        //--- change the target back after the window has opened
        setTimeout(function () {
            $("#aspnetForm").prop("target", "");
        }, 1);
    });
});

To use, add the class "new-window" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How to make shadow on border-bottom?

I'm a little late on the party, but its actualy possible to emulate borders using a box-shadow

_x000D_
_x000D_
.border {_x000D_
  background-color: #ededed;_x000D_
  padding: 10px;_x000D_
  margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
.border-top {_x000D_
  box-shadow: inset 0 3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-right {_x000D_
  box-shadow: inset -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-bottom {_x000D_
  box-shadow: inset 0 -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-left {_x000D_
  box-shadow: inset 3px 0 0 cornflowerblue;_x000D_
}
_x000D_
<div class="border border-top">border-top</div>_x000D_
<div class="border border-right">border-right</div>_x000D_
<div class="border border-bottom">border-bottom</div>_x000D_
<div class="border border-left">border-left</div>
_x000D_
_x000D_
_x000D_

EDIT: I understood this question wrong, but I will leave the awnser as more people might misunderstand the question and came for the awnser I supplied.

Putting a password to a user in PhpMyAdmin in Wamp

Looks like phpmyadmin's username and password are stored elsewhere ( probably in a custom-defined config file ) in WAMP or there is some additional hashing or ... involved in the process.

So to change currently used default 'config'-file-based password you can browse "<host>/phpmyadmin/user_password.php" using your browser. You'll be prompted to enter your mysql credentials and then you can use the displayed form to change the stored password for the user you logged into previously.

ECMAScript 6 arrow function that returns an object

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

Removing path and extension from filename in PowerShell

There's a handy .NET method for that:

C:\PS> [io.path]::GetFileNameWithoutExtension("c:\temp\myfile.txt")
myfile

Detect whether Office is 32bit or 64bit via the registry

In my tests many of the approaches described here fail, I think because they rely on entries in the Windows registry that turn out to be not reliably present, depending on Office version, how it was installed etc. So a different approach is to not use the registry at all (Ok, so strictly that makes it not an answer to the question as posed), but instead write a script that:

  1. Instantiates Excel
  2. Adds a workbook to that Excel instance
  3. Adds a VBA module to that workbook
  4. Injects a small VBA function that returns the bitness of Office
  5. Calls that function
  6. Cleans up

Here's that approach implemented in VBScript:

Function OfficeBitness()

    Dim VBACode, Excel, Wb, Module, Result

    VBACode = "Function Is64bit() As Boolean" & vbCrLf & _
              "#If Win64 Then" & vbCrLf & _
              "    Is64bit = True" & vbCrLf & _
              "#End If" & vbCrLf & _
              "End Function"

    On Error Resume Next
    Set Excel = CreateObject("Excel.Application")
    Excel.Visible = False
    Set Wb = Excel.Workbooks.Add
    Set Module = Wb.VBProject.VBComponents.Add(1)
    Module.CodeModule.AddFromString VBACode
    Result = Excel.Run("Is64bit")
    Set Module = Nothing
    Wb.Saved = True
    Wb.Close False
    Excel.Quit
    Set Excel = Nothing
    On Error GoTo 0
    If IsEmpty(Result) Then
        OfficeBitness = 0 'Alternatively raise an error here?
    ElseIf Result = True Then
        OfficeBitness = 64
    Else
        OfficeBitness = 32
    End If

End Function

PS. This approach runs more slowly than others here (about 2 seconds on my PC) but it might turn out to be more reliable across different installations and Office versions.

After some months, I've realised there may be a simpler approach, though still one that instantiates an Excel instance. The VBScript is:

Function OfficeBitness()
    Dim Excel
    Set Excel = CreateObject("Excel.Application")
    Excel.Visible = False
    If InStr(Excel.OperatingSystem,"64") > 0 Then
        OfficeBitness = 64
    Else
        OfficeBitness = 32
    End if
    Excel.Quit
    Set Excel = Nothing
End Function

This relies on the fact that Application.OperatingSystem, when called from 32-bit Excel on 64-bit Windows returns Windows (32-bit) NT 10.00 or at least it does on my PC. But that's not mentioned in the docs.

Multidimensional arrays in Swift

Using http://blog.trolieb.com/trouble-multidimensional-arrays-swift/ as a start, I added generics to mine:

class Array2DTyped<T>{

var cols:Int, rows:Int
var matrix:[T]

init(cols:Int, rows:Int, defaultValue:T){
    self.cols = cols
    self.rows = rows
    matrix = Array(count:cols*rows,repeatedValue:defaultValue)
}

subscript(col:Int, row:Int) -> T {
    get{
        return matrix[cols * row + col]
    }
    set{
        matrix[cols * row + col] = newValue
    }
}

func colCount() -> Int {
    return self.cols
}

func rowCount() -> Int {
    return self.rows
}
}

How to check if a file exists in a folder?

It can be improved like so:

if(Directory.EnumerateFileSystemEntries(ProcessingDirectory, "*.xml").ToList<string>().Count == 0)
    log.Info("no files present")

Alternatively:

log.Info(Directory.EnumerateFileSystemEntries(ProcessingDirectory, "*.xml").ToList<string>().Count + " file(s) present");

why $(window).load() is not working in jQuery?

I have to write a whole answer separately since it's hard to add a comment so long to the second answer.

I'm sorry to say this, but the second answer above doesn't work right.

The following three scenarios will show my point:

Scenario 1: Before the following way was deprecated,

  $(window).load(function () {
     alert("Window Loaded.");
  });

if we execute the following two queries:

<script>
   $(window).load(function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the way it should be.

Scenario 2: But if we execute the following two queries like the second answer above suggests:

<script>
   $(window).ready(function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

the alert (Window Loaded.) from the first query will show first, and the one (Dom Loaded.) from the second query will show later, which is NOT right.

Scenario 3: On the other hand, if we execute the following two queries, we'll get the correct result:

<script>
   $(window).on("load", function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

that is to say, the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the RIGHT result.

In short, the FIRST answer is the CORRECT one:

$(window).on('load', function () {
  alert("Window Loaded.");
});

How to debug Javascript with IE 8

I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.

  • Click ? Tools on the toolbar, to the right of the tabs.
  • Select Developer Tools. The Developer Tools dialogue should open.
  • Click the Script tab in the dialogue.
  • Click the Start Debugging button.

You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.

You can also use the statement debugger; in your JavaScript code the set a breakpoint.

when exactly are we supposed to use "public static final String"?

You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.

Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.

An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).

Here's why:

  1. Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
  2. What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.

What are the consequences?

Imagine you have this:

class Foo {
  public static final String VERSION = "1.0";
}

class Bar {
  public static void main(String[] args) {
    System.out.println("I am using version " + Foo.VERSION);
  }
}

After compiling and running Bar, you'll get:

I am using version 1.0

Now, you improve Foo and change the version to "1.1". After recompiling Foo, you run Bar and get this wrong output:

I am using version 1.0

This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.

I've seen this a couple of times and it is really hard to debug.

If by final you mean a constant that might change in later versions of your program, a better solution would be this:

class Foo {
  private static String version = "1.0";
  public static final String getVersion() {
    return version;
  }
}

The performance penalty of this is negligible, since JIT code generator will inline it at run-time.

How to start and stop/pause setInterval?

(function(){
    var i = 0;
    function stop(){
        clearTimeout(i);
    }

    function start(){
        i = setTimeout( timed, 1000 );
    }

    function timed(){
       document.getElementById("input").value++;
       start();
    }

    window.stop = stop;
    window.start = start;
})()

http://jsfiddle.net/TE3Z2/

x86 Assembly on a Mac

Also, on the Intel Macs, can I use generic x86 asm? or is there a modified instruction set? Any information about post Intel Mac assembly helps.

It's the same instruction set; it's the same chips.

Create MSI or setup project with Visual Studio 2012

I think that Deploying an Office Solution by Using ClickOnce (MSDN) can be useful.

After creating an Outlook plugin for Office 2010 the problem was to install it on the customer's computer, without using ISLE or other complex tools (or expensive).

The solution was to use the publish instrument of the Visual Studio project, as described in the link. Just two things to be done before the setup will work:

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

How to reload a div without reloading the entire page?

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

Adding an onclick event to a div element

I'm not sure what the problem is; running the below works as expected:

<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">knock knock</div>
?<div id="rad1" style="visibility: hidden">hello world</div>????????????????????????????????
<script>
function klikaj(i) {
    document.getElementById(i).style.visibility='visible';
}
</script>

See also: http://jsfiddle.net/5tD4P/

how to remove untracked files in Git?

You may also return to the previous state of the local repo in another way:

  1. Add the untracked files to the staging area with git add.
  2. return to the previous state of the local repo with git reset --hard.

Best way to disable button in Twitter's Bootstrap

<div class="bs-example">
      <button class="btn btn-success btn-lg" type="button">Active</button>
      <button class="btn btn-success disabled" type="button">Disabled</button>
</div>

create unique id with javascript

put in your namespace an instance similar to the following one

var myns = {/*.....*/};
myns.uid = new function () {
    var u = 0;
    this.toString = function () {
        return 'myID_' + u++;
    };
};
console.dir([myns.uid, myns.uid, myns.uid]);

How can I do time/hours arithmetic in Google Spreadsheet?

I had a similar issue and i just fixed it for now

  1. format each of the cell to time
  2. format the total cell (sum of all the time) to Duration

How to remove multiple indexes from a list at the same time?

If you can use numpy, then you can delete multiple indices:

>>> import numpy as np
>>> a = np.arange(10)
>>> np.delete(a,(1,3,5))
array([0, 2, 4, 6, 7, 8, 9])

and if you use np.r_ you can combine slices with individual indices:

>>> np.delete(a,(np.r_[0:5,7,9]))
array([5, 6, 8])

However, the deletion is not in place, so you have to assign to it.

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value
end

If you write:

attr_reader :age

That gets translated into:

def age
  @age
end

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value
end

def age
  @age
end

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

How to install Boost on Ubuntu

An update for Windows 10 Ubuntu Application via Subsystem (also works on standard Ubuntu):

You might have problems finding the package. If you do, never fear! PPA is here!

sudo add-apt-repository ppa:boost-latest/ppa
sudo apt-get update

Then run:

sudo apt-get install libboost-all-dev

Simple dynamic breadcrumb

A better one using explode() function is as follows...

Don't forget to replace your URL variable in the hyperlink href.

<?php 
    if($url != ''){
        $b = '';
        $links = explode('/',rtrim($url,'/'));
        foreach($links as $l){
            $b .= $l;
            if($url == $b){
                echo $l;
            }else{
                echo "<a href='URL?url=".$b."'>".$l."/</a>";
            }
            $b .= '/';
         }
     }
?>

How can I insert new line/carriage returns into an element.textContent?

I found that inserting \\n works. I.e., you escape the escaped new line character

Kill a postgresql session/connection

You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same.

SELECT 
    pg_terminate_backend(pid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    pid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

Before executing this query, you have to REVOKE the CONNECT privileges to avoid new connections:

REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;

If you're using Postgres 8.4-9.1 use procpid instead of pid

SELECT 
    pg_terminate_backend(procpid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    procpid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

Within your app in the Android Emulator press Command + M on macOS or Ctrl + M on Linux and Windows.

switch() statement usage

Well, timing to the rescue again. It seems switch is generally faster than if statements. So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

# Simplified to only measure the overhead of switch vs if

test1 <- function(type) {
 switch(type,
        mean = 1,
        median = 2,
        trimmed = 3)
}

test2 <- function(type) {
 if (type == "mean") 1
 else if (type == "median") 2
 else if (type == "trimmed") 3
}

system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs

Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
           expr  min   lq median   uq      max
1 test1("mean")  709  771    864  951 16122411
2 test2("mean") 1007 1073   1147 1223  8012202

> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
              expr  min   lq median   uq      max
1 test1("trimmed")  733  792    843  944 60440833
2 test2("trimmed") 2022 2133   2203 2309 60814430

Final Update Here's showing how versatile switch is:

switch(type, case1=1, case2=, case3=2.5, 99)

This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

What is EOF in the C programming language?

#include <stdio.h>

int main() {
    int c;
    while((c = getchar()) != EOF) { 
        putchar(c);
    }    
    printf("%d  at EOF\n", c);
}

modified the above code to give more clarity on EOF, Press Ctrl+d and putchar is used to print the char avoid using printf within while loop.

PostgreSQL IF statement

From the docs

IF boolean-expression THEN
    statements
ELSE
    statements
END IF;

So in your above example the code should look as follows:

IF select count(*) from orders > 0
THEN
  DELETE from orders
ELSE 
  INSERT INTO orders values (1,2,3);
END IF;

You were missing: END IF;

SQL Developer with JDK (64 bit) cannot find JVM

I run into the same error message when trying to install SQL Developer from "Windows 64-bit with JDK 8 included" zip file in my Windows 10 Enterprise.

Launching the most recent SQL Developer version 4.1.3 in Windows 10 shows an error:

Unable to launch the Java Virtual Machine Located at path:
C:\Users\<USER>\Downloads\sqldeveloper-4.1.3.20.78-x64\sqldeveloper\jdk\jre\bin\server\jvm.dll

The path exists and is valid.

The same zip file works on Windows 7 Professional.

The problem was a missing msvcr100.dll.

I simply copied C:\Program Files\Oracle\VirtualBox\msvrc100.dll to C:\Users\<USER>\Downloads\sqldeveloper-4.1.3.20.78-x64\sqldeveloper\sqldeveloper\bin\ and SQL Developer started to work.

The details can be found from Issue running SQL Developer x64 4.1.3 with JDK.

Funny that Oracle VirtualBox team can include the dll into the installation package but Oracle SQL Developer team can't.

How to make a simple modal pop up form using jquery and html?

I came across this question when I was trying similar things.

A very nice and simple sample is presented at w3schools website.

https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Modal Example</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to run regasm.exe from command line other than Visual Studio command prompt?

I use the following in a batch file:

path = %path%;C:\Windows\Microsoft.NET\Framework\v2.0.50727
regasm httpHelper\bin\Debug\httpHelper.dll /tlb:.\httpHelper.tlb /codebase
pause

Best way to add Gradle support to IntelliJ Project

Just as a future reference, if you already have a Maven project all you need to do is doing a gradle init in your project directory which will generates build.gradle and other dependencies, then do a gradle build in the same directory.

best practice font size for mobile

The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.

Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.

TensorFlow, "'module' object has no attribute 'placeholder'"

Import the old version of tensorflow instead of the new version

[https://inneka.com/ml/tf/tensorflow-module-object-has-no-attribute-placeholder/][1]

import tensorflow.compat.v1 as tf tf.disable_v2_behavior()

Is there a MessageBox equivalent in WPF?

Maybe the code here below helps:

using Windows.UI.Popups;
namespace something.MyViewModels
{
    public class TestViewModel
    {
        public void aRandonMethode()
        {
            MyMessageBox("aRandomMessage");
        }

        public async void MyMessageBox(string mytext)
        {
            var dialog = new MessageDialog(mytext);
            await dialog.ShowAsync();
        }
    }
}

Create PostgreSQL ROLE (user) if it doesn't exist

The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER … to \gexec.

Workaround from within psql

SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec

Workaround from the shell

echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql

See accepted answer there for more details.

How get all values in a column using PHP?

Here is a simple way to do this using either PDO or mysqli

$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);

or, using mysqli

$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
    $array[] = $row['column'];
}
print_r($array);

Array
(
    [0] => 7960
    [1] => 7972
    [2] => 8028
    [3] => 8082
    [4] => 8233
)

momentJS date string add 5 days

The function add() returns the old date, but changes the original date :)

startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);

C library function to perform sort

Use qsort() in <stdlib.h>.

@paxdiablo The qsort() function conforms to ISO/IEC 9899:1990 (``ISO C90'').

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I'm posting my solution for the other sleep-deprived souls out there:

If you're using RVM, double-check that you're in the correct folder, using the correct ruby version and gemset. I had an array of terminal tabs open, and one of them was in a different directory. typing "rails console" produced the error because my default rails distro is 2.3.x.

I noticed the error on my part, cd'd to the correct directory, and my .rvmrc file did the rest.

RVM is not like Git. In git, changing branches in one shell changes it everywhere. It's literally rewriting the files in question. RVM, on the other hand, is just setting shell variables, and must be set for each new shell you open.

In case you're not familiar with .rvmrc, you can put a file with that name in any directory, and rvm will pick it up and use the version/gemset specified therein, whenever you change to that directory. Here's a sample .rvmrc file:

rvm use 1.9.2@turtles

This will switch to the latest version of ruby 1.9.2 in your RVM collection, using the gemset "turtles". Now you can open up a hundred tabs in Terminal (as I end up doing) and never worry about the ruby version it's pointing to.

Append values to query string

I like Bjorn's answer, however the solution he's provided is misleading, as the method updates an existing parameter, rather than adding it if it doesn't exist.. To make it a bit safer, I've adapted it below.

public static class UriExtensions
{
    /// <summary>
    /// Adds or Updates the specified parameter to the Query String.
    /// </summary>
    /// <param name="url"></param>
    /// <param name="paramName">Name of the parameter to add.</param>
    /// <param name="paramValue">Value for the parameter to add.</param>
    /// <returns>Url with added parameter.</returns>
    public static Uri AddOrUpdateParameter(this Uri url, string paramName, string paramValue)
    {
        var uriBuilder = new UriBuilder(url);
        var query = HttpUtility.ParseQueryString(uriBuilder.Query);

        if (query.AllKeys.Contains(paramName))
        {
            query[paramName] = paramValue;
        }
        else
        {
            query.Add(paramName, paramValue);
        }
        uriBuilder.Query = query.ToString();

        return uriBuilder.Uri;
    }
}

Convert digits into words with JavaScript

Below are the translations from

  • integer to word
  • float to word
  • money to word

Test cases are at the bottom

_x000D_
_x000D_
var ONE_THOUSAND = Math.pow(10, 3);_x000D_
var ONE_MILLION = Math.pow(10, 6);_x000D_
var ONE_BILLION = Math.pow(10, 9);_x000D_
var ONE_TRILLION = Math.pow(10, 12);_x000D_
var ONE_QUADRILLION = Math.pow(10, 15);_x000D_
var ONE_QUINTILLION = Math.pow(10, 18);_x000D_
_x000D_
function integerToWord(integer) {_x000D_
  var prefix = '';_x000D_
  var suffix = '';_x000D_
_x000D_
  if (!integer){ return "zero"; }_x000D_
  _x000D_
  if(integer < 0){_x000D_
    prefix = "negative";_x000D_
    suffix = integerToWord(-1 * integer);_x000D_
    return prefix + " " + suffix;_x000D_
  }_x000D_
  if(integer <= 90){_x000D_
    switch (integer) {_x000D_
      case integer < 0:_x000D_
        prefix = "negative";_x000D_
        suffix = integerToWord(-1 * integer);_x000D_
        return prefix + " "  + suffix;_x000D_
      case 1: return "one";_x000D_
      case 2: return "two";_x000D_
      case 3: return "three";_x000D_
      case 4:  return "four";_x000D_
      case 5: return "five";_x000D_
      case 6: return "six";_x000D_
      case 7: return "seven";_x000D_
      case 8: return "eight";_x000D_
      case 9: return "nine";_x000D_
      case 10: return "ten";_x000D_
      case 11: return "eleven";_x000D_
      case 12: return "twelve";_x000D_
      case 13: return "thirteen";_x000D_
      case 14: return "fourteen";_x000D_
      case 15: return "fifteen";_x000D_
      case 16: return "sixteen";_x000D_
      case 17: return "seventeen";_x000D_
      case 18: return "eighteen";_x000D_
      case 19: return "nineteen";_x000D_
      case 20: return "twenty";_x000D_
      case 30: return "thirty";_x000D_
      case 40: return "forty";_x000D_
      case 50: return "fifty";_x000D_
      case 60: return "sixty";_x000D_
      case 70: return "seventy";_x000D_
      case 80: return "eighty";_x000D_
      case 90: return "ninety";_x000D_
      default: break;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  if(integer < 100){_x000D_
    prefix = integerToWord(integer - integer % 10);_x000D_
    suffix = integerToWord(integer % 10);_x000D_
    return prefix + "-"  + suffix;_x000D_
  }_x000D_
_x000D_
  if(integer < ONE_THOUSAND){_x000D_
    prefix = integerToWord(parseInt(Math.floor(integer / 100), 10) )  + " hundred";_x000D_
    if (integer % 100){ suffix = " and "  + integerToWord(integer % 100); }_x000D_
    return prefix + suffix;_x000D_
  }_x000D_
_x000D_
  if(integer < ONE_MILLION){_x000D_
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_THOUSAND), 10))  + " thousand";_x000D_
    if (integer % ONE_THOUSAND){ suffix = integerToWord(integer % ONE_THOUSAND); }_x000D_
  }_x000D_
  else if(integer < ONE_BILLION){_x000D_
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_MILLION), 10))  + " million";_x000D_
    if (integer % ONE_MILLION){ suffix = integerToWord(integer % ONE_MILLION); }_x000D_
  }_x000D_
  else if(integer < ONE_TRILLION){_x000D_
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_BILLION), 10))  + " billion";_x000D_
    if (integer % ONE_BILLION){ suffix = integerToWord(integer % ONE_BILLION); }_x000D_
  }_x000D_
  else if(integer < ONE_QUADRILLION){_x000D_
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_TRILLION), 10))  + " trillion";_x000D_
    if (integer % ONE_TRILLION){ suffix = integerToWord(integer % ONE_TRILLION); }_x000D_
  }_x000D_
  else if(integer < ONE_QUINTILLION){_x000D_
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_QUADRILLION), 10))  + " quadrillion";_x000D_
    if (integer % ONE_QUADRILLION){ suffix = integerToWord(integer % ONE_QUADRILLION); }_x000D_
  } else {_x000D_
    return '';_x000D_
  }_x000D_
  return prefix + " "  + suffix;_x000D_
}_x000D_
_x000D_
function moneyToWord(value){_x000D_
  var decimalValue = (value % 1);_x000D_
  var integer = value - decimalValue;_x000D_
  decimalValue = Math.round(decimalValue * 100);_x000D_
  var decimalText = !decimalValue? '': integerToWord(decimalValue) + ' cent' + (decimalValue === 1? '': 's');_x000D_
  var integerText= !integer? '': integerToWord(integer) + ' dollar' + (integer === 1? '': 's');_x000D_
  return (_x000D_
    integer && !decimalValue? integerText:_x000D_
    integer && decimalValue? integerText + ' and ' + decimalText:_x000D_
    !integer && decimalValue? decimalText:_x000D_
    'zero cents'_x000D_
  );_x000D_
}_x000D_
_x000D_
function floatToWord(value){_x000D_
  var decimalValue = (value % 1);_x000D_
  var integer = value - decimalValue;_x000D_
  decimalValue = Math.round(decimalValue * 100);_x000D_
  var decimalText = !decimalValue? '':_x000D_
    decimalValue < 10? "point o' " + integerToWord(decimalValue):_x000D_
    decimalValue % 10 === 0? 'point ' + integerToWord(decimalValue / 10):_x000D_
    'point ' + integerToWord(decimalValue);_x000D_
  return (_x000D_
    integer && !decimalValue? integerToWord(integer):_x000D_
    integer && decimalValue? [integerToWord(integer),  decimalText].join(' '):_x000D_
    !integer && decimalValue? decimalText:_x000D_
    integerToWord(0)_x000D_
  );_x000D_
}_x000D_
_x000D_
// test_x000D_
(function(){_x000D_
  console.log('integerToWord ==================================');_x000D_
  for(var i = 0; i < 101; ++i){_x000D_
    console.log('%s=%s', i, integerToWord(i));_x000D_
  }_x000D_
  console.log('floatToWord ====================================');_x000D_
  i = 131;_x000D_
  while(i--){_x000D_
    console.log('%s=%s', i / 100, floatToWord(i / 100));_x000D_
  }_x000D_
  console.log('moneyToWord ====================================');_x000D_
  for(i = 0; i < 131; ++i){_x000D_
    console.log('%s=%s', i / 100, moneyToWord(i / 100));_x000D_
  }_x000D_
}());
_x000D_
_x000D_
_x000D_

How to add an element to the beginning of an OrderedDict?

FWIW Here is a quick-n-dirty code I wrote for inserting to an arbitrary index position. Not necessarily efficient but it works in-place.

class OrderedDictInsert(OrderedDict):
    def insert(self, index, key, value):
        self[key] = value
        for ii, k in enumerate(list(self.keys())):
            if ii >= index and k != key:
                self.move_to_end(k)

Facebook Javascript SDK Problem: "FB is not defined"

To test Mattys suggestions about FB not finishing, I put an alert in the script. This cause a delay that I could control. Sure enough... it was a timing issue.

    $("document").ready(function () {
        // Wait...
        alert('Click ok to init');
        try {
            FB.init({
                appId: '###', // App ID
                status: true, // check login status
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true  // parse XFBML
            });
        }
        catch (err) {
            txt = "There was an error on this page.\n\n";
            txt += "Error description: " + err.message + "\n\n";
            txt += "Click OK to continue.\n\n";
            alert(txt);
        }
        FB.Event.subscribe('auth.statusChange', OnLogin);
    });

Floating point vs integer calculations on modern hardware

Today, integer operations are usually a little bit faster than floating point operations. So if you can do a calculation with the same operations in integer and floating point, use integer. HOWEVER you are saying "This causes a whole lot of annoying problems and adds a lot of annoying code". That sounds like you need more operations because you use integer arithmetic instead of floating point. In that case, floating point will run faster because

  • as soon as you need more integer operations, you probably need a lot more, so the slight speed advantage is more than eaten up by the additional operations

  • the floating-point code is simpler, which means it is faster to write the code, which means that if it is speed critical, you can spend more time optimising the code.

How to find most common elements of a list?

nltk is convenient for a lot of language processing stuff. It has methods for frequency distribution built in. Something like:

import nltk
fdist = nltk.FreqDist(your_list) # creates a frequency distribution from a list
most_common = fdist.max()    # returns a single element
top_three = fdist.keys()[:3] # returns a list

Find and replace words/lines in a file

You might want to use Scanner to parse through and find the specific sections you want to modify. There's also Split and StringTokenizer that may work, but at the level you're working at Scanner might be what's needed.

Here's some additional info on what the difference is between them: Scanner vs. StringTokenizer vs. String.Split

Trusting all certificates using HttpClient over HTTPS

I'm adding a response for those that use the httpclient-4.5, and probably works for 4.4 as well.

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.ContentResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;



public class HttpClientUtils{

public static HttpClient getHttpClientWithoutSslValidation_UsingHttpClient_4_5_2() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); 
        return httpclient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
}

How to move an element down a litte bit in html

You can use the top margin-top and adjust the text or you could also use padding-top both would have similar visual effect in your case but actually both behave a bit differently.

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

I had to add "Current" using .NET 4.5:

HttpContext.Current.Server.ScriptTimeout = 300;

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

C Macro definition to determine big endian or little endian machine?

Please pay attention that most of the answers here are not portable, since compilers today will evaluate those answers in compilation time (depends on the optimization) and return a specific value based on a specific endianness, while the actual machine endianness can differ. The values on which the endianness is tested, won't never reach the system memory thus the real executed code will return the same result regardless of the actual endianness.

For example, in ARM Cortex-M3 the implemented endianness will reflect in a status bit AIRCR.ENDIANNESS and compiler cannot know this value in compile time.

Compilation output for some of the answers suggested here:

https://godbolt.org/z/GJGNE2 for this answer,

https://godbolt.org/z/Yv-pyJ for this answer, and so on.

To solve it you will need to use the volatile qualifier. Yogeesh H T's answer is the closest one for today's real life usage, but since Christoph suggests more comprehensive solution, a slight fix to his answer would make the answer complete, just add volatile to the union declaration: static const volatile union.

This would assure storing and reading from memory, which is needed to determine endianness.

Resolving require paths with webpack

Webpack >2.0

See wtk's answer.

Webpack 1.0

A more straightforward way to do this would be to use resolve.root.

http://webpack.github.io/docs/configuration.html#resolve-root

resolve.root

The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.

In your case:

webpack config

var path = require('path');

// ...

  resolve: {
    root: path.resolve('./mydir'),
    extensions: ['', '.js']
  }

consuming module

require('myfile')

or

require('myfile.js')

see also: http://webpack.github.io/docs/configuration.html#resolve-modulesdirectories

Resolve absolute path from relative path and/or file name

This is to help fill in the gaps in Adrien Plisson's answer (which should be upvoted as soon as he edits it ;-):

you can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current path, which is obviously not what you want.

unfortunately, i don't know how to mix the 2 together...

One can handle %0 and %1 likewise:

  • %~dpnx0 for fully qualified drive+path+name+extension of the batchfile itself,
    %~f0 also suffices;
  • %~dpnx1 for fully qualified drive+path+name+extension of its first argument [if that's a filename at all],
    %~f1 also suffices;

%~f1 will work independent of how you did specify your first argument: with relative paths or with absolute paths (if you don't specify the file's extension when naming %1, it will not be added, even if you use %~dpnx1 -- however.

But how on earth would you name a file on a different drive anyway if you wouldn't give that full path info on the commandline in the first place?

However, %~p0, %~n0, %~nx0 and %~x0 may come in handy, should you be interested in path (without driveletter), filename (without extension), full filename with extension or filename's extension only. But note, while %~p1 and %~n1 will work to find out the path or name of the first argument, %~nx1 and %~x1 will not add+show the extension, unless you used it on the commandline already.

"Large data" workflows using pandas

As noted by others, after some years an 'out-of-core' pandas equivalent has emerged: dask. Though dask is not a drop-in replacement of pandas and all of its functionality it stands out for several reasons:

Dask is a flexible parallel computing library for analytic computing that is optimized for dynamic task scheduling for interactive computational workloads of “Big Data” collections like parallel arrays, dataframes, and lists that extend common interfaces like NumPy, Pandas, or Python iterators to larger-than-memory or distributed environments and scales from laptops to clusters.

Dask emphasizes the following virtues:

  • Familiar: Provides parallelized NumPy array and Pandas DataFrame objects
  • Flexible: Provides a task scheduling interface for more custom workloads and integration with other projects.
  • Native: Enables distributed computing in Pure Python with access to the PyData stack.
  • Fast: Operates with low overhead, low latency, and minimal serialization necessary for fast numerical algorithms
  • Scales up: Runs resiliently on clusters with 1000s of cores Scales down: Trivial to set up and run on a laptop in a single process
  • Responsive: Designed with interactive computing in mind it provides rapid feedback and diagnostics to aid humans

and to add a simple code sample:

import dask.dataframe as dd
df = dd.read_csv('2015-*-*.csv')
df.groupby(df.user_id).value.mean().compute()

replaces some pandas code like this:

import pandas as pd
df = pd.read_csv('2015-01-01.csv')
df.groupby(df.user_id).value.mean()

and, especially noteworthy, provides through the concurrent.futures interface a general infrastructure for the submission of custom tasks:

from dask.distributed import Client
client = Client('scheduler:port')

futures = []
for fn in filenames:
    future = client.submit(load, fn)
    futures.append(future)

summary = client.submit(summarize, futures)
summary.result()

How much RAM is SQL Server actually using?

Go to management studio and run sp_helpdb <db_name>, it will give detailed disk usage for the specified database. Running it without any parameter values will list high level information for all databases in the instance.

How to download excel (.xls) file from API in postman?

You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image postman save response

For more Details check this

https://learning.getpostman.com/docs/postman/sending_api_requests/responses/

How to get the PYTHONPATH in shell?

Just write:

just write which python in your terminal and you will see the python path you are using.

Using intents to pass data between activities

I like to use this clean code to pass one value only:

startActivity(new Intent(context, YourActivity.class).putExtra("key","value"));

This make more simple to write and understandable code.

Angular.js directive dynamic templateURL

You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.

<div ng-repeat="week in [1,2]">
  <div ng-repeat="day in ['monday', 'tuesday']">
    <ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>
  </div>
</div>

Find object by its property in array of objects with AngularJS way

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

This is a very old thread but thought to share this answer as it took lot of my development time to manage NULL return of BitmapFactory.decodeByteArray() as @Anirudh has faced.

If the encodedImage string is a JSON response, simply use Base64.URL_SAFE instead of Base64.DEAULT

byte[] decodedString = Base64.decode(encodedImage, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

As my purpose is to get an empty version of the test database to import data from an external previous current active source (Access database) once all is fine tuned. I found that using DBCC CloneDatabase with Verify_CloneDB option fits perfectly.

Spring Data JPA - "No Property Found for Type" Exception

If you are using ENUM like MessageStatus, you may need a converter. Just add this class:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * Convert ENUM type in JPA.
 */
@Converter(autoApply = true)
public class MessageStatusConverter implements AttributeConverter<MessageStatus, Integer> {
  @Override
  public Integer convertToDatabaseColumn(MessageStatus messageStatus) {
    return messageStatus.getValue();
  }

  @Override
  public MessageStatus convertToEntityAttribute(Integer i) {
    return MessageStatus.valueOf(i);
  }
}

Singleton with Arguments in Java

I think this is a common problem. Separating the "initialization" of the singleton from the "get" of the singleton might work (this example uses a variation of double checked locking).

public class MySingleton {

    private static volatile MySingleton INSTANCE;

    @SuppressWarnings("UnusedAssignment")
    public static void initialize(
            final SomeDependency someDependency) {

        MySingleton result = INSTANCE;

        if (result != null) {
            throw new IllegalStateException("The singleton has already "
                    + "been initialized.");
        }

        synchronized (MySingleton.class) {
            result = INSTANCE;

            if (result == null) {
                INSTANCE = result = new MySingleton(someDependency);
            } 
        }
    }

    public static MySingleton get() {
        MySingleton  result = INSTANCE;

        if (result == null) {
            throw new IllegalStateException("The singleton has not been "
                    + "initialized. You must call initialize(...) before "
                    + "calling get()");
        }

       return result;
    }

    ...
}

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

How to override Bootstrap's Panel heading background color?

I tried using custom panel class but it didn't work. So for those who are struggling just like me, you can use inline CSS and it works fine for me.

Here is what my code looks like :

<div class="panel-heading" style="background-image:none;background: #a4c6ff;">

How can I bind to the change event of a textarea in jQuery?

try this ...

$("#txtAreaID").bind("keyup", function(event, ui) {                          

              // Write your code here       
 });

dynamically add and remove view to viewpager

After figuring out which ViewPager methods are called by ViewPager and which are for other purposes, I came up with a solution. I present it here since I see a lot of people have struggled with this and I didn't see any other relevant answers.

First, here's my adapter; hopefully comments within the code are sufficient:

public class MainPagerAdapter extends PagerAdapter
{
  // This holds all the currently displayable views, in order from left to right.
  private ArrayList<View> views = new ArrayList<View>();

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  "Object" represents the page; tell the ViewPager where the
  // page should be displayed, from left-to-right.  If the page no longer exists,
  // return POSITION_NONE.
  @Override
  public int getItemPosition (Object object)
  {
    int index = views.indexOf (object);
    if (index == -1)
      return POSITION_NONE;
    else
      return index;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager needs a page to display; it is our job
  // to add the page to the container, which is normally the ViewPager itself.  Since
  // all our pages are persistent, we simply retrieve it from our "views" ArrayList.
  @Override
  public Object instantiateItem (ViewGroup container, int position)
  {
    View v = views.get (position);
    container.addView (v);
    return v;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager no longer needs a page to display; it
  // is our job to remove the page from the container, which is normally the
  // ViewPager itself.  Since all our pages are persistent, we do nothing to the
  // contents of our "views" ArrayList.
  @Override
  public void destroyItem (ViewGroup container, int position, Object object)
  {
    container.removeView (views.get (position));
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager; can be used by app as well.
  // Returns the total number of pages that the ViewPage can display.  This must
  // never be 0.
  @Override
  public int getCount ()
  {
    return views.size();
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.
  @Override
  public boolean isViewFromObject (View view, Object object)
  {
    return view == object;
  }

  //-----------------------------------------------------------------------------
  // Add "view" to right end of "views".
  // Returns the position of the new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v)
  {
    return addView (v, views.size());
  }

  //-----------------------------------------------------------------------------
  // Add "view" at "position" to "views".
  // Returns position of new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v, int position)
  {
    views.add (position, v);
    return position;
  }

  //-----------------------------------------------------------------------------
  // Removes "view" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, View v)
  {
    return removeView (pager, views.indexOf (v));
  }

  //-----------------------------------------------------------------------------
  // Removes the "view" at "position" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, int position)
  {
    // ViewPager doesn't have a delete method; the closest is to set the adapter
    // again.  When doing so, it deletes all its views.  Then we can delete the view
    // from from the adapter and finally set the adapter to the pager again.  Note
    // that we set the adapter to null before removing the view from "views" - that's
    // because while ViewPager deletes all its views, it will call destroyItem which
    // will in turn cause a null pointer ref.
    pager.setAdapter (null);
    views.remove (position);
    pager.setAdapter (this);

    return position;
  }

  //-----------------------------------------------------------------------------
  // Returns the "view" at "position".
  // The app should call this to retrieve a view; not used by ViewPager.
  public View getView (int position)
  {
    return views.get (position);
  }

  // Other relevant methods:

  // finishUpdate - called by the ViewPager - we don't care about what pages the
  // pager is displaying so we don't use this method.
}

And here's some snips of code showing how to use the adapter.

class MainActivity extends Activity
{
  private ViewPager pager = null;
  private MainPagerAdapter pagerAdapter = null;

  //-----------------------------------------------------------------------------
  @Override
  public void onCreate (Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView (R.layout.main_activity);

    ... do other initialization, such as create an ActionBar ...

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.view_pager);
    pager.setAdapter (pagerAdapter);

    // Create an initial view to display; must be a subclass of FrameLayout.
    LayoutInflater inflater = context.getLayoutInflater();
    FrameLayout v0 = (FrameLayout) inflater.inflate (R.layout.one_of_my_page_layouts, null);
    pagerAdapter.addView (v0, 0);
    pagerAdapter.notifyDataSetChanged();
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to add a view to the ViewPager.
  public void addView (View newPage)
  {
    int pageIndex = pagerAdapter.addView (newPage);
    // You might want to make "newPage" the currently displayed page:
    pager.setCurrentItem (pageIndex, true);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to remove a view from the ViewPager.
  public void removeView (View defunctPage)
  {
    int pageIndex = pagerAdapter.removeView (pager, defunctPage);
    // You might want to choose what page to display, if the current page was "defunctPage".
    if (pageIndex == pagerAdapter.getCount())
      pageIndex--;
    pager.setCurrentItem (pageIndex);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to get the currently displayed page.
  public View getCurrentPage ()
  {
    return pagerAdapter.getView (pager.getCurrentItem());
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to set the currently displayed page.  "pageToShow" must
  // currently be in the adapter, or this will crash.
  public void setCurrentPage (View pageToShow)
  {
    pager.setCurrentItem (pagerAdapter.getItemPosition (pageToShow), true);
  }
}

Finally, you can use the following for your activity_main.xml layout:

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

</android.support.v4.view.ViewPager>

How do I fire an event when a iframe has finished loading in jQuery?

I'm pretty certain that it cannot be done.

Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)

Too bad.

Is there any way to delete local commits in Mercurial?

You can get around this even more easily with the Rebase extension, just use hg pull --rebase and your commits are automatically re-comitted to the pulled revision, avoiding the branching issue.

PHP/MySQL insert row then get 'id'

An example.

    $query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
    $query_new = $databaseConnection->prepare($query_new);
    $query_new->bind_param('s', $_POST['coursename']);
    $query_new->execute();
    $course_id = $query_new->insert_id;
    $query_new->close();

The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row. Hope this helps.

Polling the keyboard (detect a keypress) in python

Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:

import msvcrt 

def kbfunc(): 
   x = msvcrt.kbhit()
   if x: 
      ret = ord(msvcrt.getch()) 
   else: 
      ret = 0 
   return ret

Oracle pl-sql escape character (for a " ' ")

Your question implies that you're building the INSERT statement up by concatenating strings together. I suggest that this is a poor choice as it leaves you open to SQL injection attacks if the strings are derived from user input. A better choice is to use parameter markers and to bind the values to the markers. If you search for Oracle parameter markers you'll probably find some information for your specific implementation technology (e.g. C# and ADO, Java and JDBC, Ruby and RubyDBI, etc).

Share and enjoy.

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

I solved the same problem, I used a network connection through a proxy server, when I selected the option not to use proxies for internal and local connections, the problem disappeared

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

How do I use a third-party DLL file in Visual Studio C++?

You only need to use LoadLibrary if you want to late bind and only resolve the imported functions at runtime. The easiest way to use a third party dll is to link against a .lib.


In reply to your edit:

Yes, the third party API should consist of a dll and/or a lib that contain the implementation and header files that declares the required types. You need to know the type definitions whichever method you use - for LoadLibrary you'll need to define function pointers, so you could just as easily write your own header file instead. Basically, you only need to use LoadLibrary if you want late binding. One valid reason for this would be if you aren't sure if the dll will be available on the target PC.

Finding whether a point lies inside a rectangle or not

The easiest way I thought of was to just project the point onto the axis of the rectangle. Let me explain:

If you can get the vector from the center of the rectangle to the top or bottom edge and the left or right edge. And you also have a vector from the center of the rectangle to your point, you can project that point onto your width and height vectors.

P = point vector, H = height vector, W = width vector

Get Unit vector W', H' by dividing the vectors by their magnitude

proj_P,H = P - (P.H')H' proj_P,W = P - (P.W')W'

Unless im mistaken, which I don't think I am... (Correct me if I'm wrong) but if the magnitude of the projection of your point on the height vector is less then the magnitude of the height vector (which is half of the height of the rectangle) and the magnitude of the projection of your point on the width vector is, then you have a point inside of your rectangle.

If you have a universal coordinate system, you might have to figure out the height/width/point vectors using vector subtraction. Vector projections are amazing! remember that.

Resync git repo with new .gitignore file

I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch, then remove them manually, but this will not work well if there are a lot.

Here is a solution that utilizes bash arrays to capture all files.

# Build bash array of the file names
while read -r file; do 
    rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)

git rm –-cached "${rmlist[@]}"

git commit -m 'ignore update'

Find duplicate characters in a String and count the number of occurances using Java

Java 8 way:

"The quick brown fox jumped over the lazy dog."
        .chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.groupingBy(Object::toString, Collectors.counting()));

Django: multiple models in one template using forms

The MultiModelForm from django-betterforms is a convenient wrapper to do what is described in Gnudiff's answer. It wraps regular ModelForms in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.

# forms.py
from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile

User = get_user_model()

class UserEditForm(forms.ModelForm):
    class Meta:
        fields = ('email',)

class UserProfileForm(forms.ModelForm):
    class Meta:
        fields = ('favorite_color',)

class UserEditMultiForm(MultiModelForm):
    form_classes = {
        'user': UserEditForm,
        'profile': UserProfileForm,
    }

# views.py
from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm

User = get_user_model()

class UserSignupView(UpdateView):
    model = User
    form_class = UserEditMultiForm
    success_url = reverse_lazy('home')

    def get_form_kwargs(self):
        kwargs = super(UserSignupView, self).get_form_kwargs()
        kwargs.update(instance={
            'user': self.object,
            'profile': self.object.profile,
        })
        return kwargs

Excel VBA If cell.Value =... then

I think it would make more sense to use "Find" function in Excel instead of For Each loop. It works much much faster and it's designed for such actions. Try this:

 Sub FindSomeCells(strSearchQuery As String)   

    Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
    FindWhat = strSearchQuery
    Set FoundCells = FindAll(SearchRange:=SearchRange, _
                            FindWhat:=FindWhat, _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByColumns, _
                            MatchCase:=False, _
                            BeginsWith:=vbNullString, _
                            EndsWith:=vbNullString, _
                            BeginEndCompare:=vbTextCompare)
    If FoundCells Is Nothing Then
        Debug.Print "Value Not Found"
    Else
        For Each FoundCell In FoundCells
            FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
        Next FoundCell
    End If

End Sub

That subroutine searches for some string and returns a collections of cells fullfilling your search criteria. Then you can do whatever you want with the cells in that collection. Forgot to add the FindAll function definition:

Function FindAll(SearchRange As Range, _
                FindWhat As Variant, _
               Optional LookIn As XlFindLookIn = xlValues, _
                Optional LookAt As XlLookAt = xlWhole, _
                Optional SearchOrder As XlSearchOrder = xlByRows, _
                Optional MatchCase As Boolean = False, _
                Optional BeginsWith As String = vbNullString, _
                Optional EndsWith As String = vbNullString, _
                Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result.  If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
    XLookAt = xlPart
Else
    XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.

For Each Area In SearchRange.Areas
    With Area
        If .Cells(.Cells.Count).Row > MaxRow Then
            MaxRow = .Cells(.Cells.Count).Row
        End If
        If .Cells(.Cells.Count).Column > MaxCol Then
            MaxCol = .Cells(.Cells.Count).Column
        End If
    End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
        after:=LastCell, _
        LookIn:=LookIn, _
        LookAt:=XLookAt, _
        SearchOrder:=SearchOrder, _
        MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
    Set FirstFound = FoundCell
    Do Until False ' Loop forever. We'll "Exit Do" when necessary.
        Include = False
        If BeginsWith = vbNullString And EndsWith = vbNullString Then
            Include = True
        Else
            If BeginsWith <> vbNullString Then
                If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
            If EndsWith <> vbNullString Then
                If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
        End If
        If Include = True Then
            If ResultRange Is Nothing Then
                Set ResultRange = FoundCell
            Else
                Set ResultRange = Application.Union(ResultRange, FoundCell)
            End If
        End If
        Set FoundCell = SearchRange.FindNext(after:=FoundCell)
        If (FoundCell Is Nothing) Then
            Exit Do
        End If
        If (FoundCell.Address = FirstFound.Address) Then
            Exit Do
        End If
    Loop
End If
Set FindAll = ResultRange
End Function

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

What I am thinking is having webpack would be easy when production release.

FYI : https://github.com/Piusha/ngx-lazyloading

Dynamic loading of images in WPF

It is because the Creation was delayed. If you want the picture to be loaded immediately, you can simply add this code into the init phase.

src.CacheOption = BitmapCacheOption.OnLoad;

like this:

src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();

Efficient way to insert a number into a sorted array of numbers?

Here is my function, uses binary search to find item and then inserts appropriately:

_x000D_
_x000D_
function binaryInsert(val, arr){_x000D_
    let mid, _x000D_
    len=arr.length,_x000D_
    start=0,_x000D_
    end=len-1;_x000D_
    while(start <= end){_x000D_
        mid = Math.floor((end + start)/2);_x000D_
        if(val <= arr[mid]){_x000D_
            if(val >= arr[mid-1]){_x000D_
                arr.splice(mid,0,val);_x000D_
                break;_x000D_
            }_x000D_
            end = mid-1;_x000D_
        }else{_x000D_
            if(val <= arr[mid+1]){_x000D_
                arr.splice(mid+1,0,val);_x000D_
                break;_x000D_
            }_x000D_
            start = mid+1;_x000D_
        }_x000D_
    }_x000D_
    return arr;_x000D_
}_x000D_
_x000D_
console.log(binaryInsert(16, [_x000D_
    5,   6,  14,  19, 23, 44,_x000D_
   35,  51,  86,  68, 63, 71,_x000D_
   87, 117_x000D_
 ]));
_x000D_
_x000D_
_x000D_

JQuery: dynamic height() with window resize()

To see the window height while (or after) it is resized, try it:

$(window).resize(function() {
$('body').prepend('<div>' + $(window).height() - 46 + '</div>');
});

Download and install an ipa from self hosted url on iOS

Yes, safari will detect the *.ipa and will try to install it, but the ipa needs to be correctly signed and only allowed devices would be able to install it.

http://www.diawi.com is a service that will help you with this process.

All of this is for Ad-hoc distribution, not for production apps.

More information on below link : Is there a way to install iPhone App via browser?

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How to upgrade Git to latest version on macOS?

I prefer not to alter the path hierarchy, but instead deal with git specifically...knowing that I'm never going to use old git to do what new git will now manage. This is a brute force solution.

NOTE: I installed XCode on Yosemite (10.10.2) clean first.

I then installed from the binary available on git-scm.com.

$ which git
/usr/bin/git
$ cd /usr/bin
$ sudo ln -sf /usr/local/git/bin/git
$ sudo ln -sf /usr/local/git/bin/git-credential-osxkeychain
$ sudo ln -sf /usr/local/git/bin/git-cvsserver
$ sudo ln -sf /usr/local/git/bin/git-receive-pack
$ sudo ln -sf /usr/local/git/bin/git-shell
$ sudo ln -sf /usr/local/git/bin/git-upload-archive
$ sudo ln -sf /usr/local/git/bin/git-upload-pack
$ ls -la
(you should see your new symlinks)

Convert varchar into datetime in SQL Server

This seems the easiest way..

SELECT REPLACE(CONVERT(CHAR(10), GETDATE(), 110),'-','')

How to COUNT rows within EntityFramework without loading contents?

Use the ExecuteStoreQuery method of the entity context. This avoids downloading the entire result set and deserializing into objects to do a simple row count.

   int count;

    using (var db = new MyDatabase()){
      string sql = "SELECT COUNT(*) FROM MyTable where FkId = {0}";

      object[] myParams = {1};
      var cntQuery = db.ExecuteStoreQuery<int>(sql, myParams);

      count = cntQuery.First<int>();
    }

How to start color picker on Mac OS?

You can turn the color picker into an application by following the guide here:

http://hints.macworld.com/article.php?story=20060408050920158

From the guide:

Simply fire up AppleScript (Applications -> AppleScript Editor) and enter this text:

choose color

Now, save it as an application (File -> Save As, and set the File Format pop-up to Application), and you're done

jQuery select by attribute using AND and OR operators

JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:

a=$('[myc="blue"], [myid="1"], [myid="3"]');

Edit:

Sorry, you wanted blue and 1 or 3. How about:

a=$('[myc="blue"][myid="1"],  [myid="3"]');

Putting the two attribute selectors together gives you AND, using a comma gives you OR.

Get all dates between two dates in SQL Server

create procedure [dbo].[p_display_dates](@startdate datetime,@enddate datetime)
as
begin
    declare @mxdate datetime
    declare @indate datetime
    create table #daterange (dater datetime)
    insert into #daterange values (@startdate)
    set @mxdate = (select MAX(dater) from #daterange)
    while @mxdate < @enddate
        begin
            set @indate = dateadd(day,1,@mxdate)
            insert into #daterange values (@indate)
            set @mxdate = (select MAX(dater) from #daterange)
        end
    select * from #daterange
end

Best XML parser for Java

I think you should not consider any specific parser implementation. Java API for XML Processing lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).

Basically there are three ways of handling XML in a standard way:

  • SAX This is the simplest API. You read the XML by defining a Handler class that receives the data inside elements/attributes when the XML gets processed in a serial way. It is faster and simpler if you only plan to read some attributes/elements and/or write some values back (your case).
  • DOM This method creates an object tree which lets you modify/access it randomly so it is better for complex XML manipulation and handling.
  • StAX This is in the middle of the path between SAX and DOM. You just write code to pull the data from the parser you are interested in when it is processed.

Forget about proprietary APIs such as JDOM or Apache ones (i.e. Apache Xerces XMLSerializer) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.

There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which.

JavaScript get clipboard data on paste event (Cross browser)

This was too long for a comment on Nico's answer, which I don't think works on Firefox any more (per the comments), and didn't work for me on Safari as is.

Firstly, you now appear to be able to read directly from the clipboard. Rather than code like:

if (/text\/plain/.test(e.clipboardData.types)) {
    // shouldn't this be writing to elem.value for text/plain anyway?
    elem.innerHTML = e.clipboardData.getData('text/plain');
}

use:

types = e.clipboardData.types;
if (((types instanceof DOMStringList) && types.contains("text/plain")) ||
    (/text\/plain/.test(types))) {
    // shouldn't this be writing to elem.value for text/plain anyway?
    elem.innerHTML = e.clipboardData.getData('text/plain');
}

because Firefox has a types field which is a DOMStringList which does not implement test.

Next Firefox will not allow paste unless the focus is in a contenteditable=true field.

Finally, Firefox will not allow paste reliably unless the focus is in a textarea (or perhaps input) which is not only contenteditable=true but also:

  • not display:none
  • not visibility:hidden
  • not zero sized

I was trying to hide the text field so I could make paste work over a JS VNC emulator (i.e. it was going to a remote client and there was no actually textarea etc to paste into). I found trying to hide the text field in the above gave symptoms where it worked sometimes, but typically failed on the second paste (or when the field was cleared to prevent pasting the same data twice) as the field lost focus and would not properly regain it despite focus(). The solution I came up with was to put it at z-order: -1000, make it display:none, make it as 1px by 1px, and set all the colours to transparent. Yuck.

On Safari, you the second part of the above applies, i.e. you need to have a textarea which is not display:none.

jQueryUI modal dialog does not show close button (x)

While the op does not explicitly state they are using jquery ui and bootstrap together, an identical problem happens if you do. You can resolve the problem by loading bootstrap (js) before jquery ui (js). However, that will cause problems with button state colors.

The final solution is to either use bootstrap or jquery ui, but not both. However, a workaround is:

    $('<div>dialog content</div>').dialog({
        title: 'Title',
        open: function(){
            var closeBtn = $('.ui-dialog-titlebar-close');
            closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
        }
    });

How can I run a PHP script inside a HTML file?

Simply you cant !! but you have some possbile options :

1- Excute php page as external page.

2- write your html code inside the php page itself.

3- use iframe to include the php within the html page.

to be more specific , unless you wanna edit your htaccess file , you may then consider this:

http://php.about.com/od/advancedphp/p/html_php.htm

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Follow these steps

  1. Add cors dependency. type the following in cli inside your project directory

npm install --save cors

  1. Include the module inside your project

var cors = require('cors');

  1. Finally use it as a middleware.

app.use(cors());

ASP.NET Bundles how to disable minification

Here's how to disable minification on a per-bundle basis:

bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));

Sidenote: The paths used for your bundles must not coincide with any actual path in your published builds otherwise nothing will work. Also make sure to avoid using .js, .css and/or '.' and '_' anywhere in the name of the bundle. Keep the name as simple and as straightforward as possible, like in the example above.

The helper classes are shown below. Notice that in order to make these classes future-proof we surgically remove the js/css minifying instances instead of using .clear() and we also insert a mime-type-setter transformation without which production builds are bound to run into trouble especially when it comes to properly handing over css-bundles (firefox and chrome reject css bundles with mime-type set to "text/html" which is the default):

internal sealed class StyleBundleRaw : StyleBundle
{
        private static readonly BundleMimeType CssContentMimeType = new BundleMimeType("text/css");

        public StyleBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
        {
        }

        public StyleBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
        {
                 Transforms.Add(CssContentMimeType); //0 vital
                 Transforms.Remove(Transforms.FirstOrDefault(x => x is CssMinify)); //0
        }
        //0 the guys at redmond in their infinite wisdom plugged the mimetype "text/css" right into cssminify    upon unwiring the minifier we
        //  need to somehow reenable the cssbundle to specify its mimetype otherwise it will advertise itself as html and wont load
}

internal sealed class ScriptBundleRaw : ScriptBundle
{
        private static readonly BundleMimeType JsContentMimeType = new BundleMimeType("text/javascript");

        public ScriptBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
        {
        }

        public ScriptBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
        {
                 Transforms.Add(JsContentMimeType); //0 vital
                 Transforms.Remove(Transforms.FirstOrDefault(x => x is JsMinify)); //0
        }
        //0 the guys at redmond in their infinite wisdom plugged the mimetype "text/javascript" right into jsminify   upon unwiring the minifier we need
        //  to somehow reenable the jsbundle to specify its mimetype otherwise it will advertise itself as html causing it to be become unloadable by the browsers in published production builds
}

internal sealed class BundleMimeType : IBundleTransform
{
        private readonly string _mimeType;

        public BundleMimeType(string mimeType) { _mimeType = mimeType; }

        public void Process(BundleContext context, BundleResponse response)
        {
                 if (context == null)
                          throw new ArgumentNullException(nameof(context));
                 if (response == null)
                          throw new ArgumentNullException(nameof(response));

         response.ContentType = _mimeType;
        }
}

To make this whole thing work you need to install (via nuget):

WebGrease 1.6.0+ Microsoft.AspNet.Web.Optimization 1.1.3+

And your web.config should be enriched like so:

<runtime>
       [...]
       <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
       </dependentAssembly>
       <dependentAssembly>
              <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
       </dependentAssembly>
        [...]
</runtime>

<!-- setting mimetypes like we do right below is absolutely vital for published builds because for some reason the -->
<!-- iis servers in production environments somehow dont know how to handle otf eot and other font related files   -->
<system.webServer>
        [...]
        <staticContent>
      <!-- in case iis already has these mime types -->
      <remove fileExtension=".otf" />
      <remove fileExtension=".eot" />
      <remove fileExtension=".ttf" />
      <remove fileExtension=".woff" />
      <remove fileExtension=".woff2" />

      <mimeMap fileExtension=".otf" mimeType="font/otf" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
      </staticContent>

      <!-- also vital otherwise published builds wont work  https://stackoverflow.com/a/13597128/863651  -->
      <modules runAllManagedModulesForAllRequests="true">
         <remove name="BundleModule" />
         <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
      </modules>
      [...]
</system.webServer>

Note that you might have to take extra steps to make your css-bundles work in terms of fonts etc. But that's a different story.

Can I nest a <button> element inside an <a> using HTML5?

It is illegal in HTML5 to embed a button element inside a link.

Better to use CSS on the default and :active (pressed) states:

_x000D_
_x000D_
body{background-color:#F0F0F0} /* JUST TO MAKE THE BORDER STAND OUT */_x000D_
a.Button{padding:.1em .4em;color:#0000D0;background-color:#E0E0E0;font:normal 80% sans-serif;font-weight:700;border:2px #606060 solid;text-decoration:none}_x000D_
a.Button:not(:active){border-left-color:#FFFFFF;border-top-color:#FFFFFF}_x000D_
a.Button:active{border-right-color:#FFFFFF;border-bottom-color:#FFFFFF}
_x000D_
<p><a class="Button" href="www.stackoverflow.com">Click me<a>
_x000D_
_x000D_
_x000D_

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

The solution the worked for me is:

I just copied the page and and pasted it in the same portion, then renamed the first page(what ever name) and renamed the copied page as the original page. Now the controls are accessible.

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

I faced this problem

Forbidden You don't have permission to access /phpmyadmin/ on this server

Some help about this:

First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.

Follow these steps.

  1. Open your wamp\bin\mysql directory
  2. Check if in this folder there is another folder of mysql with different name, if exists delete it.
  3. enter to remain mysql folder and delete files with duplication.
  4. start your wamp server again. Wamp will be working.

How do you cache an image in Javascript

There are a few things you can look at:

Pre-loading your images
Setting a cache time in an .htaccess file
File size of images and base64 encoding them.

Preloading: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Caching: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

There are a couple different thoughts for base64 encoding, some say that the http requests bog down bandwidth, while others say that the "perceived" loading is better. I'll leave this up in the air.

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

Pass props in Link react-router

there is a way you can pass more than one parameter. You can pass "to" as object instead of string.

// your route setup
<Route path="/category/:catId" component={Category} / >

// your link creation
const newTo = { 
  pathname: "/category/595212758daa6810cbba4104", 
  param1: "Par1" 
};
// link to the "location"
// see (https://reacttraining.com/react-router/web/api/location)
<Link to={newTo}> </Link>

// In your Category Component, you can access the data like this
this.props.match.params.catId // this is 595212758daa6810cbba4104 
this.props.location.param1 // this is Par1

How to iterate a table rows with JQuery and access some cell values?

try this

var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');

function iterate(selector)
{
  var result = '';
  if ($(selector))
  {
    $(selector).each(function ()
    {
      if (result == '')
      {
        result = $(this).html();
      }
      else
      {
        result = result + "," + $(this).html();
      }
    });
  }
}

Is floating point math broken?

Imagine working in base ten with, say, 8 digits of accuracy. You check whether

1/3 + 2 / 3 == 1

and learn that this returns false. Why? Well, as real numbers we have

1/3 = 0.333.... and 2/3 = 0.666....

Truncating at eight decimal places, we get

0.33333333 + 0.66666666 = 0.99999999

which is, of course, different from 1.00000000 by exactly 0.00000001.


The situation for binary numbers with a fixed number of bits is exactly analogous. As real numbers, we have

1/10 = 0.0001100110011001100... (base 2)

and

1/5 = 0.0011001100110011001... (base 2)

If we truncated these to, say, seven bits, then we'd get

0.0001100 + 0.0011001 = 0.0100101

while on the other hand,

3/10 = 0.01001100110011... (base 2)

which, truncated to seven bits, is 0.0100110, and these differ by exactly 0.0000001.


The exact situation is slightly more subtle because these numbers are typically stored in scientific notation. So, for instance, instead of storing 1/10 as 0.0001100 we may store it as something like 1.10011 * 2^-4, depending on how many bits we've allocated for the exponent and the mantissa. This affects how many digits of precision you get for your calculations.

The upshot is that because of these rounding errors you essentially never want to use == on floating-point numbers. Instead, you can check if the absolute value of their difference is smaller than some fixed small number.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

Reverting to a specific commit based on commit id with Git?

Do you want to roll back your repo to that state, or you just want your local repo to look like that?

If you reset --hard, it will make your local code and local history be just like it was at that commit. But if you wanted to push this to someone else who has the new history, it would fail:

git reset --hard c14809fa

And if you reset --soft, it will move your HEAD to where they were , but leave your local files etc. the same:

git reset --soft c14809fa

So what exactly do you want to do with this reset?

Edit -

You can add "tags" to your repo.. and then go back to a tag. But a tag is really just a shortcut to the sha1.

You can tag this as TAG1.. then a git reset --soft c14809fa, git reset --soft TAG1, or git reset --soft c14809fafb08b9e96ff2879999ba8c807d10fb07 would all do the same thing.

How to create unit tests easily in eclipse

To create a test case template:

"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.

How can I save multiple documents concurrently in Mongoose/Node.js?

You can use the promise returned by mongoose save, Promise in mongoose does not have all, but you can add the feature with this module.

Create a module that enhance mongoose promise with all.

var Promise = require("mongoose").Promise;

Promise.all = function(promises) {
  var mainPromise = new Promise();
  if (promises.length == 0) {
    mainPromise.resolve(null, promises);
  }

  var pending = 0;
  promises.forEach(function(p, i) {
    pending++;
    p.then(function(val) {
      promises[i] = val;
      if (--pending === 0) {
        mainPromise.resolve(null, promises);
      }
    }, function(err) {
      mainPromise.reject(err);
    });
  });

  return mainPromise;
}

module.exports = Promise;

Then use it with mongoose:

var Promise = require('./promise')

...

var tasks = [];

for (var i=0; i < docs.length; i++) {
  tasks.push(docs[i].save());
}

Promise.all(tasks)
  .then(function(results) {
    console.log(results);
  }, function (err) {
    console.log(err);
  })

Disable scrolling in all mobile devices

Try adding

html {
  overflow-x: hidden;
}

as well as

body {
  overflow-x: hidden;
}

Formatting "yesterday's" date in python

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

git checkout all the files

  • If you are in base directory location of your tracked files then git checkout . will works otherwise it won't work

Link to add to Google calendar

There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md

An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole

Can I install the "app store" in an IOS simulator?

You can install other builds but not Appstore build.

From Xcode 8.2,drag and drop the build to simulator for the installation.

https://stackoverflow.com/a/41671233/1522584

SHA-1 fingerprint of keystore certificate

If you are using Android Studio IDE then you can get SHA1 has value for your all build variants with one click.

Under Gradle Projects Window > Select Root Project > signingReport > double click

File Navigation

Next

Open Run Window

Go To Variant: release for release

Go To Variant: debug for debug

http://devdeeds.com/create-sha1-key-using-android-studio/

Replace Div with another Div

You can use .replaceWith()

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $(".region").click(function(e) {_x000D_
    e.preventDefault();_x000D_
    var content = $(this).html();_x000D_
    $('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
  <div class="region"><a href="link1">region1</a></div>_x000D_
  <div class="region"><a href="link2">region2</a></div>_x000D_
  <div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

show/hide html table columns using css

One line of code using jQuery:

$('td:nth-child(2)').hide();

// If your table has header(th), use this:
//$('td:nth-child(2),th:nth-child(2)').hide();

Source: Hide a Table Column with a Single line of jQuery code

Function to calculate R2 (R-squared) in R

You need a little statistical knowledge to see this. R squared between two vectors is just the square of their correlation. So you can define you function as:

rsq <- function (x, y) cor(x, y) ^ 2

Sandipan's answer will return you exactly the same result (see the following proof), but as it stands it appears more readable (due to the evident $r.squared).


Let's do the statistics

Basically we fit a linear regression of y over x, and compute the ratio of regression sum of squares to total sum of squares.

lemma 1: a regression y ~ x is equivalent to y - mean(y) ~ x - mean(x)

lemma 1

lemma 2: beta = cov(x, y) / var(x)

lemma 2

lemma 3: R.square = cor(x, y) ^ 2

lemma 3


Warning

R squared between two arbitrary vectors x and y (of the same length) is just a goodness measure of their linear relationship. Think twice!! R squared between x + a and y + b are identical for any constant shift a and b. So it is a weak or even useless measure on "goodness of prediction". Use MSE or RMSE instead:

I agree with 42-'s comment:

The R squared is reported by summary functions associated with regression functions. But only when such an estimate is statistically justified.

R squared can be a (but not the best) measure of "goodness of fit". But there is no justification that it can measure the goodness of out-of-sample prediction. If you split your data into training and testing parts and fit a regression model on the training one, you can get a valid R squared value on training part, but you can't legitimately compute an R squared on the test part. Some people did this, but I don't agree with it.

Here is very extreme example:

preds <- 1:4/4
actual <- 1:4

The R squared between those two vectors is 1. Yes of course, one is just a linear rescaling of the other so they have a perfect linear relationship. But, do you really think that the preds is a good prediction on actual??


In reply to wordsforthewise

Thanks for your comments 1, 2 and your answer of details.

You probably misunderstood the procedure. Given two vectors x and y, we first fit a regression line y ~ x then compute regression sum of squares and total sum of squares. It looks like you skip this regression step and go straight to the sum of square computation. That is false, since the partition of sum of squares does not hold and you can't compute R squared in a consistent way.

As you demonstrated, this is just one way for computing R squared:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)  ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2)  ## total sum of squares
rsq <- 1 - rss/tss
#[1] 0.25

But there is another:

regss <- sum((preds - mean(preds)) ^ 2) ## regression sum of squares
regss / tss
#[1] 0.75

Also, your formula can give a negative value (the proper value should be 1 as mentioned above in the Warning section).

preds <- 1:4 / 4
actual <- 1:4
rss <- sum((preds - actual) ^ 2)  ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2)  ## total sum of squares
rsq <- 1 - rss/tss
#[1] -2.375

Final remark

I had never expected that this answer could eventually be so long when I posted my initial answer 2 years ago. However, given the high views of this thread, I feel obliged to add more statistical details and discussions. I don't want to mislead people that just because they can compute an R squared so easily, they can use R squared everywhere.

What is the right way to debug in iPython notebook?

After you get an error, in the next cell just run %debug and that's it.

MySQL Multiple Where Clause

You will never get a result, it's a simple logic error.

You're asking your database to return a row which has style_id = 24 AND style_id = 25 AND style_id = 26. Since 24 is niether 25 nor 26, you will get no result.

You have to use OR, then it makes some sense.

For loop in multidimensional javascript array

A bit too late, but this solution is nice and neat

const arr = [[1,2,3],[4,5,6],[7,8,9,10]]
for (let i of arr) {
  for (let j of i) {
    console.log(j) //Should log numbers from 1 to 10
  }
}

Or in your case:

const arr = [[1,2,3],[4,5,6],[7,8,9]]
for (let [d1, d2, d3] of arr) {
  console.log(`${d1}, ${d2}, ${d3}`) //Should return numbers from 1 to 9
}

Note: for ... of loop is standardised in ES6, so only use this if you have an ES5 Javascript Complier (such as Babel)

Another note: There are alternatives, but they have some subtle differences and behaviours, such as forEach(), for...in, for...of and traditional for(). It depends on your case to decide which one to use. (ES6 also has .map(), .filter(), .find(), .reduce())

Import JSON file in React

there are multiple ways to do this without using any third-party code or libraries (the recommended way).

1st STATIC WAY: create a .json file then import it in your react component example

my file name is "example.json"

{"example" : "my text"}

the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.

How to import in react component

import myJson from "jsonlocation";

and you can use it anywhere like this

myJson.example

now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.

Now, what about if we want to dynamically import the JSON data? example a multi-language support website?

2 DYNAMIC WAY

1st declare your JSON file exactly like my example above

but this time we are importing the data differently.

let language = require('./en.json');

this can access the same way.

but wait where is the dynamic load?

here is how to load the JSON dynamically

let language = require(`./${variable}.json`);

now make sure all your JSON files are within the same directory

here you can use the JSON the same way as the first example

myJson.example

what changed? the way we import because it is the only thing we really need.

I hope this helps.

Difference between pre-increment and post-increment in a loop?

Here is a Java-Sample and the Byte-Code, post- and preIncrement show no difference in Bytecode:

public class PreOrPostIncrement {

    static int somethingToIncrement = 0;

    public static void main(String[] args) {
        final int rounds = 1000;
        postIncrement(rounds);
        preIncrement(rounds);
    }

    private static void postIncrement(final int rounds) {
        for (int i = 0; i < rounds; i++) {
            somethingToIncrement++;
        }
    }

    private static void preIncrement(final int rounds) {
        for (int i = 0; i < rounds; ++i) {
            ++somethingToIncrement;
        }
    }
}

And now for the byte-code (javap -private -c PreOrPostIncrement):

public class PreOrPostIncrement extends java.lang.Object{
static int somethingToIncrement;

static {};
Code:
0:  iconst_0
1:  putstatic   #10; //Field somethingToIncrement:I
4:  return

public PreOrPostIncrement();
Code:
0:  aload_0
1:  invokespecial   #15; //Method java/lang/Object."<init>":()V
4:  return

public static void main(java.lang.String[]);
Code:
0:  sipush  1000
3:  istore_1
4:  sipush  1000
7:  invokestatic    #21; //Method postIncrement:(I)V
10: sipush  1000
13: invokestatic    #25; //Method preIncrement:(I)V
16: return

private static void postIncrement(int);
Code:
0:  iconst_0
1:  istore_1
2:  goto    16
5:  getstatic   #10; //Field somethingToIncrement:I
8:  iconst_1
9:  iadd
10: putstatic   #10; //Field somethingToIncrement:I
13: iinc    1, 1
16: iload_1
17: iload_0
18: if_icmplt   5
21: return

private static void preIncrement(int);
Code:
0:  iconst_0
1:  istore_1
2:  goto    16
5:  getstatic   #10; //Field somethingToIncrement:I
8:  iconst_1
9:  iadd
10: putstatic   #10; //Field somethingToIncrement:I
13: iinc    1, 1
16: iload_1
17: iload_0
18: if_icmplt   5
21: return

}

Change hover color on a button with Bootstrap customization

or can do this...
set all btn ( class name like : .btn- + $theme-colors: map-merge ) styles at one time :

@each $color, $value in $theme-colors {
  .btn-#{$color} {
    @include button-variant($value, $value,
    // modify
    $hover-background: lighten($value, 7.5%),
    $hover-border: lighten($value, 10%),
    $active-background: lighten($value, 10%),
    $active-border: lighten($value, 12.5%)
    // /modify
    );
  }
}

// code from "node_modules/bootstrap/scss/_buttons.scss"

should add into your customization scss file.

Java Comparator class to sort arrays

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

Basic HTTP authentication with Node and Express 4

function auth (req, res, next) {
  console.log(req.headers);
  var authHeader = req.headers.authorization;
  if (!authHeader) {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');
      err.status = 401;
      next(err);
      return;
  }
  var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
  var user = auth[0];
  var pass = auth[1];
  if (user == 'admin' && pass == 'password') {
      next(); // authorized
  } else {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');      
      err.status = 401;
      next(err);
  }
}
app.use(auth);

how to destroy an object in java?

In java there is no explicit way doing garbage collection. The JVM itself runs some threads in the background checking for the objects that are not having any references which means all the ways through which we access the object are lost. On the other hand an object is also eligible for garbage collection if it runs out of scope that is the program in which we created the object is terminated or ended. Coming to your question the method finalize is same as the destructor in C++. The finalize method is actually called just before the moment of clearing the object memory by the JVM. It is up to you to define the finalize method or not in your program. However if the garbage collection of the object is done after the program is terminated then the JVM will not invoke the finalize method which you defined in your program. You might ask what is the use of finalize method? For instance let us consider that you created an object which requires some stream to external file and you explicitly defined a finalize method to this object which checks wether the stream opened to the file or not and if not it closes the stream. Suppose, after writing several lines of code you lost the reference to the object. Then it is eligible for garbage collection. When the JVM is about to free the space of your object the JVM just checks have you defined the finalize method or not and invokes the method so there is no risk of the opened stream. finalize method make the program risk free and more robust.

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

Difference between onLoad and ng-init in angular

Works for me.

<div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>

How to display the function, procedure, triggers source code in postgresql?

For function:

you can query the pg_proc view , just as the following

select proname,prosrc from pg_proc where proname= your_function_name; 

Another way is that just execute the commont \df and \ef which can list the functions.

skytf=> \df           
                                             List of functions
 Schema |         Name         | Result data type |              Argument data types               |  Type  
--------+----------------------+------------------+------------------------------------------------+--------
 public | pg_buffercache_pages | SETOF record     |                                                | normal


skytf=> \ef  pg_buffercache_pages

It will show the source code of the function.

For triggers:

I dont't know if there is a direct way to get the source code. Just know the following way, may be it will help you!

  • step 1 : Get the table oid of the trigger:
    skytf=> select tgrelid from pg_trigger  where tgname='insert_tbl_tmp_trigger';
      tgrelid
    ---------
       26599
    (1 row)
  • step 2: Get the table name of the above oid !
    skytf=> select oid,relname  from pg_class where oid=26599;
      oid  |           relname           
    -------+-----------------------------
     26599 | tbl_tmp
    (1 row)
  • step 3: list the table information
    skytf=> \d tbl_tmp

It will show you the details of the trigger of the table . Usually a trigger uses a function. So you can get the source code of the trigger function just as the above that I pointed out !

Force SSL/https using .htaccess and mod_rewrite

Simple and Easy , just add following

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How to access the correct `this` inside a callback?

I was facing problem with Ngx line chart xAxisTickFormatting function which was called from HTML like this: [xAxisTickFormatting]="xFormat". I was unable to access my component's variable from the function declared. This solution helped me to resolve the issue to find the correct this. Hope this helps the Ngx line chart, users.

instead of using the function like this:

xFormat (value): string {
  return value.toString() + this.oneComponentVariable; //gives wrong result 
}

Use this:

 xFormat = (value) => {
   // console.log(this);
   // now you have access to your component variables
   return value + this.oneComponentVariable
 }

How to place two forms on the same page?

Well you can have each form go to to a different page. (which is preferable)

Or have a different value for the a certain input and base posts on that:

switch($_POST['submit']) {
    case 'login': 
    //...
    break;
    case 'register':
    //...
    break;
}

Set environment variables from file of key/value pairs

Here is another sed solution, which does not run eval or require ruby:

source <(sed -E -n 's/[^#]+/export &/ p' ~/.env)

This adds export, keeping comments on lines starting with a comment.

.env contents

A=1
#B=2

sample run

$ sed -E -n 's/[^#]+/export &/ p' ~/.env
export A=1
#export B=2

I found this especially useful when constructing such a file for loading in a systemd unit file, with EnvironmentFile.

Android Fastboot devices not returning device

If you got nothing when inputted fastboot devices, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-'). Then you can see you devices via fastboot devices and continue to flash your devices.

note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.

Strip out HTML and Special Characters

In a more detailed manner from Above example, Considering below is your string:

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! ??? ?? ????? ??????! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text ?? ???? test 123 ?,.m,............ ~~~ ??]??}~?]?}"; ';

Code:

echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));

Allows: English letters (Capital and small), 0 to 9 and characters !@#$%^&*().

Removes: All html tags, and special characters other than above

How to decode a QR-code image in (preferably pure) Python?

There is a library called BoofCV which claims to better than ZBar and other libraries.
Here are the steps to use that (any OS).

Pre-requisites:

  • Ensure JDK 14+ is installed and set in $PATH
  • pip install pyboof

Class to decode:

import os
import numpy as np
import pyboof as pb

pb.init_memmap() #Optional

class QR_Extractor:
    # Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
    def __init__(self):
        self.detector = pb.FactoryFiducial(np.uint8).qrcode()
    
    def extract(self, img_path):
        if not os.path.isfile(img_path):
            print('File not found:', img_path)
            return None
        image = pb.load_single_band(img_path, np.uint8)
        self.detector.detect(image)
        qr_codes = []
        for qr in self.detector.detections:
            qr_codes.append({
                'text': qr.message,
                'points': qr.bounds.convert_tuple()
            })
        return qr_codes

Usage:

qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)

Tested and works on Python 3.8 (Windows & Ubuntu)

javascript clear field value input

HTML:

<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>

JS:

function clearField(input) {
  if(input.value=="Name") { //Only clear if value is "Name"
    input.value = "";
  }
}
function fillField(input) {
    if(input.value=="") {
        input.value = "Name";
    }
}

How to convert string to binary?

Something like this?

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

SQL Server command line backup statement

if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...

Execute another jar in a Java program

Hope this helps:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}

Apply multiple functions to multiple groupby columns

Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:

create a dataframe

df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})


   a  b  c
0  1  1  x
1  2  1  x
2  3  0  y
3  4  1  y
4  5  1  z
5  6  0  z

grouping and aggregating with apply (using multiple columns)

df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

c
x    2.0
y    4.0
z    5.0

grouping and aggregating with aggregate (using multiple columns)

I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.

It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.

only access to the selected column

df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())

access to all columns since selection is after all the magic

df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']

or similarly

df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

I hope this helps.

Convert Variable Name to String?

TL;DR: Not possible. See 'conclusion' at the end.


There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.

This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.

What would be needed, is the reverse of the eval() function:

get_indentifier_name_missing_function()

which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name.


Consider the following current state of affairs:

random_function(argument_data)

If one is passing an identifier name ('function','variable','dictionary',etc) argument_data to a random_function() (another identifier name), one actually passes an identifier (e.g.: <argument_data object at 0xb1ce10>) to another identifier (e.g.: <function random_function at 0xafff78>):

<function random_function at 0xafff78>(<argument_data object at 0xb1ce10>)

From my understanding, only the memory address is passed to the function:

<function at 0xafff78>(<object at 0xb1ce10>)

Therefore, one would need to pass a string as an argument to random_function() in order for that function to have the argument's identifier name:

random_function('argument_data')

Inside the random_function()

def random_function(first_argument):

, one would use the already supplied string 'argument_data' to:

  1. serve as an 'identifier name' (to display, log, string split/concat, whatever)

  2. feed the eval() function in order to get a reference to the actual identifier, and therefore, a reference to the real data:

    print("Currently working on", first_argument)
    some_internal_var = eval(first_argument)
    print("here comes the data: " + str(some_internal_var))
    

Unfortunately, this doesn't work in all cases. It only works if the random_function() can resolve the 'argument_data' string to an actual identifier. I.e. If argument_data identifier name is available in the random_function()'s namespace.

This isn't always the case:

# main1.py
import some_module1

argument_data = 'my data'

some_module1.random_function('argument_data')


# some_module1.py
def random_function(first_argument):
    print("Currently working on", first_argument)
    some_internal_var = eval(first_argument)
    print("here comes the data: " + str(some_internal_var))
######

Expected results would be:

Currently working on: argument_data
here comes the data: my data

Because argument_data identifier name is not available in the random_function()'s namespace, this would yield instead:

Currently working on argument_data
Traceback (most recent call last):
  File "~/main1.py", line 6, in <module>
    some_module1.random_function('argument_data')
  File "~/some_module1.py", line 4, in random_function
    some_internal_var = eval(first_argument)
  File "<string>", line 1, in <module>
NameError: name 'argument_data' is not defined

Now, consider the hypotetical usage of a get_indentifier_name_missing_function() which would behave as described above.

Here's a dummy Python 3.0 code: .

# main2.py
import some_module2
some_dictionary_1       = { 'definition_1':'text_1',
                            'definition_2':'text_2',
                            'etc':'etc.' }
some_other_dictionary_2 = { 'key_3':'value_3',
                            'key_4':'value_4', 
                            'etc':'etc.' }
#
# more such stuff
#
some_other_dictionary_n = { 'random_n':'random_n',
                            'etc':'etc.' }

for each_one_of_my_dictionaries in ( some_dictionary_1,
                                     some_other_dictionary_2,
                                     ...,
                                     some_other_dictionary_n ):
    some_module2.some_function(each_one_of_my_dictionaries)


# some_module2.py
def some_function(a_dictionary_object):
    for _key, _value in a_dictionary_object.items():
        print( get_indentifier_name_missing_function(a_dictionary_object)    +
               "    " +
               str(_key) +
               "  =  " +
               str(_value) )
######

Expected results would be:

some_dictionary_1    definition_1  =  text_1
some_dictionary_1    definition_2  =  text_2
some_dictionary_1    etc  =  etc.
some_other_dictionary_2    key_3  =  value_3
some_other_dictionary_2    key_4  =  value_4
some_other_dictionary_2    etc  =  etc.
......
......
......
some_other_dictionary_n    random_n  =  random_n
some_other_dictionary_n    etc  =  etc.

Unfortunately, get_indentifier_name_missing_function() would not see the 'original' identifier names (some_dictionary_,some_other_dictionary_2,some_other_dictionary_n). It would only see the a_dictionary_object identifier name.

Therefore the real result would rather be:

a_dictionary_object    definition_1  =  text_1
a_dictionary_object    definition_2  =  text_2
a_dictionary_object    etc  =  etc.
a_dictionary_object    key_3  =  value_3
a_dictionary_object    key_4  =  value_4
a_dictionary_object    etc  =  etc.
......
......
......
a_dictionary_object    random_n  =  random_n
a_dictionary_object    etc  =  etc.

So, the reverse of the eval() function won't be that useful in this case.


Currently, one would need to do this:

# main2.py same as above, except:

    for each_one_of_my_dictionaries_names in ( 'some_dictionary_1',
                                               'some_other_dictionary_2',
                                               '...',
                                               'some_other_dictionary_n' ):
        some_module2.some_function( { each_one_of_my_dictionaries_names :
                                     eval(each_one_of_my_dictionaries_names) } )
    
    
    # some_module2.py
    def some_function(a_dictionary_name_object_container):
        for _dictionary_name, _dictionary_object in a_dictionary_name_object_container.items():
            for _key, _value in _dictionary_object.items():
                print( str(_dictionary_name) +
                       "    " +
                       str(_key) +
                       "  =  " +
                       str(_value) )
    ######

In conclusion:

  • Python passes only memory addresses as arguments to functions.
  • Strings representing the name of an identifier, can only be referenced back to the actual identifier by the eval() function if the name identifier is available in the current namespace.
  • A hypothetical reverse of the eval() function, would not be useful in cases where the identifier name is not 'seen' directly by the calling code. E.g. inside any called function.
  • Currently one needs to pass to a function:
    1. the string representing the identifier name
    2. the actual identifier (memory address)

This can be achieved by passing both the 'string' and eval('string') to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the eval() function which may easily lead to unsecured code. Care must be taken to not feed the eval() function with just about anything, especially unfiltered external-input data.

Open new Terminal Tab from command line (Mac OS X)

What about this simple snippet, based on a standard script command (echo):

# set mac osx's terminal title to "My Title"
echo -n -e "\033]0;My Title\007"

Angularjs on page load call function

you can use it directly with $scope instance

     $scope.init=function()
        {
            console.log("entered");
            data={};
            /*do whatever you want such as initialising scope variable,
              using $http instance etcc..*/
        }
       //simple call init function on controller
       $scope.init();

Example use of "continue" statement in Python?

def filter_out_colors(elements):
  colors = ['red', 'green']
  result = []
  for element in elements:
    if element in colors:
       continue # skip the element
    # You can do whatever here
    result.append(element)
  return result

  >>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
  ['lemon', 'orange', 'pear']

How to convert Blob to File in JavaScript

I have used FileSaver.js to save the blob as file.

This is the repo : https://github.com/eligrey/FileSaver.js/

Usage:

import { saveAs } from 'file-saver';

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

saveAs("https://httpbin.org/image", "image.jpg");

How to call two methods on button's onclick method in HTML or JavaScript?

As stated by Harry Joy, you can do it on the onclick attr like so:

<input type="button" onclick="func1();func2();" value="Call2Functions" />

Or, in your JS like so:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1();
    func2();
};

Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):

var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
    func1 = Call2FunctionsEle.onclick;

Call2FunctionsEle.onclick = function()
{
    if( typeof func1 === 'function' )
    {
        func1();
    }
    func2();
};

If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1.apply( this, arguments );
    func2.apply( this, arguments );
};

How to create a directory in Java?

This function allows you to create a directory on the user home directory.

private static void createDirectory(final String directoryName) {
    final File homeDirectory = new File(System.getProperty("user.home"));
    final File newDirectory = new File(homeDirectory, directoryName);
    if(!newDirectory.exists()) {
        boolean result = newDirectory.mkdir();

        if(result) {
            System.out.println("The directory is created !");
        }
    } else {
        System.out.println("The directory already exist");
    }
}

How to check ASP.NET Version loaded on a system?

I had same problem to find a way to check whether ASP.NET 4.5 is on the Server. Because v4.5 is in place replace to v4.0, if you look at c:\windows\Microsoft.NET\Framework, you will not see v4.5 folder. Actually there is a simple way to see the version installed in the machine. Under Windows Server 2008 or Windows 7, just go to control panel -> Programs and Features, you will find "Microsoft .NET Framework 4.5" if it is installed.

Communication between tabs or windows

Another method that people should consider using is Shared Workers. I know it's a cutting edge concept, but you can create a relay on a Shared Worker that is MUCH faster than localstorage, and doesn't require a relationship between the parent/child window, as long as you're on the same origin.

See my answer here for some discussion I made about this.

Update Angular model after setting input value with jQuery

The accepted answer which was triggering input event with jQuery didn't work for me. Creating an event and dispatching with native JavaScript did the trick.

$("input")[0].dispatchEvent(new Event("input", { bubbles: true }));

PHP: Limit foreach() statement?

this is best solution for me :)

$i=0;
foreach() if ($i < yourlimitnumber) {

$i +=1;
}

Include PHP file into HTML file

In order to get the PHP output into the HTML file you need to either

  • Change the extension of the HTML to file to PHP and include the PHP from there (simple)
  • Load your HTML file into your PHP as a kind of template (a lot of work)
  • Change your environment so it deals with HTML as if it was PHP (bad idea)

selectOneMenu ajax events

You could check whether the value of your selectOneMenu component belongs to the list of subjects.

Namely:

public void subjectSelectionChanged() {
    // Cancel if subject is manually written
    if (!subjectList.contains(aktNachricht.subject)) { return; }
    // Write your code here in case the user selected (or wrote) an item of the list
    // ....
}

Supposedly subjectList is a collection type, like ArrayList. Of course here your code will run in case the user writes an item of your selectOneMenu list.

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

Find distance between two points on map using Google Map API V2

you can use this function. I have used it in my project.

public String getDistance(LatLng my_latlong, LatLng frnd_latlong) {
    Location l1 = new Location("One");
    l1.setLatitude(my_latlong.latitude);
    l1.setLongitude(my_latlong.longitude);

    Location l2 = new Location("Two");
    l2.setLatitude(frnd_latlong.latitude);
    l2.setLongitude(frnd_latlong.longitude);

    float distance = l1.distanceTo(l2);
    String dist = distance + " M";

    if (distance > 1000.0f) {
        distance = distance / 1000.0f;
        dist = distance + " KM";
    }
    return dist;
}

Can Json.NET serialize / deserialize to / from a stream?

public static void Serialize(object value, Stream s)
{
    using (StreamWriter writer = new StreamWriter(s))
    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
    {
        JsonSerializer ser = new JsonSerializer();
        ser.Serialize(jsonWriter, value);
        jsonWriter.Flush();
    }
}

public static T Deserialize<T>(Stream s)
{
    using (StreamReader reader = new StreamReader(s))
    using (JsonTextReader jsonReader = new JsonTextReader(reader))
    {
        JsonSerializer ser = new JsonSerializer();
        return ser.Deserialize<T>(jsonReader);
    }
}

How to use adb command to push a file on device without sd card

My solution (example with a random mp4 video file):

  1. Set a file to device:

    adb push /home/myuser/myVideoFile.mp4 /storage/emulated/legacy/
    
  2. Get a file from device:

    adb pull /storage/emulated/legacy/myVideoFile.mp4 
    

For retrieve the path in the code:

String myFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myVideoFile.mp4";

This is all. This solution doesn't give permission problems and it works fine.

Last point: I wanted to change the video metadata information. If you want to write into your device you should change the permission in the AndroidManifest.xml. Add this line:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Setting background color for a JFrame

Retrieve the content pane for the frame and use the setBackground() method inherited from Component to change the color.

Example:

myJFrame.getContentPane().setBackground( desiredColor );

How can I check the current status of the GPS receiver?

The GPS icon seems to change its state according to received broadcast intents. You can change its state yourself with the following code samples:

Notify that the GPS has been enabled:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

Notify that the GPS is receiving fixes:

Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

Notify that the GPS is no longer receiving fixes:

Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);

Notify that the GPS has been disabled:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);

Example code to register receiver to the intents:

// MyReceiver must extend BroadcastReceiver
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter("android.location.GPS_ENABLED_CHANGE");
filter.addAction("android.location.GPS_FIX_CHANGE");
registerReceiver(receiver, filter);

By receiving these broadcast intents you can notice the changes in GPS status. However, you will be notified only when the state changes. Thus it is not possible to determine the current state using these intents.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  

Edit: or as @ CarlWitthoft suggested in the comments:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))

Send and receive messages through NSNotificationCenter in Objective-C?

To expand upon dreamlax's example... If you want to send data along with the notification

In posting code:

NSDictionary *userInfo = 
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName: 
                       @"TestNotification" object:nil userInfo:userInfo];

In observing code:

- (void) receiveTestNotification:(NSNotification *) notification {

    NSDictionary *userInfo = notification.userInfo;
    MyObject *myObject = [userInfo objectForKey:@"someKey"];
}