Programs & Examples On #Multipoint

How do I convert a byte array to Base64 in Java?

Java 8+

Encode or decode byte arrays:

byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded)    // Outputs "Hello"

For more info, see Base64.

Java < 8

Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.

For direct byte arrays:

Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = codec.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(codec.decodeBase64(encoded));
println(decoded)    // Outputs "Hello"

Spring

If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils class more ergonomic:

For direct byte arrays:

byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded))    // Outputs "Hello"

Android (with Java < 8)

If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64.

For direct byte arrays:

byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte [] decoded = Base64.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.decode(encoded));
println(decoded)    // Outputs "Hello"

MS Excel showing the formula in a cell instead of the resulting value

If you are using Excel 2013 Than do the following File > Option > Advanced > Under Display options for this worksheet: uncheck the checkbox before Show formulas in cells instead of their calculated results This should resolve the issue.

How to start an application without waiting in a batch file?

If your exe takes arguments,

start MyApp.exe -arg1 -arg2

How to check if an alert exists using WebDriver?

public boolean isAlertPresent() 
{ 
    try 
    { 
        driver.switchTo().alert(); 
        return true; 
    }   // try 
    catch (NoAlertPresentException Ex) 
    { 
        return false; 
    }   // catch 
}   // isAlertPresent()

check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

How to install Python packages from the tar.gz file without using pip install

For those of you using python3 you can use:

python3 setup.py install

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

I've changed the recursion to iteration.

def MovingTheBall(listOfBalls,position,numCell):
while 1:
    stop=1
    positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
    for i in range(0,len(listOfBalls)):
        if positionTmp==listOfBalls[i].pos:
            stop=0
    if stop==1:
        if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
            stop=0
        else:
            return positionTmp

Works good :D

How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

gradlew: Permission Denied

Try to set the execution flag on your gradlew file:

chmod +x gradlew

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value

How to get equal width of input and select fields

Add this code in css:

 select, input[type="text"]{
      width:100%;
      box-sizing:border-box;
    }

concatenate variables

If you need to concatenate paths with quotes, you can use = to replace quotes in a variable. This does not require you to know if the path already contains quotes or not. If there are no quotes, nothing is changed.

@echo off
rem Paths to combine
set DIRECTORY="C:\Directory with spaces"
set FILENAME="sub directory\filename.txt"

rem Combine two paths
set COMBINED="%DIRECTORY:"=%\%FILENAME:"=%"
echo %COMBINED%

rem This is just to illustrate how the = operator works
set DIR_WITHOUT_SPACES=%DIRECTORY:"=%
echo %DIR_WITHOUT_SPACES%

CreateProcess error=2, The system cannot find the file specified

Assuming that winrar.exe is in the PATH, then Runtime.exec is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe is installed in C:/Program Files/WinRAR you would need to use something like...

p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");

Personally, I would recommend that you use ProcessBuilder as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String elements, it deals with things like spaces much better then a single String variable, for example...

ProcessBuilder pb = new ProcessBuilder(
    "C:/Program Files/WinRAR/winrar",
    "x",
    "myjar.jar",
    "*.*",
    "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

Don't forget to read the contents of the InputStream from the process, as failing to do so may stall the process

set up device for development (???????????? no permissions)

You should NOT run adb server as root as other answers are suggesting. Instead if you are using Arch Linux do the following:

  1. Install the android-udev package with Pacman
  2. Reload udev rules:

    # udevadm control --reload-rules
    
  3. Add yourself to adbusers group and then logout and login:

    # usermod -aG adbusers $LOGNAME
    

Source: https://wiki.archlinux.org/index.php/android#Configuring_adb

MySQL LEFT JOIN Multiple Conditions

SELECT * FROM a WHERE a.group_id IN 
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';

Unable to open debugger port in IntelliJ

Set the MAVEN_OPTS. It should work !!

export MAVEN_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n"

mvn spring-boot:run -Dserver.port=8090

What is /dev/null 2>&1?

This is the way to execute a program quietly, and hide all its output.

/dev/null is a special filesystem object that discards everything written into it. Redirecting a stream into it means hiding your program's output.

The 2>&1 part means "redirect the error stream into the output stream", so when you redirect the output stream, error stream gets redirected as well. Even if your program writes to stderr now, that output would be discarded as well.

Short IF - ELSE statement

I'm a little late to the party but for future readers.

From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the ! operator?

jxPanel6.setVisible(!jxPanel6.isVisible);

It's not an if statement but I prefer this method for code related to your example.

How do I disable a Pylint warning?

There are several ways to disable warnings & errors from Pylint. Which one to use has to do with how globally or locally you want to apply the disablement -- an important design decision.

Multiple Approaches

  1. In one or more pylintrc files.

This involves more than the ~/.pylintrc file (in your $HOME directory) as described by Chris Morgan. Pylint will search for rc files, with a precedence that values "closer" files more highly:

  • A pylintrc file in the current working directory; or

  • If the current working directory is in a Python module (i.e. it contains an __init__.py file), searching up the hierarchy of Python modules until a pylintrc file is found; or

  • The file named by the environment variable PYLINTRC; or

  • If you have a home directory that isn’t /root:

    • ~/.pylintrc; or

    • ~/.config/pylintrc; or

    • /etc/pylintrc

Note that most of these files are named pylintrc -- only the file in ~ has a leading dot.

To your pylintrc file, add lines to disable specific pylint messages. For example:

[MESSAGES CONTROL]
disable=locally-disabled
  1. Further disables from the pylint command line, as described by Aboo and Cairnarvon. This looks like pylint --disable=bad-builtin. Repeat --disable to suppress additional items.

  2. Further disables from individual Python code lines, as described by Imolit. These look like some statement # pylint: disable=broad-except (extra comment on the end of the original source line) and apply only to the current line. My approach is to always put these on the end of other lines of code so they won't be confused with the block style, see below.

  3. Further disables defined for larger blocks of Python code, up to complete source files.

    • These look like # pragma pylint: disable=bad-whitespace (note the pragma key word).

    • These apply to every line after the pragma. Putting a block of these at the top of a file makes the suppressions apply to the whole file. Putting the same block lower in the file makes them apply only to lines following the block. My approach is to always put these on a line of their own so they won't be confused with the single-line style, see above.

    • When a suppression should only apply within a span of code, use # pragma pylint: enable=bad-whitespace (now using enable not disable) to stop suppressing.

Note that disabling for a single line uses the # pylint syntax while disabling for this line onward uses the # pragma pylint syntax. These are easy to confuse especially when copying & pasting.

Putting It All Together

I usually use a mix of these approaches.

  • I use ~/.pylintrc for absolutely global standards -- very few of these.

  • I use project-level pylintrc at different levels within Python modules when there are project-specific standards. Especially when you're taking in code from another person or team, you may find they use conventions that you don't prefer, but you don't want to rework the code. Keeping the settings at this level helps not spread those practices to other projects.

  • I use the block style pragmas at the top of single source files. I like to turn the pragmas off (stop suppressing messages) in the heat of development even for Pylint standards I don't agree with (like "too few public methods" -- I always get that warning on custom Exception classes) -- but it's helpful to see more / maybe all Pylint messages while you're developing. That way you can find the cases you want to address with single-line pragmas (see below), or just add comments for the next developer to explain why that warning is OK in this case.

  • I leave some of the block-style pragmas enabled even when the code is ready to check in. I try to use few of those, but when it makes sense for the module, it's OK to do as documentation. However I try to leave as few on as possible, preferably none.

  • I use the single-line-comment style to address especially potent errors. For example, if there's a place where it actually makes sense to do except Exception as exc, I put the # pylint: disable=broad-except on that line instead of a more global approach because this is a strange exception and needs to be called out, basically as a form of documentation.


Like everything else in Python, you can act at different levels of indirection. My advice is to think about what belongs at what level so you don't end up with a too-lenient approach to Pylint.

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

In order to not have the Cannot recover key exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.


Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy. Setting that to unlimited with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty() or via the java.security file. The java.security file could also be appended to by adding -Djava.security.properties=my_security.properties to the command to start the program as detailed here.


Since JDK 8u161 unlimited cryptography is enabled by default.

Convert a dta file to csv without Stata software

The R method will work reliably, and it requires little knowledge of R. Note that the conversion using the foreign package will preserve data, but may introduce differences. For example, when converting a table without a primary key, the primary key and associated columns will be inserted during the conversion.

From http://www.r-bloggers.com/using-r-for-stata-to-csv-conversion/ I recommend:

library(foreign)
write.table(read.dta(file.choose()), file=file.choose(), quote = FALSE, sep = ",")

Prevent Default on Form Submit jQuery

Use the new "on" event syntax.

$(document).ready(function() {
  $('form').on('submit', function(e){
    // validation code here
    if(!valid) {
      e.preventDefault();
    }
  });
});

Cite: https://api.jquery.com/on/

Box shadow in IE7 and IE8

in ie8 you can try

-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
 filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');

caveat: in ie8 you loose smooth fonts for some reason, they will look ragged

Get selected item value from Bootstrap DropDown with specific ID

The selector would be #demolist.dropdown-menu li a note no space between id and class. However i would suggest a more generic approach:

<div class="input-group">                                            
    <input type="TextBox" Class="form-control datebox"></input>
    <div class="input-group-btn">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>
    </ul>
</div>


$(document).on('click', '.dropdown-menu li a', function() {
    $(this).parent().parent().parent().find('.datebox').val($(this).html());
}); 

by using a class rather than id, and using parent().find(), you can have as many of these on a page as you like, with no duplicated js

Apache: "AuthType not set!" 500 Error

Remove the line that says

Require all granted

it's only needed on Apache >=2.4

Internal vs. Private Access Modifiers

Private members are accessible only within the body of the class or the struct in which they are declared.

Internal types or members are accessible only within files in the same assembly

How to include !important in jquery

Apparently it's possible to do this in jQuery:

$("#tabs").css("cssText", "height: 650px !important;");

Src: http://bugs.jquery.com/ticket/2066

How do I download a file with Angular2 or greater

Update to Hector's answer using file-saver and HttpClient for step 2:

public downloadFile(file: File): Observable<Blob> {
    return this.http.get(file.fullPath, {responseType: 'blob'})
}

In STL maps, is it better to use map::insert than []?

The difference between insert() and operator[] has already been well explained in the other answers. However, new insertion methods for std::map were introduced with C++11 and C++17 respectively:

Let me give a brief summary of the "new" insertion methods:

  • emplace(): When used correctly, this method can avoid unnecessary copy or move operations by constructing the element to be inserted in place. Similar to insert(), an element is only inserted if there is no element with the same key in the container.
  • insert_or_assign(): This method is an "improved" version of operator[]. Unlike operator[], insert_or_assign() doesn't require the map's value type to be default constructible. This overcomes the disadvantage mentioned e.g. in Greg Rogers' answer.
  • try_emplace(): This method is an "improved" version of emplace(). Unlike emplace(), try_emplace() doesn't modify its arguments (due to move operations) if insertion fails due to a key already existing in the map.

For more details on insert_or_assign() and try_emplace() please see my answer here.

Simple example code on Coliru

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

This would definitely help Many!

private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
    {
        if(e.nButton==2)
        {
            contextMenuStrip1.Show(MousePosition);
        }
    }

[ e.nbutton==2 ] is like [ e.button==MouseButtons.Right ]

Android Studio 3.0 Flavor Dimension Issue

After trying and reading carefully, I solved it myself. Solution is to add the following line in build.gradle.

flavorDimensions "versionCode"

android { 
       compileSdkVersion 24
       .....
       flavorDimensions "versionCode"
} 

What are NR and FNR and what does "NR==FNR" imply?

There are awk built-in variables.

NR - It gives the total number of records processed.

FNR - It gives the total number of records for each input file.

Is it possible to run CUDA on AMD GPUs?

You can't use CUDA for GPU Programming as CUDA is supported by NVIDIA devices only. If you want to learn GPU Computing I would suggest you to start CUDA and OpenCL simultaneously. That would be very much beneficial for you.. Talking about CUDA, you can use mCUDA. It doesn't require NVIDIA's GPU..

Hive insert query like SQL

You can't do insert into to insert single record. It's not supported by Hive. You may place all new records that you want to insert in a file and load that file into a temp table in Hive. Then using insert overwrite..select command insert those rows into a new partition of your main Hive table. The constraint here is your main table will have to be pre partitioned. If you don't use partition then your whole table will be replaced with these new records.

How to start nginx via different port(other than 80)

If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.

server {
    listen       80;
    server_name  localhost;
....

Change the port number and restart the instance.

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I have fixed the by this way:

Create a folder in your resource directory name "drawable-nodpi" and then move yours all resources in this directory from others drawable directory.

Now clean your project and then rebuilt. Run again hopefully it will work this time without any resource not found exception.

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

What is new in .NET Framework 4.5 & What's new and expected in .NET Framework 4.5:

  • Support for Windows Runtime
  • Support for Metro Style Applications
  • Support for Async Programming
  • Garbage Collector Improvements
  • Faster ASP.NET Startup
  • Better Data Access Support
  • WebSockets Support
  • Workflow Support - BCL Support

differences in ASP.NET in these frameworks

Compare What's New in ASP.NET 4 and Visual Web Developer and What's New in ASP.NET 4.5 and Visual Studio 11 Beta:

Asp.net 4.0

  • Web.config File Refactoring
  • Extensible Output Caching
  • Auto-Start Web Applications
  • Permanently Redirecting a Page
  • Shrinking Session State
  • Expanding the Range of Allowable URLs
  • Extensible Request Validation
  • Object Caching and Object Caching Extensibility
  • Extensible HTML, URL, and HTTP Header Encoding
  • Performance Monitoring for Individual Applications in a Single Worker Process
  • Multi-Targeting
  • etc

And for Asp.net 4.5 there is also a long list of improvements:

  • Asynchronously Reading and Writing HTTP Requests and Responses
  • Improvements to HttpRequest handling
  • Asynchronously flushing a response
  • Support for await and Task-Based Asynchronous Modules and Handlers

differences in C# also in these frameworks

Go Through C# 4.0 - New C# Features in the .NET Framework and What's New for Visual C# in Visual Studio 11 Beta.

Edit:
The languages documentation for C# and VB breaking changes:

VB: Visual Basic Breaking Changes in Visual Studio 2012

C#: Visual C# Breaking Changes in Visual Studio 2012

Hope this help you get what are you looking for..

Executing JavaScript after X seconds

setTimeout will help you to execute any JavaScript code based on the time you set.

Syntax

setTimeout(code, millisec, lang)

Usage,

setTimeout("function1()", 1000);

For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp

How to print all session variables currently set?

session_start();
echo '<pre>';var_dump($_SESSION);echo '</pre>';
// or
echo '<pre>';print_r($_SESSION);echo '</pre>';

NOTE: session_start(); line is must then only you will able to print the value $_SESSION

Nested JSON objects - do I have to use arrays for everything?

Every object has to be named inside the parent object:

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

So you cant declare an object like this:

var obj = {property1, property2};

It has to be

var obj = {property1: 'value', property2: 'value'};

How can I change a file's encoding with vim?

While using vim to do it is perfectly possible, why don't you simply use iconv? I mean - loading text editor just to do encoding conversion seems like using too big hammer for too small nail.

Just:

iconv -f utf-16 -t utf-8 file.xml > file.utf8.xml

And you're done.

jQuery - Detect value change on hidden input field

Although this thread is 3 years old, here is my solution:

$(function ()
{
    keep_fields_uptodate();
});

function keep_fields_uptodate()
{
    // Keep all fields up to date!
    var $inputDate = $("input[type='date']");
    $inputDate.blur(function(event)
    {
        $("input").trigger("change");
    });
}

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

Is there a way to make npm install (the command) to work behind proxy?

Go TO Environment Variables and Either Remove or set it to empty

HTTP_PROXY and HTTPS_PROXY

it will resolve proxy issue for corporate env too

java.lang.IllegalArgumentException: View not attached to window manager

alex,

I could be wrong here, but I suspect that multiple phones 'in the wild' have a bug that causes them to switch orientation on applications that are marked as statically oriented. This happens quite a bit on my personal phone, and on many of the test phones our group uses (including droid, n1, g1, hero). Typically an app marked as statically oriented (perhaps vertically) will lay itself out for a second or two using a horizontal orientation, and then immediately switch back. End result is that even though you don't want your app to switch orientation, you have to be prepared that it may. I don't know under what exact conditions this behavior can be reproduced, I don't know if it is specific to a version of Android. All I know is that I have seen it happen plenty of times :(

I would recommend using the solution provided in the link you posted that suggests overriding the Activity onCreateDialog method and letting the Android OS manage the lifecycle of your Dialogs. It looks to me like even though you don't want your activity to switch orientations, it is switching orientation somewhere. You can try to track down a method that will always prevent orientation switching, but I am trying to tell you that I personally don't believe there is a foolproof way that works on all current Android phones in the market.

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

Reflection - get attribute name and value on property

public static class PropertyInfoExtensions
{
    public static TValue GetAttributValue<TAttribute, TValue>(this PropertyInfo prop, Func<TAttribute, TValue> value) where TAttribute : Attribute
    {
        var att = prop.GetCustomAttributes(
            typeof(TAttribute), true
            ).FirstOrDefault() as TAttribute;
        if (att != null)
        {
            return value(att);
        }
        return default(TValue);
    }
}

Usage:

 //get class properties with attribute [AuthorAttribute]
        var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
            foreach (var prop in props)
            {
               string value = prop.GetAttributValue((AuthorAttribute a) => a.Name);
            }

or:

 //get class properties with attribute [AuthorAttribute]
        var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
        IList<string> values = props.Select(prop => prop.GetAttributValue((AuthorAttribute a) => a.Name)).Where(attr => attr != null).ToList();

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

How to get href value using jQuery?

if the page have one <a> It Works,but,many <a> ,have to use var href = $(this).attr('href');

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

No notification sound when sending notification from firebase in android

With HTTP v1 API it is different

Documentation

Example:

{
 "message":{
    "topic":"news",
    "notification":{
       "body":"Very good news",
       "title":"Good news"
    },
    "android":{
       "notification":{
          "body":"Very good news",
          "title":"Good news",
          "sound":"default"
       }
    }
  }
}

What is "with (nolock)" in SQL Server?

I use with (nolock) hint particularly in SQLServer 2000 databases with high activity. I am not certain that it is needed in SQL Server 2005 however. I recently added that hint in a SQL Server 2000 at the request of the client's DBA, because he was noticing a lot of SPID record locks.

All I can say is that using the hint has NOT hurt us and appears to have made the locking problem solve itself. The DBA at that particular client basically insisted that we use the hint.

By the way, the databases I deal with are back-ends to enterprise medical claims systems, so we are talking about millions of records and 20+ tables in many joins. I typically add a WITH (nolock) hint for each table in the join (unless it is a derived table, in which case you can't use that particular hint)

Best Practices for securing a REST API / web service

I've used OAuth a few times, and also used some other methods (BASIC/DIGEST). I wholeheartedly suggest OAuth. The following link is the best tutorial I've seen on using OAuth:

http://hueniverse.com/oauth/guide/

Enable binary mode while restoring a Database from an SQL dump

I had the same problem, but found out that the dump file was actually a MSSQL Server backup, not MySQL.

Sometimes legacy backup files play tricks on us. Check your dump file.

On terminal window:

~$ cat mybackup.dmp 

The result was:

TAPE??G?"5,^}???Microsoft SQL ServerSPAD^LSFMB8..... etc...

To stop processing the cat command:

CTRL + C

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes

How to convert string values from a dictionary, into int/float datatypes?

If that's your exact format, you can go through the list and modify the dictionaries.

for item in list_of_dicts:
    for key, value in item.iteritems():
        try:
            item[key] = int(value)
        except ValueError:
            item[key] = float(value)

If you've got something more general, then you'll have to do some kind of recursive update on the dictionary. Check if the element is a dictionary, if it is, use the recursive update. If it's able to be converted into a float or int, convert it and modify the value in the dictionary. There's no built-in function for this and it can be quite ugly (and non-pythonic since it usually requires calling isinstance).

Returning a promise in an async function in TypeScript

When you do new Promise((resolve)... the type inferred was Promise<{}> because you should have used new Promise<number>((resolve).

It is interesting that this issue was only highlighted when the async keyword was added. I would recommend reporting this issue to the TS team on GitHub.

There are many ways you can get around this issue. All the following functions have the same behavior:

const whatever1 = () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever2 = async () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever3 = async () => {
    return await new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever4 = async () => {
    return Promise.resolve(4);
};

const whatever5 = async () => {
    return await Promise.resolve(4);
};

const whatever6 = async () => Promise.resolve(4);

const whatever7 = async () => await Promise.resolve(4);

In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>.

Get values from label using jQuery

Firstly, I don't think spaces for an id is valid.

So i'd change the id to not include spaces.

<label year="2010" month="6" id="currentMonth"> June &nbsp;2010</label>

then the jquery code is simple (keep in mind, its better to fetch the jquery object once and use over and over agian)

var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();

Sorting an array of objects by property values

While I am aware that the OP wanted to sort an array of numbers, this question has been marked as the answer for similar questions regarding strings. To that fact, the above answers do not consider sorting an array of text where casing is important. Most answers take the string values and convert them to uppercase/lowercase and then sort one way or another. The requirements that I adhere to are simple:

  • Sort alphabetically A-Z
  • Uppercase values of the same word should come before lowercase values
  • Same letter (A/a, B/b) values should be grouped together

What I expect is [ A, a, B, b, C, c ] but the answers above return A, B, C, a, b, c. I actually scratched my head on this for longer than I wanted (which is why I am posting this in hopes that it will help at least one other person). While two users mention the localeCompare function in the comments for the marked answer, I didn't see that until after I stumbled upon the function while searching around. After reading the String.prototype.localeCompare() documentation I was able to come up with this:

var values = [ "Delta", "charlie", "delta", "Charlie", "Bravo", "alpha", "Alpha", "bravo" ];
var sorted = values.sort((a, b) => a.localeCompare(b, undefined, { caseFirst: "upper" }));
// Result: [ "Alpha", "alpha", "Bravo", "bravo", "Charlie", "charlie", "Delta", "delta" ]

This tells the function to sort uppercase values before lowercase values. The second parameter in the localeCompare function is to define the locale but if you leave it as undefined it automatically figures out the locale for you.

This works the same for sorting an array of objects as well:

var values = [
    { id: 6, title: "Delta" },
    { id: 2, title: "charlie" },
    { id: 3, title: "delta" },
    { id: 1, title: "Charlie" },
    { id: 8, title: "Bravo" },
    { id: 5, title: "alpha" },
    { id: 4, title: "Alpha" },
    { id: 7, title: "bravo" }
];
var sorted = values
    .sort((a, b) => a.title.localeCompare(b.title, undefined, { caseFirst: "upper" }));

What is DOM Event delegation?

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

See this link --> http://www.akadia.com/services/dotnet_delegates_and_events.html

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

What is the attribute property="og:title" inside meta tag?

The property in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.

For example, to use that code you would have to have something like this in your <head tag. <head xmlns:og="http://example.org/"> and inside the http://example.org/ there would be a specification for title (og:title).

The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).

Check if element is visible in DOM

I've got a more performant solution compared to AlexZ's getComputedStyle() solution when one has position 'fixed' elements, if one is willing to ignore some edge cases (check comments):

function isVisible(el) {
    /* offsetParent would be null if display 'none' is set.
       However Chrome, IE and MS Edge returns offsetParent as null for elements
       with CSS position 'fixed'. So check whether the dimensions are zero.

       This check would be inaccurate if position is 'fixed' AND dimensions were
       intentionally set to zero. But..it is good enough for most cases.*/
    if (!el.offsetParent && el.offsetWidth === 0 && el.offsetHeight === 0) {
        return false;
    }
    return true;
}

Side note: Strictly speaking, "visibility" needs to be defined first. In my case, I am considering an element visible as long as I can run all DOM methods/properties on it without problems (even if opacity is 0 or CSS visibility property is 'hidden' etc).

How do I add options to a DropDownList using jQuery?

Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:

$.each(myOptions, function(val, text) {
    $("#mySelect").append($("&lt;option/&gt;").attr("value", val).text(text));
});

use current date as default value for a column

You can use:

Insert into Event(Description,Date) values('teste', GETDATE());

Also, you can change your table so that 'Date' has a default, "GETDATE()"

Bootstrap Modal before form Submit

$('form button[type="submit"]').on('click', function () {
   $(this).parents('form').submit();
});

Center Div inside another (100% width) div

.parent { text-align: center; }
.parent > .child { margin: 0 auto; width: 900px; }

How do you reverse a string in place in JavaScript?

The below might help anyone that is looking to reverse a string recursively. Was asked to do this in a recent job interview using functional programming style:

var reverseStr = function(str) {
    return (str.length > 0) ? str[str.length - 1] + reverseStr(str.substr(0, str.length -   1)) : '';
};

//tests
console.log(reverseStr('setab retsam')); //master bates

Random numbers with Math.random() in Java

Yours: Lowest possible is min, highest possible is max+min-1

Google: Lowest possible is min, highest possible is max-1

How to remove leading zeros from alphanumeric text?

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

s.replaceFirst("^0+(?!$)", "")

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!$) negative lookahead ensures that not the entire string will be matched.

Test harness:

String[] in = {
    "01234",         // "[1234]"
    "0001234a",      // "[1234a]"
    "101234",        // "[101234]"
    "000002829839",  // "[2829839]"
    "0",             // "[0]"
    "0000000",       // "[0]"
    "0000009",       // "[9]"
    "000000z",       // "[z]"
    "000000.z",      // "[.z]"
};
for (String s : in) {
    System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}

See also

java.util.NoSuchElementException: No line found

Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.

For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.

Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called

      "java.util.NoSuchElementException: No line found".

If you have to call "sc.nextLine()" n times, then you have to have at least n lines.

Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths

From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).

More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.

Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.

Convert Iterator to ArrayList

Note there is a difference between Iterable and Iterator.

If you have an Iterable, then with Java 8 you can use this solution:

Iterable<Element> iterable = createIterable();
List<Element> array = StreamSupport
    .stream(iterable.spliterator(), false)
    .collect(Collectors.toList());

As I know Collectors.toList() creates ArrayList instance.

Actually in my opinion, it also looks good in one line.
For example if you need to return List<Element> from some method:

return StreamSupport.stream(iter.spliterator(), false).collect(Collectors.toList());

How to include (source) R script in other scripts

You could write a function that takes a filename and an environment name, checks to see if the file has been loaded into the environment and uses sys.source to source the file if not.

Here's a quick and untested function (improvements welcome!):

include <- function(file, env) {
  # ensure file and env are provided
  if(missing(file) || missing(env))
    stop("'file' and 'env' must be provided")
  # ensure env is character
  if(!is.character(file) || !is.character(env))
    stop("'file' and 'env' must be a character")

  # see if env is attached to the search path
  if(env %in% search()) {
    ENV <- get(env)
    files <- get(".files",ENV)
    # if the file hasn't been loaded
    if(!(file %in% files)) {
      sys.source(file, ENV)                        # load the file
      assign(".files", c(file, files), envir=ENV)  # set the flag
    }
  } else {
    ENV <- attach(NULL, name=env)      # create/attach new environment
    sys.source(file, ENV)              # load the file
    assign(".files", file, envir=ENV)  # set the flag
  }
}

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

REST API - file (ie images) processing - best practices

OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)

After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.

If you have a special endpoint for images, it gives you much more power over handling those images.

We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.

Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".

The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).

Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.


Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.

There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.

Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.

SmartGit Installation and Usage on Ubuntu

What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon

In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.

Creating a selector from a method name with parameters

You can't pass a parameter in a @selector().

It looks like you're trying to implement a callback. The best way to do that would be something like this:

[object setCallbackObject:self withSelector:@selector(myMethod:)];

Then in your object's setCallbackObject:withSelector: method: you can call your callback method.

-(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
    [anObject performSelector:selector];
}

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

Angular 5 Button Submit On Enter Key Press

try use keyup.enter or keydown.enter

  <button type="submit" (keyup.enter)="search(...)">Search</button>

How would I run an async Task<T> method synchronously?

It's much simpler to run the task on the thread pool, rather than trying to trick the scheduler to run it synchronously. That way you can be sure that it won't deadlock. Performance is affected because of the context switch.

Task<MyResult> DoSomethingAsync() { ... }

// Starts the asynchronous task on a thread-pool thread.
// Returns a proxy to the original task.
Task<MyResult> task = Task.Run(() => DoSomethingAsync());

// Will block until the task is completed...
MyResult result = task.Result; 

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

Python and SQLite: insert into table

conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
  c.execute('insert into tablename values (?,?,?)', item)

"The public type <<classname>> must be defined in its own file" error in Eclipse

If .java file contains top level (not nested) public class, it have same name as that public class. So if you have class like public class A{...} it needs to be placed in A.java file. Because of that we can't have two public classes in one .java file.

If having two public classes would be allowed then, and lets say aside from public A class file would also contain public class B{} it would require from A.java file to be also named as B.java but files can't have two (or more) names (at least in all systems on which Java can be run).

So assuming your code is placed in StaticDemoShow.java file you have two options:

  1. If you want to have other class in same file make them non-public (lack of visibility modifier will represent default/package-private visibility)

    class StaticDemo { // It can no longer public
    
        static int a = 3;
        static int b = 4;
    
        static {
            System.out.println("Voila! Static block put into action");
        }
    
        static void show() {
            System.out.println("a= " + a);
            System.out.println("b= " + b);
        }
    
    }
    
    public class StaticDemoShow { // Only one top level public class in same .java file
        public static void main() {
            StaticDemo.show();
        }
    }
    
  2. Move all public classes to their own .java files. So in your case you would need to split it into two files:

    • StaticDemo.java

      public class StaticDemo { // Note: same name as name of file
      
          static int a = 3;
          static int b = 4;
      
          static {
              System.out.println("Voila! Static block put into action");
          }
      
          static void show() {
              System.out.println("a= " + a);
              System.out.println("b= " + b);
          }
      
      }
      
    • StaticDemoShow.java

      public class StaticDemoShow { 
          public static void main() {
              StaticDemo.show();
          }
      }
      

JavaScript override methods

Edit: It's now six years since the original answer was written and a lot has changed!

  • If you're using a newer version of JavaScript, possibly compiled with a tool like Babel, you can use real classes.
  • If you're using the class-like component constructors provided by Angular or React, you'll want to look in the docs for that framework.
  • If you're using ES5 and making "fake" classes by hand using prototypes, the answer below is still as right as it ever was.

Good luck!


JavaScript inheritance looks a bit different from Java. Here is how the native JavaScript object system looks:

// Create a class
function Vehicle(color){
  this.color = color;
}

// Add an instance method
Vehicle.prototype.go = function(){
  return "Underway in " + this.color;
}

// Add a second class
function Car(color){
  this.color = color;
}

// And declare it is a subclass of the first
Car.prototype = new Vehicle();

// Override the instance method
Car.prototype.go = function(){
  return Vehicle.prototype.go.call(this) + " car"
}

// Create some instances and see the overridden behavior.
var v = new Vehicle("blue");
v.go() // "Underway in blue"

var c = new Car("red");
c.go() // "Underway in red car"

Unfortunately this is a bit ugly and it does not include a very nice way to "super": you have to manually specify which parent classes' method you want to call. As a result, there are a variety of tools to make creating classes nicer. Try looking at Prototype.js, Backbone.js, or a similar library that includes a nicer syntax for doing OOP in js.

Example of a strong and weak entity types

Just to play with it, question is strong entity type and answer is weak. Question is always there, but an answer requires a question to exist.

Example: Don't ask 'Why?' if Your Dad's a Chemistry Professor

Why does HTML think “chucknorris” is a color?

The rules for parsing colors on legacy attributes involves additional steps than those mentioned in existing answers. The truncate component to 2 digits part is described as:

  1. Discard all characters except the last 8
  2. Discard leading zeros one by one as long as all components have a leading zero
  3. Discard all characters except the first 2

Some examples:

oooFoooFoooF
000F 000F 000F                <- replace, pad and chunk
0F 0F 0F                      <- leading zeros truncated
0F 0F 0F                      <- truncated to 2 characters from right

oooFooFFoFFF
000F 00FF 0FFF                <- replace, pad and chunk
00F 0FF FFF                   <- leading zeros truncated
00 0F FF                      <- truncated to 2 characters from right

ABCooooooABCooooooABCoooooo
ABC000000 ABC000000 ABC000000 <- replace, pad and chunk
BC000000 BC000000 BC000000    <- truncated to 8 characters from left
BC BC BC                      <- truncated to 2 characters from right

AoCooooooAoCooooooAoCoooooo
A0C000000 A0C000000 A0C000000 <- replace, pad and chunk
0C000000 0C000000 0C000000    <- truncated to 8 characters from left
C000000 C000000 C000000       <- leading zeros truncated
C0 C0 C0                      <- truncated to 2 characters from right

Below is a partial implementation of the algorithm. It does not handle errors or cases where the user enters a valid color.

_x000D_
_x000D_
function parseColor(input) {_x000D_
  // todo: return error if input is ""_x000D_
  input = input.trim();_x000D_
  // todo: return error if input is "transparent"_x000D_
  // todo: return corresponding #rrggbb if input is a named color_x000D_
  // todo: return #rrggbb if input matches #rgb_x000D_
  // todo: replace unicode code points greater than U+FFFF with 00_x000D_
  if (input.length > 128) {_x000D_
    input = input.slice(0, 128);_x000D_
  }_x000D_
  if (input.charAt(0) === "#") {_x000D_
    input = input.slice(1);_x000D_
  }_x000D_
  input = input.replace(/[^0-9A-Fa-f]/g, "0");_x000D_
  while (input.length === 0 || input.length % 3 > 0) {_x000D_
    input += "0";_x000D_
  }_x000D_
  var r = input.slice(0, input.length / 3);_x000D_
  var g = input.slice(input.length / 3, input.length * 2 / 3);_x000D_
  var b = input.slice(input.length * 2 / 3);_x000D_
  if (r.length > 8) {_x000D_
    r = r.slice(-8);_x000D_
    g = g.slice(-8);_x000D_
    b = b.slice(-8);_x000D_
  }_x000D_
  while (r.length > 2 && r.charAt(0) === "0" && g.charAt(0) === "0" && b.charAt(0) === "0") {_x000D_
    r = r.slice(1);_x000D_
    g = g.slice(1);_x000D_
    b = b.slice(1);_x000D_
  }_x000D_
  if (r.length > 2) {_x000D_
    r = r.slice(0, 2);_x000D_
    g = g.slice(0, 2);_x000D_
    b = b.slice(0, 2);_x000D_
  }_x000D_
  return "#" + r.padStart(2, "0") + g.padStart(2, "0") + b.padStart(2, "0");_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
  $("#input").on("change", function() {_x000D_
    var input = $(this).val();_x000D_
    var color = parseColor(input);_x000D_
    var $cells = $("#result tbody td");_x000D_
    $cells.eq(0).attr("bgcolor", input);_x000D_
    $cells.eq(1).attr("bgcolor", color);_x000D_
_x000D_
    var color1 = $cells.eq(0).css("background-color");_x000D_
    var color2 = $cells.eq(1).css("background-color");_x000D_
    $cells.eq(2).empty().append("bgcolor: " + input, "<br>", "getComputedStyle: " + color1);_x000D_
    $cells.eq(3).empty().append("bgcolor: " + color, "<br>", "getComputedStyle: " + color2);_x000D_
  });_x000D_
});
_x000D_
body { font: medium monospace; }_x000D_
input { width: 20em; }_x000D_
table { table-layout: fixed; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<p><input id="input" placeholder="Enter color e.g. chucknorris"></p>_x000D_
<table id="result">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Left Color</th>_x000D_
      <th>Right Color</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I check if a string is unicode or ascii?

For py2/py3 compatibility simply use

import six if isinstance(obj, six.text_type)

How to set DataGrid's row Background, based on a property value using data bindings

In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGrid has the BackGround Color of the ColorSet Property of my Object.

How to resize Image in Android?

BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image 
Bitmap bitmap=BitmapFactory.decodeStream(is, null, options); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); //compressed bitmap to file 

How do I remove the "extended attributes" on a file in Mac OS X?

Try using:

xattr -rd com.apple.quarantine directoryname

This takes care of recursively removing the pesky attribute everywhere.

Disabling Minimize & Maximize On WinForm?

Set MaximizeBox and MinimizeBox form properties to False

How to test valid UUID/GUID?

Beside Gambol's answer that will do the job in nearly all cases, all answers given so far missed that the grouped formatting (8-4-4-4-12) is not mandatory to encode GUIDs in text. It's used extremely often but obviously also a plain chain of 32 hexadecimal digits can be valid.[1] regexenh:

/^[0-9a-f]{8}-?[0-9a-f]{4}-?[1-5][0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$/i

[1] The question is about checking variables, so we should include the user-unfriendly form as well.

How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs

Type npm list graceful-fs and you will see which versions of graceful-fs are currently installed.

In my case I got:

npm list graceful-fs

@request/[email protected] /projects/request/promise-core
+-- [email protected]
| `-- [email protected]
|   +-- [email protected]
|   | `-- [email protected]
|   |   `-- [email protected]
|   |     `-- [email protected]
|   |       `-- [email protected]        <==== !!!
|   `-- [email protected] 
`-- [email protected]
  +-- [email protected]
  | `-- [email protected]
  |   `-- [email protected]
  |     `-- [email protected]
  |       `-- [email protected] 
  `-- [email protected]
    `-- [email protected]
      `-- [email protected]

As you can see gulp deep down depends on a very old version. Unfortunately, I can't update that myself using npm update graceful-fs. gulp would need to update their dependencies. So if you have a case like this you are out of luck. But you may open an issue for the project with the old dependency - i.e. gulp.

JUNIT testing void methods

You can learn something called "mocking". You can use this, for example, to check if: - a function was called - a function was called x times - a function was called at least x times - a function was called with a specific set of parameters. In your case, for example, you can use mocking to check that method3 was called once with whatever you pass as arg1 and arg2.

Have a look at these: https://code.google.com/p/mockito/ https://code.google.com/p/powermock/

What is time(NULL) in C?

The call to time(NULL) returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t variable, that pointer variable will point to the current time.

What is the PostgreSQL equivalent for ISNULL()

SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias

Or more idiomatic:

SELECT coalesce(field, 'Empty') AS field_alias

Invalid default value for 'create_date' timestamp field

You might like to examine the timezone setting on the MySql instance:

mysql> show variables like 'time_zone';
+---------------+--------+
| Variable_name | Value  |
+---------------+--------+
| time_zone     | SYSTEM |
+---------------+--------+

in my case, I realised that the underlying system had it's timezone set to BST rather than UTC, and so in the create table the default of '1970-01-01 00:00:01' was being coerced back 1 hour, resulting in an invalid timestamp value.

For me, I actually wanted the machine's timezone set to UTC, and that sorted me out. As I was running Centos/7, I simply did

# timedatectl set-timezone UTC

and restarted everything.

When to use @QueryParam vs @PathParam

For resource names and IDs, I use @PathParams. For optional variables, I use @QueryParams

String contains - ignore case

If you won't go with regex:

"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())

Calculate business days

Variant 1:

<?php
/*
 * Does not count current day, the date returned is the last business day
 * Requires PHP 5.1 (Using ISO-8601 week)
 */

function businessDays($timestamp = false, $bDays = 2) {
    if($timestamp === false) $timestamp = time();
    while ($bDays>0) {
        $timestamp += 86400;
        if (date('N', $timestamp)<6) $bDays--;
    }
    return $timestamp;
}

Variant 2:

<?php
/*
 * Does not count current day, the date returned is a business day 
 * following the last business day
 * Requires PHP 5.1 (Using ISO-8601 week)
 */

function businessDays($timestamp = false, $bDays = 2) {
    if($timestamp === false) $timestamp = time();
    while ($bDays+1>0) {
        $timestamp += 86400;
        if (date('N', $timestamp)<6) $bDays--;
    }
    return $timestamp;
}

Variant 3:

<?php
/*
 * Does not count current day, the date returned is 
 * a date following the last business day (can be weekend or not. 
 * See above for alternatives)
 * Requires PHP 5.1 (Using ISO-8601 week)
 */

function businessDays($timestamp = false, $bDays = 2) {
    if($timestamp === false) $timestamp = time();
    while ($bDays>0) {
        $timestamp += 86400;
        if (date('N', $timestamp)<6) $bDays--;
    }
    return $timestamp += 86400;
}

The additional holiday considerations can be made using variations of the above by doing the following. Note! assure all the timestamps are the same time of the day (i.e. midnight).

Make an array of holiday dates (as unixtimestamps) i.e.:

$holidays = array_flip(strtotime('2011-01-01'),strtotime('2011-12-25'));

Modify line :

if (date('N', $timestamp)<6) $bDays--;

to be :

if (date('N', $timestamp)<6 && !isset($holidays[$timestamp])) $bDays--;

Done!

<?php
/*
 * Does not count current day, the date returned is the last business day
 * Requires PHP 5.1 (Using ISO-8601 week)
 */

function businessDays($timestamp = false, $bDays = 2) {
    if($timestamp === false) $timestamp = strtotime(date('Y-m-d',time()));
    $holidays = array_flip(strtotime('2011-01-01'),strtotime('2011-12-25'));
    while ($bDays>0) {
        $timestamp += 86400;
        if (date('N', $timestamp)<6 && !isset($holidays[$timestamp])) $bDays--;
    }
    return $timestamp;
}

python list by value not by reference

I found that we can use extend() to implement the function of copy()

a=['help', 'copyright', 'credits', 'license']
b = []
b.extend(a)
b.append("XYZ") 

How to change to an older version of Node.js

Ubuntu - The Official Way (manually)

If you're on node 12 and want to downgrade to node 10, just remove node and follow the instructions for the desired version:

# Remove the version that is currently installed
sudo apt remove -y nodejs

# Setup sources for the version you want
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -

# (Re-)Install Node
sudo apt-get install -y nodejs

Windows - The Official Way (manually)

I found myself wanting to downgrade to LTS on Windows from the bleeding edge. If you're not using a package manager like Chocolatey or a node version manager like nvm or n, just download the .msi for the version you want and install it. You might want to remove the currently installed version via "Add or remove programs" tool in Windows.

Chocolatey - The Package Manager Way

I highly recommend chocolatey for keeping installations up to date easily and it is a common way to install Node.js on Windows. I had to remove the bleeding edge version before installing the LTS version:

choco uninstall nodejs

choco install nodejs-lts

With package.json - The Maintainable and Portable Way

Lets each project specify its own version

You can add node as a dependency in package.json and control which version is used for a particular project. Upon executing a package.json "script", npm (and yarn) will use that version to run the script instead of the globally installed Node.js.

The node package accomplishes this by downloading a node binary for your local system and puts it into the node_modules/.bin directory.


Node Version Manager - The "Screw it, I'll do it myself!" Way

While not very portable or easily maintainable, some developers like manually switching which global version of node is active at any given point in time and think the official ways of doing this are too slow. There are two popular npm packages that provide helpful CLI interfaces for selecting (and automatically installing) whichever version you want for your system: nvm and n. Using either is beyond the scope of this answer.

Generating sql insert into for Oracle

I have been searching for a solution for this and found it today. Here is how you can do it.

  1. Open Oracle SQL Developer Query Builder

  2. Run the query

  3. Right click on result set and export

    http://i.stack.imgur.com/lJp9P.png

Search text in stored procedure in SQL Server

also try this :

   SELECT ROUTINE_NAME 
    FROM INFORMATION_SCHEMA.ROUTINES 
    WHERE ROUTINE_DEFINITION like '%\[ABD\]%'

R: Comment out block of code

I have dealt with this at talkstats.com in posts 94, 101 & 103 found in the thread: Share Your Code. As others have said Rstudio may be a better way to go. I store these functions in my .Rprofile and actually use them a but to automatically block out lines of code quickly.

Not quite as nice as you were hoping for but may be an approach.

How to change default JRE for all Eclipse workspaces?

Finally got it: The way Eclipse picks up the JRE is using the system's PATH.

I did not have C:\home\SFTWR\jdk1.6.0_21\bin in the path at all before and I did have C:\Program Files (x86)\Java\jre6\bin. I had both JRE_HOME and JAVA_HOME set to C:\home\SFTWR\jdk1.6.0_21 but neither of those two mattered. I guess Eclipse did (something to the effect of) where java (or which on UNIX/Linux) to see where Java is in the path and took the JRE to which that java.exe belonged. In my case, despite all the configuration tweaks I had done (including eclipse.ini -vm option as suggested above), it remained stuck to what was in the path.

I removed the old JRE bin from the path, put the new one in, and it works for all workspaces.

How can I replace a regex substring match in Javascript?

I would get the part before and after what you want to replace and put them either side.

Like:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

var matches = str.match(regex);

var result = matches[1] + "1" + matches[2];

// With ES6:
var result = `${matches[1]}1${matches[2]}`;

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

How do I cast a JSON Object to a TypeScript class?

In TypeScript you can do a type assertion using an interface and generics like so:

var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array<ILocationMap> = JSON.parse(json).location;

Where ILocationMap describes the shape of your data. The advantage of this method is that your JSON could contain more properties but the shape satisfies the conditions of the interface.

However, this does NOT add class instance methods.

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

How to remove all non-alpha numeric characters from a string in MySQL?

Needed to replace non-alphanumeric characters rather than remove non-alphanumeric characters so I have created this based on Ryan Shillington's alphanum. Works for strings up to 255 characters in length

DROP FUNCTION IF EXISTS alphanumreplace; 
DELIMITER | 
CREATE FUNCTION alphanumreplace( str CHAR(255), d CHAR(32) ) RETURNS CHAR(255) 
BEGIN 
  DECLARE i, len SMALLINT DEFAULT 1; 
  DECLARE ret CHAR(32) DEFAULT ''; 
  DECLARE c CHAR(1); 
  SET len = CHAR_LENGTH( str ); 
  REPEAT 
    BEGIN 
      SET c = MID( str, i, 1 ); 
      IF c REGEXP '[[:alnum:]]' THEN SET ret=CONCAT(ret,c); 
      ELSE SET ret=CONCAT(ret,d);
      END IF; 
      SET i = i + 1; 
    END; 
  UNTIL i > len END REPEAT; 
  RETURN ret; 
END | 
DELIMITER ; 

Example:

select 'hello world!',alphanum('hello world!'),alphanumreplace('hello world!','-');
+--------------+--------------------------+-------------------------------------+
| hello world! | alphanum('hello world!') | alphanumreplace('hello world!','-') |
+--------------+--------------------------+-------------------------------------+
| hello world! | helloworld               | hello-world-                        |
+--------------+--------------------------+-------------------------------------+

You'll need to add the alphanum function seperately if you want that, I just have it here for the example.

How to detect browser using angularjs?

You can easily use the "ng-device-detector" module.

https://github.com/srfrnk/ng-device-detector

var app = angular.module('myapp', ["ng.deviceDetector"]);
app.controller('DeviceCtrl', ["$scope","deviceDetector",function($scope,deviceDetector) {
      console.log("browser: ", deviceDetector.browser);
      console.log("browser version: ", deviceDetector.browser_version);
      console.log("device: ", deviceDetector.device);
}]);

Generating an array of letters in the alphabet

Note also, the string has a operator[] which returns a Char, and is an IEnumerable<char>, so for most purposes, you can use a string as a char[]. Hence:

string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
for (int i =0; i < 26; ++i)
{  
     Console.WriteLine(alpha[i]);
}

foreach(char c in alpha)
{  
     Console.WriteLine(c);
}

Difference between two DateTimes C#?

Are you perhaps looking for:

int Difference = (a-b).Hours;

How to export collection to CSV in MongoDB?

Solution for MongoDB Atlas users!

Add the --fields parameter as comma separated field names enclosed in double inverted quotes:

--fields "<FIELD 1>,<FIELD 2>..."

This is complete example:

mongoexport --host Cluster0-shard-0/shard1URL.mongodb.net:27017,shard2URL.mongodb.net:27017,shard3URL.mongodb.net:27017 --ssl --username <USERNAME> --password <PASSWORD> --authenticationDatabase admin --db <DB NAME> --collection <COLLECTION NAME> --type <OUTPUT FILE TYPE> --out <OUTPUT FILE NAME> --fields "<FIELD 1>,<FIELD 2>..."

Does SVG support embedding of bitmap images?

You could use a Data URI to supply the image data, for example:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>

</svg>

The image will go through all normal svg transformations.

But this technique has disadvantages, for example the image will not be cached by the browser

How to check if spark dataframe is empty?

If you do df.count > 0. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.

The best way to do this is to perform df.take(1) and check if its null. This will return java.util.NoSuchElementException so better to put a try around df.take(1).

The dataframe return an error when take(1) is done instead of an empty row. I have highlighted the specific code lines where it throws the error.

enter image description here

How can I format bytes a cell in Excel as KB, MB, GB etc?

Less than Tera will write on GB & more than 999 GB write on TB

[<1000]0" GB";[>999]0.0," TB"

OR

[<1000]0" GB";[>=1000]0.0," TB"

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Instead of defining: COLUMN_HEADINGS("columnHeadings")

Try defining it as: COLUMNHEADINGS("columnHeadings")

Then when you call getByName(String name) method, call it with the upper-cased String like this: getByName(myStringVariable.toUpperCase())

I had the same problem as you, and this worked for me.

Input group - two inputs close to each other

I was not content with any of the answers on this page, so I fiddled with this myself for a bit. I came up with the following

_x000D_
_x000D_
angular.module('showcase', []).controller('Ctrl', function() {_x000D_
  var vm = this;_x000D_
  vm.focusParent = function(event) {_x000D_
    angular.element(event.target).parent().addClass('focus');_x000D_
  };_x000D_
_x000D_
  vm.blurParent = function(event) {_x000D_
    angular.element(event.target).parent().removeClass('focus');_x000D_
  };_x000D_
});
_x000D_
.input-merge .col-xs-2,_x000D_
.input-merge .col-xs-4,_x000D_
.input-merge .col-xs-6 {_x000D_
  padding-left: 0;_x000D_
  padding-right: 0;_x000D_
}_x000D_
.input-merge div:first-child .form-control {_x000D_
  border-top-right-radius: 0;_x000D_
  border-bottom-right-radius: 0;_x000D_
}_x000D_
.input-merge div:last-child .form-control {_x000D_
  border-top-left-radius: 0;_x000D_
  border-bottom-left-radius: 0;_x000D_
}_x000D_
.input-merge div:not(:first-child) {_x000D_
  margin-left: -1px;_x000D_
}_x000D_
.input-merge div:not(:first-child):not(:last-child) .form-control {_x000D_
  border-radius: 0;_x000D_
}_x000D_
.focus {_x000D_
  z-index: 2;_x000D_
}
_x000D_
<html ng-app="showcase">_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body class="container">_x000D_
  <label class="control-label">Person</label>_x000D_
  <div class="input-merge" ng-controller="Ctrl as showCase">_x000D_
    <div class="col-xs-4">_x000D_
      <input class="form-control input-sm" name="initials" type="text" id="initials"_x000D_
             ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
             ng-model="person.initials" placeholder="Initials" />_x000D_
    </div>_x000D_
_x000D_
    <div class="col-xs-2">_x000D_
      <input class="form-control input-sm" name="prefixes" type="text" id="prefixes"_x000D_
             ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
             ng-model="persoon.prefixes" placeholder="Prefixes" />_x000D_
    </div>_x000D_
_x000D_
    <div class="col-xs-6">_x000D_
      <input class="form-control input-sm" name="surname" type="text" id="surname"_x000D_
             ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
             ng-model="persoon.surname" placeholder="Surname" />_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

With this it is possible to set the width of the individual inputs to your liking. Also a minor issue with the above snippets was that the input looks incomplete when focussed or when it is not valid. I fixed this with some angular code, but you can just as easily do this with jQuery or native javascript or whatever.

The code adds the class .focus to the containing div's, so it can get a higher z-index then the others when the input is focussed.

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

Creating new database from a backup of another Database on the same server?

Think of it like an archive. MyDB.Bak contains MyDB.mdf and MyDB.ldf.

Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.

So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.

Concat strings by & and + in VB.Net

From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

    Dim s1 As String
    Dim i As Integer
    s1 = "Hello"
    i = 1
    String.Format("{0} {1}", s1, i)

It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

How to escape strings in SQL Server using PHP?

function ms_escape_string($data) {
        if ( !isset($data) or empty($data) ) return '';
        if ( is_numeric($data) ) return $data;

        $non_displayables = array(
            '/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
            '/%1[0-9a-f]/',             // url encoded 16-31
            '/[\x00-\x08]/',            // 00-08
            '/\x0b/',                   // 11
            '/\x0c/',                   // 12
            '/[\x0e-\x1f]/'             // 14-31
        );
        foreach ( $non_displayables as $regex )
            $data = preg_replace( $regex, '', $data );
        $data = str_replace("'", "''", $data );
        return $data;
    }

Some of the code here was ripped off from CodeIgniter. Works well and is a clean solution.

EDIT: There are plenty of issues with that code snippet above. Please don't use this without reading the comments to know what those are. Better yet, please don't use this at all. Parameterized queries are your friends: http://php.net/manual/en/pdo.prepared-statements.php

How do you rename a Git tag?

As an add on to the other answers, I added an alias to do it all in one step, with a more familiar *nix move command feel. Argument 1 is the old tag name, argument 2 is the new tag name.

[alias]
    renameTag = "!sh -c 'set -e;git tag $2 $1; git tag -d $1;git push origin :refs/tags/$1;git push --tags' -"

Usage:

git renametag old new

Twitter bootstrap hide element on small devices

On small device : 4 columns x 3 (= 12) ==> col-sm-3

On extra small : 3 columns x 4 (= 12) ==> col-xs-4

 <footer class="row">
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 1</li>
            <li>Text 2</li>
            <li>Text 3</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 4</li>
            <li>Text 5</li>
            <li>Text 6</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 7</li>
            <li>Text 8</li>
            <li>Text 9</li>
            </ul>
        </nav>
        <nav class="hidden-xs col-sm-3">
            <ul class="list-unstyled">
            <li>Text 10</li>
            <li>Text 11</li>
            <li>Text 12</li>
            </ul>
        </nav>
    </footer>

As you say, hidden-xs is not enough, you have to combine xs and sm class.


Here is links to the official doc about available responsive classes and about the grid system.

Have in head :

  • 1 row = 12 cols
  • For XtraSmall device : col-xs-__
  • For SMall device : col-sm-__
  • For MeDium Device: col-md-__
  • For LarGe Device : col-lg-__
  • Make visible only (hidden on other) : visible-md (just visible in medium [not in lg xs or sm])
  • Make hidden only (visible on other) : hidden-xs (just hidden in XtraSmall)

How can I run another application within a panel of my C# program?

Another interesting solution to luch an exeternal application with a WinForm container is the follow:

[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);


private void Form1_Load(object sender, EventArgs e)
{
    ProcessStartInfo psi = new ProcessStartInfo("notepad.exe");
    psi.WindowStyle = ProcessWindowStyle.Minimized;
    Process p = Process.Start(psi);
    Thread.Sleep(500);
    SetParent(p.MainWindowHandle, panel1.Handle);
    CenterToScreen();
    psi.WindowStyle = ProcessWindowStyle.Normal;
}

The step to ProcessWindowStyle.Minimized from ProcessWindowStyle.Normal remove the annoying delay.

enter image description here

CSS - Syntax to select a class within an id

Just needed to drill down to the last li.

    #navigation li .navigationLevel2 li

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

Matplotlib scatter plot with different text at each data point

You may also use pyplot.text (see here).

def plot_embeddings(M_reduced, word2Ind, words):
    """ 
        Plot in a scatterplot the embeddings of the words specified in the list "words".
        Include a label next to each point.
    """
    for word in words:
        x, y = M_reduced[word2Ind[word]]
        plt.scatter(x, y, marker='x', color='red')
        plt.text(x+.03, y+.03, word, fontsize=9)
    plt.show()

M_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]])
word2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4}
words = ['test1', 'test2', 'test3', 'test4', 'test5']
plot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words)

enter image description here

Setting default values for columns in JPA

This isn't possible in JPA.

Here's what you can do with the Column annotation: http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html

How to secure phpMyAdmin

The simplest approach would be to edit the webserver, most likely an Apache2 installation, configuration and give phpmyadmin a different name.

A second approach would be to limit the IP addresses from where phpmyadmin may be accessed (e.g. only local lan or localhost).

How to resize an Image C#

In the application I made it was necessary to create a function with multiple options. It's quite large, but it resizes the image, can keep the aspect ratio and can cut of the edges to return only the center of the image:

/// <summary>
    /// Resize image with a directory as source
    /// </summary>
    /// <param name="OriginalFileLocation">Image location</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <param name="getCenter">return the center bit of the image</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
    {
        int newheigth = heigth;
        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFileLocation);

        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (keepAspectRatio || getCenter)
        {
            int bmpY = 0;
            double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector
            if (getCenter)
            {
                bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);// gives the Y value of the part that will be cut off, to show only the part in the center
                Rectangle section = new Rectangle(new Point(0, bmpY), new Size(FullsizeImage.Width, (int)(heigth * resize)));// create the section to cut of the original image
                //System.Console.WriteLine("the section that will be cut off: " + section.Size.ToString() + " the Y value is minimized by: " + bmpY);
                Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);//for the correct effect convert image to bitmap.
                FullsizeImage.Dispose();//clear the original image
                using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
                {
                    Graphics cutImg = Graphics.FromImage(tempImg);//              set the file to save the new image to.
                    cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);// cut the image and save it to tempImg
                    FullsizeImage = tempImg;//save the tempImg as FullsizeImage for resizing later
                    orImg.Dispose();
                    cutImg.Dispose();
                    return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
                }
            }
            else newheigth = (int)(FullsizeImage.Height / resize);//  set the new heigth of the current image
        }//return the image resized to the given heigth and width
        return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero);
    }

To make it easier to acces the function it's possible to add some overloaded functions:

/// <summary>
    /// Resize image with a directory as source
    /// </summary>
    /// <param name="OriginalFileLocation">Image location</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width)
    {
        return resizeImageFromFile(OriginalFileLocation, heigth, width, false, false);
    }

    /// <summary>
    /// Resize image with a directory as source
    /// </summary>
    /// <param name="OriginalFileLocation">Image location</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio)
    {
        return resizeImageFromFile(OriginalFileLocation, heigth, width, keepAspectRatio, false);
    }

Now are the last two booleans optional to set. Call the function like this:

System.Drawing.Image ResizedImage = resizeImageFromFile(imageLocation, 800, 400, true, true);

Reset git proxy to default configuration

For me, I had to add:

git config --global --unset http.proxy

Basically, you can run:

git config --global -l 

to get the list of all proxy defined, and then use "--unset" to disable them

XSS prevention in JSP/Servlet web application

XSS can be prevented in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.

For example:

<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>

This will escape characters which may malform the rendered HTML such as <, >, ", ' and & into HTML/XML entities such as &lt;, &gt;, &quot;, &apos; and &amp;.

Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes &amp;amp; instead of &amp; and ultimately the enduser would see &amp; being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also Markdown or HTML.

The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement instead of Statement. In JPA terms, use Query.


An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.

Changing API level Android Studio

In build.gradle change minSdkVersion 13 to minSdkVersion 8 Thats all you need to do. I solved my problem by only doing this.

defaultConfig {
    applicationId "com.example.sabrim.sbrtest"
    minSdkVersion 8
    targetSdkVersion 20
    versionCode 1
    versionName "1.0"
}

How can I unstage my files again after making a local commit?

Lets say you want to unstage changes upto n commits,

Where commit hashes are as follows:

  • h1
  • h2 ...
  • hn
  • hn+1

Then run the following command:
git reset hn

Now the HEAD will be at hn+1. Changes from h1 to hn will be unstaged.

What is a "callback" in C and how are they implemented?

It is lot easier to understand an idea through example. What have been told about callback function in C so far are great answers, but probably the biggest benefit of using the feature is to keep the code clean and uncluttered.

Example

The following C code implements quick sorting. The most interesting line in the code below is this one, where we can see the callback function in action:

qsort(arr,N,sizeof(int),compare_s2b);

The compare_s2b is the name of function which qsort() is using to call the function. This keeps qsort() so uncluttered (hence easier to maintain). You just call a function by name from inside another function (of course, the function prototype declaration, at the least, must precde before it can be called from another function).

The Complete Code

#include <stdio.h>
#include <stdlib.h>

int arr[]={56,90,45,1234,12,3,7,18};
//function prototype declaration 

int compare_s2b(const void *a,const void *b);

int compare_b2s(const void *a,const void *b);

//arranges the array number from the smallest to the biggest
int compare_s2b(const void* a, const void* b)
{
    const int* p=(const int*)a;
    const int* q=(const int*)b;

    return *p-*q;
}

//arranges the array number from the biggest to the smallest
int compare_b2s(const void* a, const void* b)
{
    const int* p=(const int*)a;
    const int* q=(const int*)b;

    return *q-*p;
}

int main()
{
    printf("Before sorting\n\n");

    int N=sizeof(arr)/sizeof(int);

    for(int i=0;i<N;i++)
    {
        printf("%d\t",arr[i]);
    }

    printf("\n");

    qsort(arr,N,sizeof(int),compare_s2b);

    printf("\nSorted small to big\n\n");

    for(int j=0;j<N;j++)
    {
        printf("%d\t",arr[j]);
    }

    qsort(arr,N,sizeof(int),compare_b2s);

    printf("\nSorted big to small\n\n");

    for(int j=0;j<N;j++)
    {
        printf("%d\t",arr[j]);
    }

    exit(0);
}

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

It is worth noting that you can build upon Gavin Toweys answer by using multiple fields from across your query such as

SUM(table.field = 1 AND table2.field = 2)

You can also use this syntax for COUNT and I am sure other functions as well.

How to check if an item is selected from an HTML drop down list?

<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
     alert('select one answer');
}
else {
    var selectedText = card.options[card.selectedIndex].text;
    alert(selectedText);
}
</script>

Pass a javascript variable value into input type hidden value

You could give your hidden field an id:

<input type="hidden" id="myField" value="" />

and then when you want to assign its value:

document.getElementById('myField').value = product(2, 3);

Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load event.

Driver executable must be set by the webdriver.ie.driver system property

I just put the driver files directly into my project to not get any dependency to my local machine.

final File file = new File("driver/chromedriver_2_22_mac");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

driver = new ChromeDriver();

How can I set the value of a DropDownList using jQuery?

Using the highlighted/checked answer above worked for me... here's a little insight. I cheated a little on getting the URL, but basically I'm defining the URL in the Javascript, and then setting it via the jquery answer from above:

<select id="select" onChange="window.location.href=this.value">
    <option value="">Select a task </option>
    <option value="http://127.0.0.1:5000/choose_form/1">Task 1</option>
    <option value="http://127.0.0.1:5000/choose_form/2">Task 2</option>
    <option value="http://127.0.0.1:5000/choose_form/3">Task 3</option>
    <option value="http://127.0.0.1:5000/choose_form/4">Task 4</option>
    <option value="http://127.0.0.1:5000/choose_form/5">Task 5</option>
    <option value="http://127.0.0.1:5000/choose_form/6">Task 6</option>
    <option value="http://127.0.0.1:5000/choose_form/7">Task 7</option>
    <option value="http://127.0.0.1:5000/choose_form/8">Task 8</option>
</select>
<script>
    var pathArray = window.location.pathname.split( '/' );
    var selectedItem = "http://127.0.0.1:5000/" + pathArray[1] + "/" + pathArray[2];
    var trimmedItem = selectedItem.trim();
    $("#select").val(trimmedItem);
</script>

MySQL JOIN the most recent row only?

For anyone who must work with an older version of MySQL (pre-5.0 ish) you are unable to do sub-queries for this type of query. Here is the solution I was able to do and it seemed to work great.

SELECT MAX(d.id), d2.*, CONCAT(title,' ',forename,' ',surname) AS name
FROM customer AS c 
LEFT JOIN customer_data as d ON c.customer_id=d.customer_id 
LEFT JOIN customer_data as d2 ON d.id=d2.id
WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
GROUP BY c.customer_id LIMIT 10, 20;

Essentially this is finding the max id of your data table joining it to the customer then joining the data table to the max id found. The reason for this is because selecting the max of a group doesn't guarantee that the rest of the data matches with the id unless you join it back onto itself.

I haven't tested this on newer versions of MySQL but it works on 4.0.30.

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

MySQL - Trigger for updating same table after insert

Had the same problem but had to update a column with the id that was about to enter, so you can make an update should be done BEFORE and AFTER not BEFORE had no id so I did this trick

DELIMITER $$
DROP TRIGGER IF EXISTS `codigo_video`$$
CREATE TRIGGER `codigo_video` BEFORE INSERT ON `videos` 
FOR EACH ROW BEGIN
    DECLARE ultimo_id, proximo_id INT(11);
    SELECT id INTO ultimo_id FROM videos ORDER BY id DESC LIMIT 1;
    SET proximo_id = ultimo_id+1;
    SET NEW.cassette = CONCAT(NEW.cassette, LPAD(proximo_id, 5, '0'));
END$$
DELIMITER ;

Change the "From:" address in Unix "mail"

What allowed me to have a custom reply-to address on an Ubuntu 16.04 with UTF-8 encoding and a file attachment:

Install the mail client:

sudo apt-get install heirloom-mailx

Edit the SMTP configuration:

sudo vim /etc/ssmtp/ssmtp.conf
mailhub=smtp.gmail.com:587
FromLineOverride=YES
[email protected]
AuthPass=???
UseSTARTTLS=YES

Send the mail:

sender='[email protected]'
recipient='[email protected]'
zipfile="results/file.zip"
today=`date +\%d-\%m-\%Y`
mailSubject='My subject on the '$today
read -r -d '' mailBody << EOM
Find attached the zip file.

Regards,
EOM
mail -s "$mailSubject" -r "Name <$sender>" -S replyto="$sender" -a $zipfile $recipient < <(echo $mailBody)

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Code:

private static void RegisterServices(IKernel kernel)
{
    Mock<IProductRepository> mock=new Mock<IProductRepository>();
    mock.Setup(x => x.Products).Returns(new List<Product>
    {
        new Product {Name = "Football", Price = 23},
        new Product {Name = "Surf board", Price = 179},
        new Product {Name = "Running shose", Price = 95}
    });

    kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}        

but see exception.

Setting TIME_WAIT TCP

In Windows, you can change it through the registry:

; Set the TIME_WAIT delay to 30 seconds (0x1E)

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TCPIP\Parameters]
"TcpTimedWaitDelay"=dword:0000001E

Get text of the selected option with jQuery

Close, you can use

$('#select_2 option:selected').html()

Inserting into Oracle and retrieving the generated sequence ID

You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

or, as a pl-sql script:

variable l_batchid number;

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

select :l_batchid from dual;

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

Add this to the project level build.gradle file and it should work fine.

allprojects {
    repositories {
        google() // this is to be added if there's something already.
        jcenter()
    }
}

iOS: Compare two dates

After searching stackoverflow and the web a lot, I've got to conclution that the best way of doing it is like this:

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
    NSDate* enddate = checkEndDate;
    NSDate* currentdate = [NSDate date];
    NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
    double secondsInMinute = 60;
    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

    if (secondsBetweenDates == 0)
        return YES;
    else if (secondsBetweenDates < 0)
        return YES;
    else
        return NO;
}

You can change it to difference between hours also.

Enjoy!


Edit 1

If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date]; && NSTimeInterval distance

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];

Scala list concatenation, ::: vs ++

::: works only with lists, while ++ can be used with any traversable. In the current implementation (2.9.0), ++ falls back on ::: if the argument is also a List.

Angular2 - Input Field To Accept Only Numbers

You can create this Validator and import it in your component.
Basically validates the form input string:

  • check there is no dot
  • converts string to number
  • check is an integer
  • check is greater than zero

To implement it in your project:

  1. suggested path in your app folder: src/app/validators/number.validator.ts
  2. import in your component

    import { NumberValidator } from '../../validators/number.validator';

  3. add it to the form control
    inputNumber: ['', [NumberValidator.isInteger]],
  4. if you dont want to show the invalid char, bind a (change)="deleteCharIfInvalid()" to the input, if form.get('inputNumber').hasError('isInteger') is true, delete the last char inserted.
// FILE: src/app/validators/number.validator.ts

import { FormControl } from '@angular/forms';

export interface ValidationResult {
    [key: string]: boolean;
}

export class NumberValidator {

    public static isInteger(control: FormControl): ValidationResult {
        // check if string has a dot
        let hasDot:boolean = control.value.indexOf('.') >= 0 ? true : false;
        // convert string to number
        let number:number = Math.floor(control.value);
        // get result of isInteger()
        let integer:boolean = Number.isInteger(number);
        // validate conditions 
        let valid:boolean = !hasDot && integer && number>0;
        console.log('isInteger > valid', hasDot, number, valid);
        if (!valid) {
            return { isInteger: true };
        }
        return null;
    }        
}

Masking password input from the console : Java

You would use the Console class

char[] password = console.readPassword("Enter password");  
Arrays.fill(password, ' ');

By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.

If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained

Detecting IE11 using CSS Capability/Feature Detection

Take a look at this article: CSS: User Agent Selectors

Basically, when you use this script:

var b = document.documentElement;
b.setAttribute('data-useragent',  navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

You can now use CSS to target any browser / version.

So for IE11 we could do this:

FIDDLE

html[data-useragent*='rv:11.0']
{
    color: green;
}

PHP removing a character in a string

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

Site does not exist error for a2ensite

Worked after I added .conf to the configuration file

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

ModelState.AddModelError - How can I add an error that isn't for a property?

You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.

As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using

<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>

and

ModelState.AddModelError("Email", Resources.EmailInUse);

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.

I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.

For simplicity, here's your same code re-written with a function callback provided by the calling controller:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(callbackFunc) {
        $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
        }).success(function(data){
            // With the data succesfully returned, call our callback
            callbackFunc(data);
        }).error(function(){
            alert("error");
        });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Now, $http actually already returns a $promise, so this can be re-written:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function() {
        // $http() returns a $promise that we can add handlers with .then()
        return $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.

Load CSV file with Spark

If your csv data happens to not contain newlines in any of the fields, you can load your data with textFile() and parse it

import csv
import StringIO

def loadRecord(line):
    input = StringIO.StringIO(line)
    reader = csv.DictReader(input, fieldnames=["name1", "name2"])
    return reader.next()

input = sc.textFile(inputFile).map(loadRecord)

getting the X/Y coordinates of a mouse click on an image with jQuery

You can use pageX and pageY to get the position of the mouse in the window. You can also use jQuery's offset to get the position of an element.

So, it should be pageX - offset.left for how far from the left of the image and pageY - offset.top for how far from the top of the image.

Here is an example:

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    alert(e.pageX - offset.left);
    alert(e.pageY - offset.top);
  });
});

I've made a live example here and here is the source.

To calculate how far from the bottom or right, you would have to use jQuery's width and height methods.

MySQL equivalent of DECODE function in Oracle

The example translates directly to:

Select Name, CASE Age
       WHEN 13 then 'Thirteen' WHEN 14 then 'Fourteen' WHEN 15 then 'Fifteen' WHEN 16 then 'Sixteen'
       WHEN 17 then 'Seventeen' WHEN 18 then 'Eighteen' WHEN 19 then 'Nineteen'
       ELSE 'Adult' END AS AgeBracket
FROM Person

which you may prefer to format e.g. like this:

Select Name,
       CASE Age
         when 13 then 'Thirteen'
         when 14 then 'Fourteen'
         when 15 then 'Fifteen'
         when 16 then 'Sixteen'
         when 17 then 'Seventeen'
         when 18 then 'Eighteen'
         when 19 then 'Nineteen'
         else         'Adult'
       END AS AgeBracket
FROM Person

Best way to reverse a string

Have a look at the wikipedia entry here. They implement the String.Reverse extension method. This allows you to write code like this:

string s = "olleh";
s.Reverse();

They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this:

public static string Reverse(this string input)
{
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}

How to exit an Android app programmatically?

this will clear Task(stack of activities) and begin new Task

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(1);

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

How do I loop through or enumerate a JavaScript object?

Performance

Today 2020.03.06 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6

Conclusions

  • solutions based on for-in (A,B) are fast (or fastest) for all browsers for big and small objects
  • surprisingly for-of (H) solution is fast on chrome for small and big objects
  • solutions based on explicit index i (J,K) are quite fast on all browsers for small objects (for firefox also fast for big ojbects but medium fast on other browsers)
  • solutions based on iterators (D,E) are slowest and not recommended
  • solution C is slow for big objects and medium-slow for small objects

enter image description here

Details

Performance tests was performed for

  • small object - with 3 fields - you can perform test on your machine HERE
  • 'big' object - with 1000 fields - you can perform test on your machine HERE

Below snippets presents used solutions

_x000D_
_x000D_
function A(obj,s='') {_x000D_
 for (let key in obj) if (obj.hasOwnProperty(key)) s+=key+'->'+obj[key] + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function B(obj,s='') {_x000D_
 for (let key in obj) s+=key+'->'+obj[key] + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function C(obj,s='') {_x000D_
  const map = new Map(Object.entries(obj));_x000D_
 for (let [key,value] of map) s+=key+'->'+value + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function D(obj,s='') {_x000D_
  let o = { _x000D_
    ...obj,_x000D_
    *[Symbol.iterator]() {_x000D_
      for (const i of Object.keys(this)) yield [i, this[i]];    _x000D_
    }_x000D_
  }_x000D_
  for (let [key,value] of o) s+=key+'->'+value + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function E(obj,s='') {_x000D_
  let o = { _x000D_
    ...obj,_x000D_
    *[Symbol.iterator]() {yield *Object.keys(this)}_x000D_
  }_x000D_
  for (let key of o) s+=key+'->'+o[key] + ' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function F(obj,s='') {_x000D_
 for (let key of Object.keys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function G(obj,s='') {_x000D_
 for (let [key, value] of Object.entries(obj)) s+=key+'->'+value+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function H(obj,s='') {_x000D_
 for (let key of Object.getOwnPropertyNames(obj)) s+=key+'->'+obj[key]+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function I(obj,s='') {_x000D_
 for (const key of Reflect.ownKeys(obj)) s+=key+'->'+obj[key]+' ';_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function J(obj,s='') {_x000D_
  let keys = Object.keys(obj);_x000D_
 for(let i = 0; i < keys.length; i++){_x000D_
    let key = keys[i];_x000D_
    s+=key+'->'+obj[key]+' ';_x000D_
  }_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function K(obj,s='') {_x000D_
  var keys = Object.keys(obj), len = keys.length, i = 0;_x000D_
  while (i < len) {_x000D_
    let key = keys[i];_x000D_
    s+=key+'->'+obj[key]+' ';_x000D_
    i += 1;_x000D_
  }_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function L(obj,s='') {_x000D_
  Object.keys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function M(obj,s='') {_x000D_
  Object.entries(obj).forEach(([key, value]) => s+=key+'->'+value+' ');_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function N(obj,s='') {_x000D_
  Object.getOwnPropertyNames(obj).forEach(key => s+=key+'->'+obj[key]+' ');_x000D_
  return s;_x000D_
}_x000D_
_x000D_
function O(obj,s='') {_x000D_
  Reflect.ownKeys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );_x000D_
  return s;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
let log = (name,f) => console.log(`${name} ${f(p)}`)_x000D_
_x000D_
log('A',A);_x000D_
log('B',B);_x000D_
log('C',C);_x000D_
log('D',D);_x000D_
log('E',E);_x000D_
log('F',F);_x000D_
log('G',G);_x000D_
log('H',H);_x000D_
log('I',I);_x000D_
log('J',J);_x000D_
log('K',K);_x000D_
log('L',L);_x000D_
log('M',M);_x000D_
log('N',N);_x000D_
log('O',O);
_x000D_
This snippet only presents choosen solutions
_x000D_
_x000D_
_x000D_

And here are result for small objects on chrome

enter image description here

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

You have 2 options for this error:

  1. The file you are uploading is too big, which you need to use smaller file.
  2. Increase the upload size in php.ini to

upload_max_filesize = 9M; post_max_size = 9M;

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

Set LIMIT with doctrine 2?

$query_ids = $this->getEntityManager()
      ->createQuery(
        "SELECT e_.id
        FROM MuzichCoreBundle:Element e_
        WHERE [...]
        GROUP BY e_.id")
     ->setMaxResults(5)
     ->setMaxResults($limit) 
    ;

HERE in the second query the result of the first query should be passed ..

$query_select = "SELECT e
      FROM MuzichCoreBundle:Element e 
      WHERE e.id IN (".$query_ids->getResult().")
      ORDER BY e.created DESC, e.name DESC"
    ;


$query = $this->getEntityManager()
      ->createQuery($query_select)
      ->setParameters($params)
      ->setMaxResults($limit);
    ;

$resultCollection = $query->getResult();

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

this resolved this issue by adding namespace to Global.asax.cs file.

using System.Web.Http;

this resolved the issue.

Get data from JSON file with PHP

Get the content of the JSON file using file_get_contents():

$str = file_get_contents('http://example.com/example.json/');

Now decode the JSON using json_decode():

$json = json_decode($str, true); // decode the JSON into an associative array

You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:

echo '<pre>' . print_r($json, true) . '</pre>';

This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

Or loop through the array however you wish:

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

Demo!

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

How do I test if a recordSet is empty? isNull?

A simple way is to write it:

Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
   msgbox "There is no records" 
End if

Importing a long list of constants to a Python file

create constant file with any name like my_constants.py declare constant like that

CONSTANT_NAME = "SOME VALUE"

For accessing constant in your code import file like that

import my_constants as constant

and access the constant value as -

constant.CONSTANT_NAME

jQuery textbox change event doesn't fire until textbox loses focus?

Try this:

$("#textbox").bind('paste',function() {alert("Change detected!");});

See demo on JSFiddle.

How to remove an item from an array in AngularJS scope?

For the the accepted answer of @Joseph Silber is not working, because indexOf returns -1. This is probably because Angular adds an hashkey, which is different for my $scope.items[0] and my item. I tried to resolve this with the angular.toJson() function, but it did not work :(

Ah, I found out the reason... I use a chunk method to create two columns in my table by watching my $scope.items. Sorry!

How do I remove a submodule?

In latest git just 4 operation is needed to remove the git submodule.

  • Remove corresponding entry in .gitmodules
  • Stage changes git add .gitmodules
  • Remove the submodule directory git rm --cached <path_to_submodule>
  • Commit it git commit -m "Removed submodule xxx"

How do you find all subclasses of a given class in Java?

I did this several years ago. The most reliable way to do this (i.e. with official Java APIs and no external dependencies) is to write a custom doclet to produce a list that can be read at runtime.

You can run it from the command line like this:

javadoc -d build -doclet com.example.ObjectListDoclet -sourcepath java/src -subpackages com.example

or run it from ant like this:

<javadoc sourcepath="${src}" packagenames="*" >
  <doclet name="com.example.ObjectListDoclet" path="${build}"/>
</javadoc>

Here's the basic code:

public final class ObjectListDoclet {
    public static final String TOP_CLASS_NAME =  "com.example.MyClass";        

    /** Doclet entry point. */
    public static boolean start(RootDoc root) throws Exception {
        try {
            ClassDoc topClassDoc = root.classNamed(TOP_CLASS_NAME);
            for (ClassDoc classDoc : root.classes()) {
                if (classDoc.subclassOf(topClassDoc)) {
                    System.out.println(classDoc);
                }
            }
            return true;
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}

For simplicity, I've removed command line argument parsing and I'm writing to System.out rather than a file.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.

E.g.:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"

You can view the dump from the console on the mentioned path.

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How do I concatenate multiple C++ strings on one line?

Maybe you like my "Streamer" solution to really do it in one line:

#include <iostream>
#include <sstream>
using namespace std;

class Streamer // class for one line string generation
{
public:

    Streamer& clear() // clear content
    {
        ss.str(""); // set to empty string
        ss.clear(); // clear error flags
        return *this;
    }

    template <typename T>
    friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer

    string str() // get current string
    { return ss.str();}

private:
    stringstream ss;
};

template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}

Streamer streamer; // make this a global variable


class MyTestClass // just a test class
{
public:
    MyTestClass() : data(0.12345){}
    friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
    double data;
};

ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}


int main()
{
    int i=0;
    string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str();                      // test strings
    string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
    string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str();              // test with test class
    cout<<"s1: '"<<s1<<"'"<<endl;
    cout<<"s2: '"<<s2<<"'"<<endl;
    cout<<"s3: '"<<s3<<"'"<<endl;
}

Number of occurrences of a character in a string

Your string example looks like the query string part of a GET. If so, note that HttpContext has some help for you

int numberOfArgs = HttpContext.Current.QueryString.Count;

For more of what you can do with QueryString, see NameValueCollection

Best way to update an element in a generic List

You could do:

var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));

This will return the matching dog, else it will return null.

You can then set the property like follows:

if (matchingDog != null)
    matchingDog.Name = "New Dog Name";

Creating an R dataframe row-by-row

You can grow them row by row by appending or using rbind().

That does not mean you should. Dynamically growing structures is one of the least efficient ways to code in R.

If you can, allocate your entire data.frame up front:

N <- 1e4  # total number of rows to preallocate--possibly an overestimate

DF <- data.frame(num=rep(NA, N), txt=rep("", N),  # as many cols as you need
                 stringsAsFactors=FALSE)          # you don't know levels yet

and then during your operations insert row at a time

DF[i, ] <- list(1.4, "foo")

That should work for arbitrary data.frame and be much more efficient. If you overshot N you can always shrink empty rows out at the end.

Escaping quotation marks in PHP

Use the addslashes function:

 $str = "Is your name O'Reilly?";

 // Outputs: Is your name O\'Reilly?
   echo addslashes($str);

Disable eslint rules for folder

To ignore some folder from eslint rules we could create the file .eslintignore in root directory and add there the path to the folder we want omit (the same way as for .gitignore).

Here is the example from the ESLint docs on Ignoring Files and Directories:

# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

npm not working after clearing cache

I solved this issue by running cmd as an administrator. before that, I was trying to run in vs code.

run it in Power Shell or Cmd with administrative privilege. I hope that it will help.

npm install –g @angular/cli@latest