Programs & Examples On #Module management

How to use a switch case 'or' in PHP

Match expression (PHP 8)

PHP 8 RFC introduced a new match expression that is similar to switch but with the shorter syntax:

  • doesn't require break statements
  • combine conditions using a comma
  • returns a value

Example:

match ($value) {
  0 => '0',
  1, 2 => "1 or 2",
  default => "3",
}

JavaScript - Getting HTML form values

I know this is an old post but maybe someone down the line can use this.

_x000D_
_x000D_
// use document.form["form-name"] to reference the form
const ccForm = document.forms["ccform"];

// bind the onsubmit property to a function to do some logic
ccForm.onsubmit = function(e) {

  // access the desired input through the var we setup
  let ccSelection = ccForm.ccselect.value;
  console.log(ccSelection);

  e.preventDefault();
}
_x000D_
<form name="ccform">
  <select name="ccselect">
    <option value="card1">Card 1</option>
    <option value="card2">Card 2</option>
    <option value="card3">Card 3</option>
  </select>
  <button type="submit">Enter</button>
</form>
_x000D_
_x000D_
_x000D_

Nullable type as a generic parameter possible?

Just do two things to your original code – remove the where constraint, and change the last return from return null to return default(T). This way you can return whatever type you want.

By the way, you can avoid the use of is by changing your if statement to if (columnValue != DBNull.Value).

Standard concise way to copy a file in Java?

Fast and work with all the versions of Java also Android:

private void copy(final File f1, final File f2) throws IOException {
    f2.createNewFile();

    final RandomAccessFile file1 = new RandomAccessFile(f1, "r");
    final RandomAccessFile file2 = new RandomAccessFile(f2, "rw");

    file2.getChannel().write(file1.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f1.length()));

    file1.close();
    file2.close();
}

How can I send the "&" (ampersand) character via AJAX?

encodeURIComponent(Your text here);

This will truncate special characters.

Check if a string is not NULL or EMPTY

If the variable is a parameter then you could use advanced function parameter binding like below to validate not null or empty:

[CmdletBinding()]
Param (
    [parameter(mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Version
)

jQuery Show-Hide DIV based on Checkbox Value

I use jQuery prop

$('#yourCheckbox').change(function(){
  if($(this).prop("checked")) {
    $('#showDiv').show();
  } else {
    $('#hideDiv').hide();
  }
});

Application Installation Failed in Android Studio

Allow or enable "Installation from USB" in the developer options.

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

How to disable a link using only CSS?

Apply below class on html.

.avoid-clicks {
  pointer-events: none;
}

How to Free Inode Usage?

Late answer: In my case, it was my session files under

/var/lib/php/sessions

that were using Inodes.
I was even unable to open my crontab or making a new directory let alone triggering the deletion operation. Since I use PHP, we have this guide where I copied the code from example 1 and set up a cronjob to execute that part of the code.

<?php
// Note: This script should be executed by the same user of web server 
process.

// Need active session to initialize session data storage access.
session_start();

// Executes GC immediately
session_gc();

// Clean up session ID created by session_gc()
session_destroy();
?>

If you're wondering how did I manage to open my crontab, then well, I deleted some sessions manually through CLI.

Hope this helps!

Javascript ES6/ES5 find in array and change

Whereas most of the existing answers are great, I would like to include an answer using a traditional for loop, which should also be considered here. The OP requests an answer which is ES5/ES6 compatible, and the traditional for loop applies :)

The problem with using array functions in this scenario, is that they don't mutate objects, but in this case, mutation is a requirement. The performance gain of using a traditional for loop is just a (huge) bonus.

const findThis = 2;
const items = [{id:1, ...}, {id:2, ...}, {id:3, ...}];

for (let i = 0, l = items.length; i < l; ++i) {
  if (items[i].id === findThis) {
    items[i].iAmChanged = true;
    break;
  }
}

Although I am a great fan of array functions, don't let them be the only tool in your toolbox. If the purpose is mutating the array, they are not the best fit.

Removing object from array in Swift 3

This is official answer to find index of specific object, then you can easily remove any object using that index :

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
     // students[i] = "Max"
     students.remove(at: i)
}
print(students)
// Prints ["Ben", "Ivy", "Jordell"]

Here is the link: https://developer.apple.com/documentation/swift/array/2994720-firstindex

Refresh (reload) a page once using jQuery?

Alright, I think I got what you're asking for. Try this

if(window.top==window) {
    // You're not in a frame, so you reload the site.
    window.setTimeout('location.reload()', 3000); //Reloads after three seconds
}
else {
    //You're inside a frame, so you stop reloading.
}

If it is once, then just do

$('#div-id').triggerevent(function(){
    $('#div-id').html(newContent);
});

If it is periodically

function updateDiv(){
    //Get new content through Ajax
    ...
    $('#div-id').html(newContent);
}

setInterval(updateDiv, 5000); // That's five seconds

So, every five seconds the div #div-id content will refresh. Better than refreshing the whole page.

How to hide elements without having them take space on the page?

$('#abc').css({"display":"none"});

this hides the content and also does not leave empty space.

Error: "an object reference is required for the non-static field, method or property..."

You just need to make the siprimo and volteado methods static.

private static bool siprimo(long a)

and

private static long volteado(long a)

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer

Spring Data Rest - _links

onclick or inline script isn't working in extension

I had the same problem, and didn´t want to rewrite the code, so I wrote a function to modify the code and create the inline declarated events:

function compile(qSel){
    var matches = [];
    var match = null;
    var c = 0;

    var html = $(qSel).html();
    var pattern = /(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/mg;

    while (match = pattern.exec(html)) {
        var arr = [];
        for (i in match) {
            if (!isNaN(i)) {
                arr.push(match[i]);
            }
        }
        matches.push(arr);
    }
    var items_with_events = [];
    var compiledHtml = html;

    for ( var i in matches ){
        var item_with_event = {
            custom_id : "my_app_identifier_"+i,
            code : matches[i][5],
            on : matches[i][3],
        };
        items_with_events.push(item_with_event);
        compiledHtml = compiledHtml.replace(/(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/m, "<$2 custom_id='"+item_with_event.custom_id+"' $7 $8");
    }

    $(qSel).html(compiledHtml);

    for ( var i in items_with_events ){
        $("[custom_id='"+items_with_events[i].custom_id+"']").bind(items_with_events[i].on, function(){
            eval(items_with_events[i].code);
        });
    }
}

$(document).ready(function(){
    compile('#content');
})

This should remove all inline events from the selected node, and recreate them with jquery instead.

How do I modify a MySQL column to allow NULL?

Your syntax error is caused by a missing "table" in the query

ALTER TABLE mytable MODIFY mycolumn varchar(255) null;

Undefined symbols for architecture i386

At the risk of sounding obvious, always check the spelling of your forward class files. Sometimes XCode (at least XCode 4.3.2) will turn a declaration green that's actually camel cased incorrectly. Like in this example:

"_OBJC_CLASS_$_RadioKit", referenced from:
  objc-class-ref in RadioPlayerViewController.o

If RadioKit was a class file and you make it a property of another file, in the interface declaration, you might see that

Radiokit *rk;

has "Radiokit" in green when the actual decalaration should be:

RadioKit *rk;

This error will also throw this type of error. Another example (in my case), is when you have _iPhone and _iphone extensions on your class names for universal apps. Once I changed the appropriate file from _iphone to the correct _iPhone, the errors went away.

Change border-bottom color using jquery?

$('#elementid').css('border-bottom', 'solid 1px red');

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details.

List:

class List
{
    public:
        List(): head(nullptr), tail(nullptr) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list.

Android changing Floating Action Button color

I got the same problem and its all snatching my hair. Thanks for this https://stackoverflow.com/a/35697105/5228412

What we can do..

 favourite_fab.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.favourite_selected));

it works fine for me and wish for others who'll reach here.

Android - how to make a scrollable constraintlayout?

To summarize, you basically wrap your android.support.constraint.ConstraintLayout view in a ScrollView within the text of the *.xml file associated with your layout.

Example activity_sign_in.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SignInActivity"> <!-- usually the name of the Java file associated with this activity -->

    <android.support.constraint.ConstraintLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/gradient"
        tools:context="app.android.SignInActivity">

        <!-- all the layout details of your page -->

    </android.support.constraint.ConstraintLayout>
</ScrollView>

Note 1: The scroll bars only appear if a wrap is needed in any way, including the keyboard popping up.

Note 2: It also wouldn't be a bad idea to make sure your ConstraintLayout is big enough to the reach the bottom and sides of any given screen, especially if you have a background, as this will ensure that there isn't odd whitespace. You can do this with spaces if nothing else.

Compiling and Running Java Code in Sublime Text 2

Alex Yao's Answer is the simplest solution, if you just want to build and run Java program w/o taking any input from the console use the solution provided by Alex Yao. However if you would like to take input from the console then refer to the following link

Java console input in Sublime Text 2?

Find out if string ends with another string in C++

My two cents:

bool endsWith(std::string str, std::string suffix)
{
   return str.find(suffix, str.size() - suffix.size()) != string::npos;
}

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

Print array without brackets and commas

If you use Java8 or above, you can use with stream() with native.

publicArray.stream()
        .map(Object::toString)
        .collect(Collectors.joining(" "));

References

Does uninstalling a package with "pip" also remove the dependent packages?

i've successfully removed dependencies of a package using this bash line:

for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done

this worked on pip 1.5.4

How to efficiently use try...catch blocks in PHP

When an exception is thrown, execution is immediately halted and continues at the catch{} block. This means that, if you place the database calls in the same try{} block and $tableAresults = $dbHandler->doSomethingWithTableA(); throws an exception, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will not occur. With your second option, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will still occur since it is after the catch{} block, when execution has resumed.

There is no ideal option for every situation; if you want the second operation to continue regardless, then you must use two blocks. If it is acceptable (or desirable) to have the second operation not occur, then you should use only one.

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.

In other words, your code only works by accident, and probably not in all browsers.

Is this what you're trying to do?

<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>

Get all Attributes from a HTML element with Javascript/jQuery

Element.prototype.getA = function (a) {
        if (a) {
            return this.getAttribute(a);
        } else {
            var o = {};
            for(let a of this.attributes){
                o[a.name]=a.value;
            }
            return o;
        }
    }

having <div id="mydiv" a='1' b='2'>...</div> can use

mydiv.getA() // {id:"mydiv",a:'1',b:'2'}

How can I make a CSS table fit the screen width?

Put the table in a container element that has

overflow:scroll; max-width:95vw;

or make the table fit to the screen and overflow:scroll all table cells.

List attributes of an object

>>> class new_class():
...   def __init__(self, number):
...     self.multi = int(number) * 2
...     self.str = str(number)
... 
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])

You may also find pprint helpful.

How to pip or easy_install tkinter on Windows

I'm posting as the top answer requotes the documentation which I didn't find useful.

tkinter comes packaged with python install on windows IFF you select it during the install window.

The solution is to repair the installation (via uninstall GUI is fine), and select to install tk this time. You may need to point at or redownload the binary in this process. Downloading directly from activestate did not work for me.

This is a common problem people have on windows as it's easy to not want to install TCL/TK if you don't know what it is, but Matplotlib etc require it.

Git: Remove committed file after push

  1. Get the hash code of last commit.

    • git log
  2. Revert the commit
    • git revert <hash_code_from_git_log>
  3. Push the changes
    • git push

check out in the GHR. you might get what ever you need, hope you this is useful

Apache default VirtualHost

I had the same issue. I could fix it by adding the following in httpd.conf itself before the IncludeOptional directives for virtual hosts. Now localhost and the IP 192.168.x.x both points to the default test page of Apache. All other virtual hosts are working as expected.

<VirtualHost *:80>
    DocumentRoot /var/www/html
</VirtualHost>

Reference: https://httpd.apache.org/docs/2.4/vhosts/name-based.html#defaultvhost

Microsoft Visual C++ Compiler for Python 3.4

Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:

Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.

See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw

This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.

How to exit an application properly

Application.Exit
    End

will work like a charm The "END" immediately terminates further execution while "Application.Exit" closes all forms and calls.

Best regrads,

Full Page <iframe>

This is what I have used in the past.

html, body {
  height: 100%;
  overflow: auto;
}

Also in the iframe add the following style

border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%

How do I do an OR filter in a Django query?

It is worth to note that it's possible to add Q expressions.

For example:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='[email protected]'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)

queryset = User.objects.filter(query)

This ends up with a query like :

(first_name = 'mark' or email = '[email protected]') and last_name = 'doe'

This way there is no need to deal with or operators, reduce's etc.

How can I get (query string) parameters from the URL in Next.js?

import { useRouter } from 'next/router';

function componentName() {
    const router = useRouter();
    console.log('router obj', router);
}

We can find the query object inside a router using which we can get all query string parameters.

How to write an XPath query to match two attributes?

Sample XML:

<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>

string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"

XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

Generate fixed length Strings filled with whitespaces

Utilize String.format's padding with spaces and replace them with the desired char.

String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);

Prints 000Apple.


Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).

int width = 10;
char fill = '0';

String toPad = "New York";
String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
System.out.println(padded);

Prints 00New York.

But a check needs to be added to prevent the attempt of creating a char array with negative length.

How do I get the time of day in javascript/Node.js?

Check out the moment.js library. It works with browsers as well as with Node.JS. Allows you to write

moment().hour();

or

moment().hours();

without prior writing of any functions.

How can I declare dynamic String array in Java

Maybe you are looking for Vector. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList instead.

Call Python script from bash with argument

Print all args without the filename:

for i in range(1, len(sys.argv)):
print(sys.argv[i])

How to schedule a stored procedure in MySQL

In order to create a cronjob, follow these steps:

  1. run this command : SET GLOBAL event_scheduler = ON;

  2. If ERROR 1229 (HY000): Variable 'event_scheduler' is a GLOBAL variable and should be set with SET GLOBAL: mportant

It is possible to set the Event Scheduler to DISABLED only at server startup. If event_scheduler is ON or OFF, you cannot set it to DISABLED at runtime. Also, if the Event Scheduler is set to DISABLED at startup, you cannot change the value of event_scheduler at runtime.

To disable the event scheduler, use one of the following two methods:

  1. As a command-line option when starting the server:

    --event-scheduler=DISABLED
    
  2. In the server configuration file (my.cnf, or my.ini on Windows systems): include the line where it will be read by the server (for example, in a [mysqld] section):

    event_scheduler=DISABLED
    

    Read MySQL documentation for more information.

     DROP EVENT IF EXISTS EVENT_NAME;
      CREATE EVENT EVENT_NAME
     ON SCHEDULE EVERY 10 SECOND/minute/hour
     DO
     CALL PROCEDURE_NAME();
    

What is "origin" in Git?

remote(repository url alias) ? origin(upstream alias) ? master(branch alias);

  • remote, level same as working directory, index, repository,

  • origin, local repository branch map to remote repository branch

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

Try @ sign at start of expression. So you wont need to type escape characters just copy paste the regular expression in "" and put @ sign. Like so:

[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }

No notification sound when sending notification from firebase in android

The onMessageReceived method is fired only when app is in foreground or the notification payload only contains the data type.

From the Firebase docs

For downstream messaging, FCM provides two types of payload: notification and data.

For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

Further down the docs

App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.

If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.

If you want to play notification sound when app is in background using the conventional method, you need to add the sound parameter to the notification payload.

What's the difference between session.persist() and session.save() in Hibernate?

Actually, the difference between hibernate save() and persist() methods depends on generator class we are using.
If our generator class is assigned, then there is no difference between save() and persist() methods. Because generator ‘assigned’ means, as a programmer we need to give the primary key value to save in the database right [ Hope you know this generators concept ] In case of other than assigned generator class, suppose if our generator class name is Increment means hibernate itself will assign the primary key id value into the database right [other than assigned generator, hibernate only used to take care the primary key id value remember], so in this case if we call save() or persist() method, then it will insert the record into the database normally.
But here, thing is, save() method can return that primary key id value which is generated by hibernate and we can see it by
long s = session.save(k);
In this same case, persist() will never give any value back to the client, return type void.
persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries.
whereas in save(), INSERT happens immediately, no matter if you are inside or outside of a transaction.

Alternate table row color using CSS?

We can use odd and even CSS rules and jQuery method for alternate row colors

Using CSS

table tr:nth-child(odd) td{
           background:#ccc;
}
table tr:nth-child(even) td{
            background:#fff;
}

Using jQuery

$(document).ready(function()
{
  $("table tr:odd").css("background", "#ccc");
  $("table tr:even").css("background", "#fff");
});

_x000D_
_x000D_
table tr:nth-child(odd) td{_x000D_
           background:#ccc;_x000D_
}_x000D_
table tr:nth-child(even) td{_x000D_
            background:#fff;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>One</td>_x000D_
    <td>one</td>_x000D_
   </tr>_x000D_
  <tr>_x000D_
    <td>Two</td>_x000D_
    <td>two</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Pointer arithmetic for void pointer in C

The C standard does not allow void pointer arithmetic. However, GNU C is allowed by considering the size of void is 1.

C11 standard §6.2.5

Paragraph - 19

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

Following program is working fine in GCC compiler.

#include<stdio.h>

int main()
{
    int arr[2] = {1, 2};
    void *ptr = &arr;
    ptr = ptr + sizeof(int);
    printf("%d\n", *(int *)ptr);
    return 0;
}

May be other compilers generate an error.

Using pointer to char array, values in that array can be accessed?

When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:

printf("\nvalue:%c", (*ptr)[0]); , which is the same as *((*ptr)+0)

Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.

char arr[5] = {'a','b','c','d','e',0}; 
char *ptr = arr; //same as char *ptr = &arr[0]

printf("\nvalue:%c", ptr[0]);

How to detect if JavaScript is disabled?

You might, for instance, use something like document.location = 'java_page.html' to redirect the browser to a new, script-laden page. Failure to redirect implies that JavaScript is unavailable, in which case you can either resort to CGI ro utines or insert appropriate code between the tags. (NOTE: NOSCRIPT is only available in Netscape Navigator 3.0 and up.)

credit http://www.intranetjournal.com/faqs/jsfaq/how12.html

Input Type image submit form value?

Inputs of type="image" don't send their name/value pair when used to submit the form. To me, that sounds like a bug, but that's how it is.

To get around this, you can replace the input with a button of type="submit", and put a img element inside.

Unfortunately, that causes your image to be in a ugly HTML "button". However, assuming you aren't using the standard HTML button anywhere, you can just override the stylesheet, and then everything should work as expected:

_x000D_
_x000D_
button, input[type="submit"], input[type="reset"] {_x000D_
 background: none;_x000D_
 color: inherit;_x000D_
 border: none;_x000D_
 padding: 0;_x000D_
 font: inherit;_x000D_
 cursor: pointer;_x000D_
 outline: inherit;_x000D_
}
_x000D_
<form action="/post">_x000D_
<input name="test">_x000D_
<button type="submit" name="submit_button" value="submitted">_x000D_
<img src="https://via.placeholder.com/32" alt="image">_x000D_
</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Size of Matrix OpenCV

cv:Mat mat;
int rows = mat.rows;
int cols = mat.cols;

cv::Size s = mat.size();
rows = s.height;
cols = s.width;

Also note that stride >= cols; this means that actual size of the row can be greater than element size x cols. This is different from the issue of continuous Mat and is related to data alignment.

jQuery: Change button text on click

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore2');
    if($this.hasClass('SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

This should do it. You have to make sure you toggle the correct class and take out the "." from the hasClass

http://jsfiddle.net/V4u5X/2/

Delete an element from a dictionary

    species = {'HI': {'1': (1215.671, 0.41600000000000004),
  '10': (919.351, 0.0012),
  '1025': (1025.722, 0.0791),
  '11': (918.129, 0.0009199999999999999),
  '12': (917.181, 0.000723),
  '1215': (1215.671, 0.41600000000000004),
  '13': (916.429, 0.0005769999999999999),
  '14': (915.824, 0.000468),
  '15': (915.329, 0.00038500000000000003),
 'CII': {'1036': (1036.3367, 0.11900000000000001), '1334': (1334.532, 0.129)}}

The following code will make a copy of dict species and delete items which are not in trans_HI

trans_HI=['1025','1215']
for transition in species['HI'].copy().keys():
    if transition not in trans_HI:
        species['HI'].pop(transition)

How to get difference between two rows for a column field?

SELECT
   [current].rowInt,
   [current].Value,
   ISNULL([next].Value, 0) - [current].Value
FROM
   sourceTable       AS [current]
LEFT JOIN
   sourceTable       AS [next]
      ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt)

EDIT:

Thinking about it, using a subquery in the select (ala Quassnoi's answer) may be more efficient. I would trial different versions, and look at the execution plans to see which would perform best on the size of data set that you have...


EDIT2:

I still see this garnering votes, though it's unlikely many people still use SQL Server 2005.

If you have access to Windowed Functions such as LEAD(), then use that instead...

SELECT
  RowInt,
  Value,
  LEAD(Value, 1, 0) OVER (ORDER BY RowInt) - Value
FROM
  sourceTable

Twig for loop for arrays with keys

These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:

1D Array

Without Key Sort and Reverse

{% for key, value in array_one_dimension %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort

{% for key, value in array_one_dimension|keys|sort %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort and Reverse

{% for key, value in array_one_dimension|keys|sort|reverse %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

2D Arrays

Without Key Sort and Reverse

{% for key_a, value_a in array_two_dimension %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Both Outer and Inner Arrays

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array & Key Sort and Reverse on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Outer Array & Key Sort on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Both Outer and Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Setting dynamic scope variables in AngularJs - scope.<some_string>

If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.

This is what I use for an API success response for JSON data array...

function(data){

    $scope.subjects = [];

    $.each(data, function(i,subject){
        //Store array of data types
        $scope.subjects.push(subject.name);

        //Split data in to arrays
        $scope[subject.name] = subject.data;
    });
}

Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

How to get last N records with activerecord?

Add an :order parameter to the query

Does Java have a path joining method?

This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.

import java.io.File;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        System.out.println(pathJoin());
        System.out.println(pathJoin(""));
        System.out.println(pathJoin("a"));
        System.out.println(pathJoin("a", "b"));
        System.out.println(pathJoin("a", "b", "c"));
        System.out.println(pathJoin("a", "b", "", "def"));
    }

    public static String pathJoin(final String ... pathElements)
    {
        final String path;

        if(pathElements == null || pathElements.length == 0)
        {
            path = File.separator;
        }
        else
        {
            final StringBuilder builder;

            builder = new StringBuilder();

            for(final String pathElement : pathElements)
            {
                final String sanitizedPathElement;

                // the "\\" is for Windows... you will need to come up with the 
                // appropriate regex for this to be portable
                sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");

                if(sanitizedPathElement.length() > 0)
                {
                    builder.append(sanitizedPathElement);
                    builder.append(File.separator);
                }
            }

            path = builder.toString();
        }

        return (path);
    }
}

Remove a git commit which has not been pushed

This is what I do:

First checkout your branch (for my case master branch):

git checkout master

Then reset to remote HEAD^ (it'll remove all your local changes), force clean and pull:

git reset HEAD^ --hard && git clean -df && git pull

What is a non-capturing group in regular expressions?

tl;dr non-capturing groups, as the name suggests are the parts of the regex that you do not want to be included in the match and ?: is a way to define a group as being non-capturing.

Let's say you have an email address [email protected]. The following regex will create two groups, the id part and @example.com part. (\p{Alpha}*[a-z])(@example.com). For simplicity's sake, we are extracting the whole domain name including the @ character.

Now let's say, you only need the id part of the address. What you want to do is to grab the first group of the match result, surrounded by () in the regex and the way to do this is to use the non-capturing group syntax, i.e. ?:. So the regex (\p{Alpha}*[a-z])(?:@example.com) will return just the id part of the email.

Pycharm: run only part of my Python file

You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:

enter image description here

After you've enabled, set a break-point to where you want it to:

enter image description here

After you're done setting the break-point:

enter image description here

Once that has been completed:

enter image description here

Finding absolute value of a number without using Math.abs()

In case of the absolute value of an integer x without using Math.abs(), conditions or bit-wise operations, below could be a possible solution in Java.

(int)(((long)x*x - 1)%(double)x + 1);

Because Java treats a%b as a - a/b * b, the sign of the result will be same as "a" no matter what sign of "b" is; (x*x-1)%x will equal abs(x)-1; type casting of "long" is to prevent overflow and double allows dividing by zero.

Again, x = Integer.MIN_VALUE will cause overflow due to subtracting 1.

Is there Java HashMap equivalent in PHP?

HashMap that also works with keys other than strings and integers with O(1) read complexity (depending on quality of your own hash-function).

You can make a simple hashMap yourself. What a hashMap does is storing items in a array using the hash as index/key. Hash-functions give collisions once in a while (not often, but they may do), so you have to store multiple items for an entry in the hashMap. That simple is a hashMap:

class IEqualityComparer {
    public function equals($x, $y) {
        throw new Exception("Not implemented!");
    }
    public function getHashCode($obj) {
        throw new Exception("Not implemented!");
    }
}

class HashMap {
    private $map = array();
    private $comparer;

    public function __construct(IEqualityComparer $keyComparer) {
        $this->comparer = $keyComparer;
    }

    public function has($key) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            return false;
        }

        foreach ($this->map[$hash] as $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                return true;
            }
        }

        return false;
    }

    public function get($key) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            return false;
        }

        foreach ($this->map[$hash] as $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                return $item['value'];
            }
        }

        return false;
    }

    public function del($key) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            return false;
        }

        foreach ($this->map[$hash] as $index => $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                unset($this->map[$hash][$index]);
                if (count($this->map[$hash]) == 0)
                    unset($this->map[$hash]);

                return true;
            }
        }

        return false;
    }

    public function put($key, $value) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            $this->map[$hash] = array();
        }

        $newItem = array('key' => $key, 'value' => $value);        

        foreach ($this->map[$hash] as $index => $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                $this->map[$hash][$index] = $newItem;
                return;
            }
        }

        $this->map[$hash][] = $newItem;
    }
}

For it to function you also need a hash-function for your key and a comparer for equality (if you only have a few items or for another reason don't need speed you can let the hash-function return 0; all items will be put in same bucket and you will get O(N) complexity)

Here is an example:

class IntArrayComparer extends IEqualityComparer {
    public function equals($x, $y) {
        if (count($x) !== count($y))
            return false;

        foreach ($x as $key => $value) {
            if (!isset($y[$key]) || $y[$key] !== $value)
                return false;
        }

        return true;
    }

    public function getHashCode($obj) {
        $hash = 0;
        foreach ($obj as $key => $value)
            $hash ^= $key ^ $value;

        return $hash;
    }
}

$hashmap = new HashMap(new IntArrayComparer());

for ($i = 0; $i < 10; $i++) {
    for ($j = 0; $j < 10; $j++) {
        $hashmap->put(array($i, $j), $i * 10 + $j);
    }
}

echo $hashmap->get(array(3, 7)) . "<br/>";
echo $hashmap->get(array(5, 1)) . "<br/>";

echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(-1, 9))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(6))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(1, 2, 3))? 'true': 'false') . "<br/>";

$hashmap->del(array(8, 4));
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";

Which gives as output:

37
51
true
false
false
false
false

Comparing strings by their alphabetical order

String.compareTo might or might not be what you need.

Take a look at this link if you need localized ordering of strings.

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

You can access any LayoutParams from code using View.getLayoutParams. You just have to be very aware of what LayoutParams your accessing. This is normally achieved by checking the containing ViewGroup if it has a LayoutParams inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams. You'll be using RelativeLayout.LayoutParams#addRule(int verb) and RelativeLayout.LayoutParams#addRule(int verb, int anchor)

You can get to it via code:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

button.setLayoutParams(params); //causes layout update

adding child nodes in treeview

You can improve that code

 private void Form1_Load(object sender, EventArgs e)
    {
        /*
         D:\root\Project1\A\A.pdf
         D:\root\Project1\B\t.pdf
         D:\root\Project2\c.pdf
         */
        List<string> n = new List<string>();
        List<string> kn = new List<string>();
        n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        foreach (var item in kn)
        {
            treeView1.Nodes.Add(item.ToString());
        }
        for (int i = 0; i < treeView1.Nodes.Count; i++)
        {
            n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
            for (int zik = 0; zik < n.Count; zik++)
            {
                treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
            }
        }        
    }

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

Checkboxes in web pages – how to make them bigger?

I'm writtinga phonegap app, and checkboxes vary in size, look, etc. So I made my own simple checkbox:

First the HTML code:

<span role="checkbox"/>

Then the CSS:

[role=checkbox]{
    background-image: url(../img/checkbox_nc.png);
    height: 15px;
    width: 15px;
    display: inline-block;
    margin: 0 5px 0 5px;
    cursor: pointer;
}

.checked[role=checkbox]{
    background-image: url(../img/checkbox_c.png);
}

To toggle checkbox state, I used JQuery:

CLICKEVENT='touchend';
function createCheckboxes()
{
    $('[role=checkbox]').bind(CLICKEVENT,function()
    {
        $(this).toggleClass('checked');
    });
}

But It can easily be done without it...

Hope it can help!

Appending a list or series to a pandas DataFrame as a row?

As mentioned here - https://kite.com/python/answers/how-to-append-a-list-as-a-row-to-a-pandas-dataframe-in-python, you'll need to first convert the list to a series then append the series to dataframe.

df = pd.DataFrame([[1, 2], [3, 4]], columns = ["a", "b"])
to_append = [5, 6]
a_series = pd.Series(to_append, index = df.columns)
df = df.append(a_series, ignore_index=True)

Access localhost from the internet

use your ip address or a service like noip.com if you need something more practical. Then eventually configure your router properly so incoming connection will be forwarded to the machine with the server running.

Check last modified date of file in C#

Just use File.GetLastWriteTime. There's a sample on that page showing how to use it.

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

C++ template constructor

You can create a templated factory function:

class Foo
{
public:
    template <class T> static Foo* create() // could also return by value, or a smart pointer
    {
        return new Foo(...);
    }
...        
};

Internet Explorer cache location

If you want to find the folder in a platform independent way, you should query the registry key:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache

Which maven dependencies to include for spring 3.0?

Use a BOM to solve version issues.

you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.

https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/html/overview.html#overview-maven-bom

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-framework-bom</artifactId>
  <version>3.2.12.RELEASE</version>
  <type>pom</type>
</dependency>

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Generate random number between two numbers in JavaScript

Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.

function randomBetween(min, max) {
    if (min < 0) {
        return min + Math.random() * (Math.abs(min)+max);
    }else {
        return min + Math.random() * max;
    }
}

E.g

randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)

Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.

SQL SELECT WHERE field contains words

try to use the "tesarus search" in full text index in MS SQL Server. This is much better than using "%" in search if you have millions of records. tesarus have a small amount of memory consumption than the others. try to search this functions :)

Working copy locked error in tortoise svn while committing

I had no idea what file was having the lock so what I did to get out of this issue was:

  1. Went to the highest level folder
  2. Click clean-up and also ticked from the cleaning-up methods --> Break locks

This worked for me.

CKEditor instance already exists

remove class="ckeditor" , it might have triggered ckeditor initialization

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

A simpler solution on recent versions of tmux (tested on 1.9) you can now do :

tmux detach -a

-a is for all other client on this session except the current one

You can alias it in your .[bash|zsh]rc

alias takeover="tmux detach -a"

Workflow: You can connect to your session normally, and if you are bothered by another session that forced down your tmux window size you can simply call takeover.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

If you need to override IE's Compatibility View Settings for intranet sites you can do so in the web.config (IIS7) or through the custom HTTP headers in the web site's properties (IIS6) and set X-UA-Compatible there. The meta tag doesn't override IE's intranet setting in Compatibility View Settings, but if you set it at the hosting server it will override the compatibility.

Example for web.config in IIS7:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=EmulateIE8" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Edit: I removed the clear code from just before the add; it was an unnecessary oversight from copying and pasting. Good catch, commenters!

Omit rows containing specific column of NA

Try this:

cc=is.na(DF$y)
m=which(cc==c("TRUE"))
DF=DF[-m,]

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

If you are not using "-XX:HeapDumpPath" option then in case of JBoss EAP/As by default the heap dump file will be generated in "JBOSS_HOME/bin" directory.

Laravel 5: Retrieve JSON array from $request

 $postbody='';
 // Check for presence of a body in the request
 if (count($request->json()->all())) {
     $postbody = $request->json()->all();
 }

This is how it's done in laravel 5.2 now.

Compare objects in Angular

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this Demo with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

Android Stop Emulator from Command Line

FOR MAC:

  1. Run:
ps -ax | grep emulator 

which gives you a wider result something like:

 6617 ??         9:05.54 /Users/nav/Library/Android/sdk/emulator/qemu/darwin-x86_64/qemu-system-x86_64 -netdelay none -netspeed full -avd Nexus_One_API_29
 6619 ??         0:06.10 /Users/nav/Library/Android/sdk/emulator/emulator64-crash-service -pipe com.google.AndroidEmulator.CrashService.6617 -ppid 6617 -data-dir /tmp/android-nav/
 6658 ??         0:07.93 /Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/QtWebEngineProcess --type=renderer --disable-accelerated-video-decode --disable-gpu-memory-buffer-video-frames --disable-pepper-3d-image-chromium --enable-threaded-compositing --file-url-path-alias=/gen=/Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/gen --enable-features=AllowContentInitiatedDataUrlNavigations --disable-features=MacV2Sandbox,MojoVideoCapture,SurfaceSynchronization,UseVideoCaptureApiForDevToolsSnapshots --disable-gpu-compositing --service-pipe-token=15570406721898250245 --lang=en-US --webengine-schemes=qrc:sLV --num-raster-threads=4 --enable-main-frame-before-activation --service-request-channel-token=15570406721898250245 --renderer-client-id=2
 6659 ??         0:01.11 /Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/QtWebEngineProcess --type=renderer --disable-accelerated-video-decode --disable-gpu-memory-buffer-video-frames --disable-pepper-3d-image-chromium --enable-threaded-compositing --file-url-path-alias=/gen=/Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/gen --enable-features=AllowContentInitiatedDataUrlNavigations --disable-features=MacV2Sandbox,MojoVideoCapture,SurfaceSynchronization,UseVideoCaptureApiForDevToolsSnapshots --disable-gpu-compositing --service-pipe-token=--lang=en-US --webengine-schemes=qrc:sLV --num-raster-threads=4 --enable-main-frame-before-activation --service-request-channel-token=  --renderer-client-id=3
10030 ttys000    0:00.00 grep emulator
  1. The first (left) column is the process ID (PID) that you are looking for.

  2. Find the first PID (in the above example, it's 6617).

  3. Force kill that process:

kill -9 PID

In my case, the command is:

kill -9 6617
  1. Usually, killing the first process in enough to stop the emulator, but if that doesn't work, try killing other processes as well.

Animate scroll to ID on page load

Pure javascript solution with scrollIntoView() function:

_x000D_
_x000D_
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
_x000D_
<h2 id="title1">Some title</h2>
_x000D_
_x000D_
_x000D_

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.

Include php files when they are in different folders

Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

When I understand this correctly, you replace the default constructor with a parameterized one and therefore have to describe the JSON keys which are used to call the constructor with.

Dynamic SQL results into temp table in SQL Stored procedure

Try:

SELECT into #T1 execute ('execute ' + @SQLString )

And this smells real bad like an sql injection vulnerability.


correction (per @CarpeDiem's comment):

INSERT into #T1 execute ('execute ' + @SQLString )

also, omit the 'execute' if the sql string is something other than a procedure

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

React PropTypes : Allow different types of PropTypes for one prop

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

Sorting Directory.GetFiles()

In .NET 2.0, you'll need to use Array.Sort to sort the FileSystemInfos.

Additionally, you can use a Comparer delegate to avoid having to declare a class just for the comparison:

DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] files = dir.GetFileSystemInfos();

// sort them by creation time
Array.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)
                                    {
                                        return a.LastWriteTime.CompareTo(b.LastWriteTime);
                                    });

How do I download the Android SDK without downloading Android Studio?

You can find the command line tools at the downloads page under the "Command line tools only" section.

enter image description here

These are the links provided in the page as of now (version 26.1.1):

Be sure to have read and agreed with the terms of service before downloading any of the command line tools.

The installer version for windows doesn't seem to be available any longer, this is the link for version 24.4.1:

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

Find and replace words/lines in a file

Any decent text editor has a search&replace facility that supports regular expressions.

If however, you have reason to reinvent the wheel in Java, you can do:

Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

This only works for Java 7 or newer. If you are stuck on an older Java, you can do:

String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);

In this case, you'll need to add error handling and close the streams after you are done with them.

IOUtils is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html

Normalizing images in OpenCV

The other answers normalize an image based on the entire image. But if your image has a predominant color (such as black), it will mask out the features that you're trying to enhance since it will not be as pronounced. To get around this limitation, we can normalize the image based on a subsection region of interest (ROI). Essentially we will normalize based on the section of the image that we want to enhance instead of equally treating each pixel with the same weight. Take for instance this earth image:

Input image -> Normalization based on entire image

If we want to enhance the clouds by normalizing based on the entire image, the result will not be very sharp and will be over saturated due to the black background. The features to enhance are lost. So to obtain a better result we can crop a ROI, normalize based on the ROI, and then apply the normalization back onto the original image. Say we crop the ROI highlighted in green:

This gives us this ROI

The idea is to calculate the mean and standard deviation of the ROI and then clip the frame based on the lower and upper range. In addition, we could use an offset to dynamically adjust the clip intensity. From here we normalize the original image to this new range. Here's the result:

Before -> After

Code

import cv2
import numpy as np

# Load image as grayscale and crop ROI
image = cv2.imread('1.png', 0)
x, y, w, h = 364, 633, 791, 273
ROI = image[y:y+h, x:x+w]

# Calculate mean and STD
mean, STD  = cv2.meanStdDev(ROI)

# Clip frame to lower and upper STD
offset = 0.2
clipped = np.clip(image, mean - offset*STD, mean + offset*STD).astype(np.uint8)

# Normalize to range
result = cv2.normalize(clipped, clipped, 0, 255, norm_type=cv2.NORM_MINMAX)

cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.imshow('result', result)
cv2.waitKey()

The difference between normalizing based on the entire image vs a specific section of the ROI can be visualized by applying a heatmap to the result. Notice the difference on how the clouds are defined.

Input image -> heatmap

Normalized on entire image -> heatmap

Normalized on ROI -> heatmap

Heatmap code

import matplotlib.pyplot as plt
import numpy as np
import cv2

image = cv2.imread('result.png', 0)
colormap = plt.get_cmap('inferno')
heatmap = (colormap(image) * 2**16).astype(np.uint16)[:,:,:3]
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_RGB2BGR)

cv2.imshow('image', image)
cv2.imshow('heatmap', heatmap)
cv2.waitKey()

Note: The ROI bounding box coordinates were obtained using how to get ROI Bounding Box Coordinates without Guess & Check and heatmap code was from how to convert a grayscale image to heatmap image with Python OpenCV

Operation is not valid due to the current state of the object, when I select a dropdown list

I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

In your project, find Target -> Build Settings -> Other Linker Flags, select Other Linker Flags, press delete(Mac Keyboard)/Backspace(Normal keyboard) to recover the setting. It works for me.

Example:

Before enter image description here

After enter image description here

Is Python interpreted, or compiled, or both?

The answer depends on what implementation of python is being used. If you are using lets say CPython (The Standard implementation of python) or Jython (Targeted for integration with java programming language)it is first translated into bytecode, and depending on the implementation of python you are using, this bycode is directed to the corresponding virtual machine for interpretation. PVM (Python Virtual Machine) for CPython and JVM (Java Virtual Machine) for Jython.

But lets say you are using PyPy which is another standard CPython implementation. It would use a Just-In-Time Compiler.

HTML - Arabic Support

Won't you need the ensure the area where you display the Arabic is Right-to-Left orientated also?

e.g.

<p dir="rtl">

JavaScript Chart.js - Custom data formatting to display on tooltip

tooltips: {
    callbacks: {
        label: function (tooltipItem) {
            return (new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
            })).format(tooltipItem.value);
        }
    }
}

Unix epoch time to Java Date object

How about just:

Date expiry = new Date(Long.parseLong(date));

EDIT: as per rde6173's answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:

Date expiry = new Date(Long.parseLong(date) * 1000);

Concatenate strings from several rows using Pandas groupby

You can groupby the 'name' and 'month' columns, then call transform which will return data aligned to the original df and apply a lambda where we join the text entries:

In [119]:

df['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))
df[['name','text','month']].drop_duplicates()
Out[119]:
    name         text  month
0  name1       hej,du     11
2  name1        aj,oj     12
4  name2     fin,katt     11
6  name2  mycket,lite     12

I sub the original df by passing a list of the columns of interest df[['name','text','month']] here and then call drop_duplicates

EDIT actually I can just call apply and then reset_index:

In [124]:

df.groupby(['name','month'])['text'].apply(lambda x: ','.join(x)).reset_index()

Out[124]:
    name  month         text
0  name1     11       hej,du
1  name1     12        aj,oj
2  name2     11     fin,katt
3  name2     12  mycket,lite

update

the lambda is unnecessary here:

In[38]:
df.groupby(['name','month'])['text'].apply(','.join).reset_index()

Out[38]: 
    name  month         text
0  name1     11           du
1  name1     12        aj,oj
2  name2     11     fin,katt
3  name2     12  mycket,lite

Java collections convert a string to a list of characters

You can do this without boxing if you use Eclipse Collections:

CharAdapter abc = Strings.asChars("abc");
CharList list = abc.toList();
CharSet set = abc.toSet();
CharBag bag = abc.toBag();

Because CharAdapter is an ImmutableCharList, calling collect on it will return an ImmutableList.

ImmutableList<Character> immutableList = abc.collect(Character::valueOf);

If you want to return a boxed List, Set or Bag of Character, the following will work:

LazyIterable<Character> lazyIterable = abc.asLazy().collect(Character::valueOf);
List<Character> list = lazyIterable.toList();
Set<Character> set = lazyIterable.toSet();
Bag<Character> set = lazyIterable.toBag();

Note: I am a committer for Eclipse Collections.

how to convert image to byte array in java?

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • What is a "callback" in C and how are they implemented?

    This wikipedia article has an example in C.

    A good example is that new modules written to augment the Apache Web server register with the main apache process by passing them function pointers so those functions are called back to process web page requests.

    What's in an Eclipse .classpath/.project file?

    This eclipse documentation has details on the markups in .project file: The project description file

    It describes the .project file as:

    When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

    Unsupported operand type(s) for +: 'int' and 'str'

    try,

    str_list = " ".join([str(ele) for ele in numlist])

    this statement will give you each element of your list in string format

    print("The list now looks like [{0}]".format(str_list))

    and,

    change print(numlist.pop(2)+" has been removed") to

    print("{0} has been removed".format(numlist.pop(2)))

    as well.

    navbar color in Twitter Bootstrap

    If you are using the LESS or SASS Version of the Bootstrap. The most efficient way is to change the variable name, in the LESS or SASS file.

    $navbar-default-color:              #FFFFFF !default;
    $navbar-default-bg:                 #36669d !default;
    $navbar-default-border:             $navbar-default-bg !default;
    

    This by far the most easiest and the most efficient way to change the Bootstraps Navbar. You need not write overrides, and the code remains clean.

    Proper MIME type for OTF fonts

    Try using "font/opentype".

    Putting a simple if-then-else statement on one line

    count = 0 if count == N else N+1
    

    - the ternary operator. Although I'd say your solution is more readable than this.

    Unable to open a file with fopen()

    Well, now you know there is a problem, the next step is to figure out what exactly the error is, what happens when you compile and run this?:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        FILE *file;
        file = fopen("TestFile1.txt", "r");
        if (file == NULL) {
          perror("Error");
        } else {
          fclose(file);
        }
    }
    

    What evaluates to True/False in R?

    T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

    Run CRON job everyday at specific time

    you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM

    1 10 * * * php -f /var/www/package/index.php controller function
    
    30 14 * * * php -f /var/www/package/index.php controller function
    

    but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30 .

    30 10,14 * * * php -f /var/www/package/index.php controller function
    

    Good Hash Function for Strings

             public String hashString(String s) throws NoSuchAlgorithmException {
        byte[] hash = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            hash = md.digest(s.getBytes());
    
        } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.length; ++i) {
            String hex = Integer.toHexString(hash[i]);
            if (hex.length() == 1) {
                sb.append(0);
                sb.append(hex.charAt(hex.length() - 1));
            } else {
                sb.append(hex.substring(hex.length() - 2));
            }
        }
        return sb.toString();
    }
    

    SSH Private Key Permissions using Git GUI or ssh-keygen are too open

    You changed the permissions on the whole directory, which I agree with Splash is a bad idea. If you can remember what the original permissions for the directory are, I would try to set them back to that and then do the following

    cd ~/.ssh
    chmod 700 id_rsa
    

    inside the .ssh folder. That will set the id_rsa file to rwx (read, write, execute) for the owner (you) only, and zero access for everyone else.

    If you can't remember what the original settings are, add a new user and create a set of SSH keys for that user, thus creating a new .ssh folder which will have default permissions. You can use that new .ssh folder as the reference for permissions to reset your .ssh folder and files to.

    If that doesn't work, I would try doing an uninstall of msysgit, deleting ALL .ssh folders on the computer (just for safe measure), then reinstalling msysgit with your desired settings and try starting over completely (though I think you told me you tried this already).

    Edited: Also just found this link via Google -- Fixing "WARNING: UNPROTECTED PRIVATE KEY FILE!" on Linux While it's targeted at linux, it might help since we're talking liunx permissions and such.

    Comparing Arrays of Objects in JavaScript

    There`s my solution. It will compare arrays which also have objects and arrays. Elements can be stay in any positions. Example:

    const array1 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
    const array2 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
    
    const arraysCompare = (a1, a2) => {
      if (a1.length !== a2.length) return false;
      const objectIteration = (object) => {
        const result = [];
        const objectReduce = (obj) => {
          for (let i in obj) {
            if (typeof obj[i] !== 'object') {
              result.push(`${i}${obj[i]}`);
            } else {
              objectReduce(obj[i]);
            }
          }
        };
        objectReduce(object);
        return result;
      };
      const reduceArray1 = a1.map(item => {
        if (typeof item !== 'object') return item;
        return objectIteration(item).join('');
      });
      const reduceArray2 = a2.map(item => {
        if (typeof item !== 'object') return item;
        return objectIteration(item).join('');
      });
      const compare =  reduceArray1.map(item => reduceArray2.includes(item));
      return compare.reduce((acc, item) => acc + Number(item)) === a1.length;
    };
    
    console.log(arraysCompare(array1, array2));
    

    How to check whether a Storage item is set?

    You can use hasOwnProperty method to check this

    > localStorage.setItem('foo', 123)
    undefined
    > localStorage.hasOwnProperty('foo')
    true
    > localStorage.hasOwnProperty('bar')
    false
    

    Works in current versions of Chrome(Mac), Firefox(Mac) and Safari.

    SQL Case Sensitive String Compare

    Just as another alternative you could use HASHBYTES, something like this:

    SELECT * 
    FROM a_table 
    WHERE HASHBYTES('sha1', attribute) = HASHBYTES('sha1', 'k')
    

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

    You can install other builds but not Appstore build.

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

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

    How can I get key's value from dictionary in Swift?

    For finding value use below

    if let a = companies["AAPL"] {
       // a is the value
    }
    

    For traversing through the dictionary

    for (key, value) in companies {
        print(key,"---", value)
    }
    

    Finally for searching key by value you firstly add the extension

    extension Dictionary where Value: Equatable {
        func findKey(forValue val: Value) -> Key? {
            return first(where: { $1 == val })?.key
        }
    }
    

    Then just call

    companies.findKey(val : "Apple Inc")
    

    Visual Studio breakpoints not being hit

    In my case I had a string of length 70kb. Compiler did not thrown any error. But Debugger failed to hit the break point. After spending 3 hours and scratching my hair I found the cause for not hitting the break point. After removing 70kb data break point worked as normal.

    Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

    For anyone who works in VB.NET

    Try
    Catch ex As DbEntityValidationException
        For Each a In ex.EntityValidationErrors
            For Each b In a.ValidationErrors
                Dim st1 As String = b.PropertyName
                Dim st2 As String = b.ErrorMessage
            Next
        Next
    End Try
    

    removing table border

    Use Firebug to inspect the table in question, and see where does it inherit the border from. (check the right column). Try setting on-the-fly inline style border:none; to see if you get rid of it. Could also be the browsers default stylesheets. In this case, use a CSS reset. http://developer.yahoo.com/yui/reset/

    How to escape braces (curly brackets) in a format string in .NET

    For you to output foo {1, 2, 3} you have to do something like:

    string t = "1, 2, 3";
    string v = String.Format(" foo {{{0}}}", t);
    

    To output a { you use {{ and to output a } you use }}.

    or Now, you can also use c# string interpolation like this (feature available in C# 6.0)

    Escaping Brackets: String Interpolation $(""). it is new feature in C# 6.0

    var inVal = "1, 2, 3";
    var outVal = $" foo {{{inVal}}}";
    //Output will be:  foo {1, 2, 3}
    

    Flutter - The method was called on null

    You have a CryptoListPresenter _presenter but you are never initializing it. You should either be doing that when you declare it or in your initState() (or another appropriate but called-before-you-need-it method).

    One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.

    EDIT:

    I see diegoveloper beat me to answering this, and that the OP asked a follow up.

    @Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);, or

    CryptoListPresenter _presenter;
    
    @override
    void initState() {
      _presenter = new CryptoListPresenter(...);
    }
    

    Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

    This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:

    ' Get customer workbook...
    Dim customerBook As Workbook
    Dim filter As String
    Dim caption As String
    Dim customerFilename As String
    Dim customerWorkbook As Workbook
    Dim targetWorkbook As Workbook
    
    ' make weak assumption that active workbook is the target
    Set targetWorkbook = Application.ActiveWorkbook
    
    ' get the customer workbook
    filter = "Text files (*.xlsx),*.xlsx"
    caption = "Please Select an input file "
    customerFilename = Application.GetOpenFilename(filter, , caption)
    
    Set customerWorkbook = Application.Workbooks.Open(customerFilename)
    
    ' assume range is A1 - C10 in sheet1
    ' copy data from customer to target workbook
    Dim targetSheet As Worksheet
    Set targetSheet = targetWorkbook.Worksheets(1)
    Dim sourceSheet As Worksheet
    Set sourceSheet = customerWorkbook.Worksheets(1)
    
    targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
    
    ' Close customer workbook
    customerWorkbook.Close
    

    Reload chart data via JSON with Highcharts

    Correct answer is:

    $.each(lines, function(lineNo, line) {
                        var items = line.split(',');
                        var data = {};
                        $.each(items, function(itemNo, item) {
                            if (itemNo === 0) {
                                data.name = item;
                            } else {
                                data.y = parseFloat(item);
                            }
                        });
                        options.series[0].data.push(data);
                        data = {};
                    });
    

    You need to flush the 'data' array.

    data = {};
    

    How do I make bootstrap table rows clickable?

    That code transforms any bootstrap table row that has data-href attribute set into a clickable element

    Note: data-href attribute is a valid tr attribute (HTML5), href attributes on tr element are not.

    $(function(){
        $('.table tr[data-href]').each(function(){
            $(this).css('cursor','pointer').hover(
                function(){ 
                    $(this).addClass('active'); 
                },  
                function(){ 
                    $(this).removeClass('active'); 
                }).click( function(){ 
                    document.location = $(this).attr('data-href'); 
                }
            );
        });
    });
    

    How to fire AJAX request Periodically?

    Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here's how you might do it with setTimeout:

    function executeQuery() {
      $.ajax({
        url: 'url/path/here',
        success: function(data) {
          // do something with the return value here if you like
        }
      });
      setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
    }
    
    $(document).ready(function() {
      // run the first time; all subsequent calls will take care of themselves
      setTimeout(executeQuery, 5000);
    });
    

    How to find first element of array matching a boolean condition in JavaScript?

    As of ECMAScript 6, you can use Array.prototype.find for this. This is implemented and working in Firefox (25.0), Chrome (45.0), Edge (12), and Safari (7.1), but not in Internet Explorer or a bunch of other old or uncommon platforms.

    For example, x below is 106:

    _x000D_
    _x000D_
    const x = [100,101,102,103,104,105,106,107,108,109].find(function (el) {
        return el > 105;
    });
    console.log(x);
    _x000D_
    _x000D_
    _x000D_

    If you want to use this right now but need support for IE or other unsupporting browsers, you can use a shim. I recommend the es6-shim. MDN also offers a shim if for some reason you don't want to put the whole es6-shim into your project. For maximum compatibility you want the es6-shim, because unlike the MDN version it detects buggy native implementations of find and overwrites them (see the comment that begins "Work around bugs in Array#find and Array#findIndex" and the lines immediately following it).

    [Ljava.lang.Object; cannot be cast to

    java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource
    

    Problem is

    (List<SwitcherServiceSource>) LoadSource.list();
    

    This will return a List of Object arrays (Object[]) with scalar values for each column in the SwitcherServiceSource table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

    Solution

    List<Object> result = (List<Object>) LoadSource.list(); 
    Iterator itr = result.iterator();
    while(itr.hasNext()){
       Object[] obj = (Object[]) itr.next();
       //now you have one array of Object for each row
       String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String 
       Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
       //same way for all obj[2], obj[3], obj[4]
    }
    

    Related link

    Shell equality operators (=, ==, -eq)

    It's the other way around: = and == are for string comparisons, -eq is for numeric ones. -eq is in the same family as -lt, -le, -gt, -ge, and -ne, if that helps you remember which is which.

    == is a bash-ism, by the way. It's better to use the POSIX =. In bash the two are equivalent, and in plain sh = is the only one guaranteed to work.

    $ a=foo
    $ [ "$a" = foo ]; echo "$?"       # POSIX sh
    0
    $ [ "$a" == foo ]; echo "$?"      # bash specific
    0
    $ [ "$a" -eq foo ]; echo "$?"     # wrong
    -bash: [: foo: integer expression expected
    2
    

    (Side note: Quote those variable expansions! Do not leave out the double quotes above.)

    If you're writing a #!/bin/bash script then I recommend using [[ instead. The doubled form has more features, more natural syntax, and fewer gotchas that will trip you up. Double quotes are no longer required around $a, for one:

    $ [[ $a == foo ]]; echo "$?"      # bash specific
    0
    

    See also:

    how to use json file in html code

    You can use JavaScript like... Just give the proper path of your json file...

    <!doctype html>
    <html>
        <head>
            <script type="text/javascript" src="abc.json"></script>
            <script type="text/javascript" >
                function load() {
                    var mydata = JSON.parse(data);
                    alert(mydata.length);
    
                    var div = document.getElementById('data');
    
                    for(var i = 0;i < mydata.length; i++)
                    {
                        div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                    }
                }
            </script>
        </head>
        <body onload="load()">
            <div id="data">
    
            </div>
        </body>
    </html>
    

    Simply getting the data and appending it to a div... Initially printing the length in alert.

    Here is my Json file: abc.json

    data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
    

    How to read and write INI file with Python3?

    There are some problems I found when used configparser such as - I got an error when I tryed to get value from param:

    destination=\my-server\backup$%USERNAME%

    It was because parser can't get this value with special character '%'. And then I wrote a parser for reading ini files based on 're' module:

    import re
    
    # read from ini file.
    def ini_read(ini_file, key):
        value = None
        with open(ini_file, 'r') as f:
            for line in f:
                match = re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I)
                if match:
                    value = match.group()
                    value = re.sub(r'^ *' + key + ' *= *', '', value)
                    break
        return value
    
    
    # read value for a key 'destination' from 'c:/myconfig.ini'
    my_value_1 = ini_read('c:/myconfig.ini', 'destination')
    
    # read value for a key 'create_destination_folder' from 'c:/myconfig.ini'
    my_value_2 = ini_read('c:/myconfig.ini', 'create_destination_folder')
    
    
    # write to an ini file.
    def ini_write(ini_file, key, value, add_new=False):
        line_number = 0
        match_found = False
        with open(ini_file, 'r') as f:
            lines = f.read().splitlines()
        for line in lines:
            if re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I):
                match_found = True
                break
            line_number += 1
        if match_found:
            lines[line_number] = key + ' = ' + value
            with open(ini_file, 'w') as f:
                for line in lines:
                    f.write(line + '\n')
            return True
        elif add_new:
            with open(ini_file, 'a') as f:
                f.write(key + ' = ' + value)
            return True
        return False
    
    
    # change a value for a key 'destination'.
    ini_write('my_config.ini', 'destination', '//server/backups$/%USERNAME%')
    
    # change a value for a key 'create_destination_folder'
    ini_write('my_config.ini', 'create_destination_folder', 'True')
    
    # to add a new key, we need to use 'add_new=True' option.
    ini_write('my_config.ini', 'extra_new_param', 'True', True)
    

    Searching a list of objects in Python

    Another way you could do it is using the next() function.

    matched_obj = next(x for x in list if x.n == 10)
    

    How to get just the parent directory name of a specific file

    Use below,

    File file = new File("file/path");
    String parentPath = file.getAbsoluteFile().getParent();
    

    AngularJS + JQuery : How to get dynamic content working in angularjs

    You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

    In your fiddle, it would look something like this.

    $("#dynamicContent").html(
      $compile(
        "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
      )(scope)
    );
    

    Obviously, $compile must be injected into your controller for this to work.

    Read more in the $compile documentation.

    How do I return clean JSON from a WCF Service?

    When you are using GET Method the contract must be this.

    [WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    List<User> Get();
    

    with this we have a json without the boot parameter

    Aldo Flores @alduar http://alduar.blogspot.com

    download file using an ajax request

    This solution is not very different from those above, but for me it works very well and i think it's clean.

    I suggest to base64 encode the file server side (base64_encode(), if you are using PHP) and send the base64 encoded data to the client

    On the client you do this:

     let blob = this.dataURItoBlob(THE_MIME_TYPE + "," + response.file);
     let uri = URL.createObjectURL(blob);
     let link = document.createElement("a");
     link.download = THE_FILE_NAME,
     link.href = uri;
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
    

    This code puts the encoded data in a link and simulates a click on the link, then it removes it.

    How do I get whole and fractional parts from double in JSP/Java?

    What if your number is 2.39999999999999. I suppose you want to get the exact decimal value. Then use BigDecimal:

    Integer x,y,intPart;
    BigDecimal bd,bdInt,bdDec;
    bd = new BigDecimal("2.39999999999999");
    intPart = bd.intValue();
    bdInt = new BigDecimal(intPart);
    bdDec = bd.subtract(bdInt);
    System.out.println("Number : " + bd);
    System.out.println("Whole number part : " + bdInt);
    System.out.println("Decimal number part : " + bdDec);
    

    How do I center list items inside a UL element?

    A more modern way is to use flexbox:

    _x000D_
    _x000D_
    ul{_x000D_
      list-style-type:none;_x000D_
      display:flex;_x000D_
      justify-content: center;_x000D_
    _x000D_
    }_x000D_
    ul li{_x000D_
      display: list-item;_x000D_
      background: black;_x000D_
      padding: 5px 10px;_x000D_
      color:white;_x000D_
      margin: 0 3px;_x000D_
    }_x000D_
    div{_x000D_
      background: wheat;_x000D_
    }
    _x000D_
    <div>_x000D_
    <ul>_x000D_
      <li>One</li>_x000D_
      <li>Two</li>_x000D_
      <li>Three</li>_x000D_
    </ul>  _x000D_
    _x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Safely casting long to int in Java

    A new method has been added with Java 8 to do just that.

    import static java.lang.Math.toIntExact;
    
    long foo = 10L;
    int bar = toIntExact(foo);
    

    Will throw an ArithmeticException in case of overflow.

    See: Math.toIntExact(long)

    Several other overflow safe methods have been added to Java 8. They end with exact.

    Examples:

    • Math.incrementExact(long)
    • Math.subtractExact(long, long)
    • Math.decrementExact(long)
    • Math.negateExact(long),
    • Math.subtractExact(int, int)

    How to pretty-print a numpy.array without scientific notation and with given precision?

    Unutbu gave a really complete answer (they got a +1 from me too), but here is a lo-tech alternative:

    >>> x=np.random.randn(5)
    >>> x
    array([ 0.25276524,  2.28334499, -1.88221637,  0.69949927,  1.0285625 ])
    >>> ['{:.2f}'.format(i) for i in x]
    ['0.25', '2.28', '-1.88', '0.70', '1.03']
    

    As a function (using the format() syntax for formatting):

    def ndprint(a, format_string ='{0:.2f}'):
        print [format_string.format(v,i) for i,v in enumerate(a)]
    

    Usage:

    >>> ndprint(x)
    ['0.25', '2.28', '-1.88', '0.70', '1.03']
    
    >>> ndprint(x, '{:10.4e}')
    ['2.5277e-01', '2.2833e+00', '-1.8822e+00', '6.9950e-01', '1.0286e+00']
    
    >>> ndprint(x, '{:.8g}')
    ['0.25276524', '2.283345', '-1.8822164', '0.69949927', '1.0285625']
    

    The index of the array is accessible in the format string:

    >>> ndprint(x, 'Element[{1:d}]={0:.2f}')
    ['Element[0]=0.25', 'Element[1]=2.28', 'Element[2]=-1.88', 'Element[3]=0.70', 'Element[4]=1.03']
    

    Get selected option text with JavaScript

     <select class="cS" onChange="fSel2(this.value);">
         <option value="0">S?lectionner</option>
         <option value="1">Un</option>
         <option value="2" selected>Deux</option>
         <option value="3">Trois</option>
     </select>
    
     <select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
         <option value="0">S?lectionner</option>
         <option value="1">Un</option>
         <option value="2" selected>Deux</option>
         <option value="3">Trois</option>
     </select><br>
    
     <select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
         <option value="0">S?lectionner</option>
         <option value="1">Un</option>
         <option value="2" selected>Deux</option>
         <option value="3">Trois</option>
     </select>
    
     <select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
         <option value="0">S?lectionner</option>
         <option value="1">Un</option>
         <option value="2" selected>Deux</option>
         <option value="3">Trois</option>
     </select>
    
     <select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
         <option value="0">S?lectionner</option>
         <option value="1">Un</option>
         <option value="2" selected>Deux</option>
         <option value="3">Trois</option>
     </select>
    
     <select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
         <option value="0">S?lectionner</option>
         <option value="1">Un</option>
         <option value="2" selected>Deux</option>
         <option value="3">Trois</option>
     </select>
    
     <script type="text/javascript"> "use strict";
       const s=document.querySelector(".cS");
    
     // options[this.selectedIndex].value
     let fSel = (sIdx) => console.log(sIdx,
         s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);
    
     let fSel2= (sIdx) => { // this.value
         console.log(sIdx, s.options[sIdx].text,
             s.options[sIdx].textContent, s.options[sIdx].label);
     }
    
     // options[this.selectedIndex].text
     // options[this.selectedIndex].textContent
     // options[this.selectedIndex].label
     // options[this.selectedIndex].innerHTML
     let fSel3= (sIdx) => {
         console.log(sIdx);
     }
     </script> // fSel
    

    But :

     <script type="text/javascript"> "use strict";
        const x=document.querySelector(".cS"),
              o=x.options, i=x.selectedIndex;
        console.log(o[i].value,
                    o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
     </script> // .cS"
    

    And also this :

     <select id="iSel" size="3">
         <option value="one">Un</option>
         <option value="two">Deux</option>
         <option value="three">Trois</option>
     </select>
    
    
     <script type="text/javascript"> "use strict";
        const i=document.getElementById("iSel");
        for(let k=0;k<i.length;k++) {
            if(k == i.selectedIndex) console.log("Selected ".repeat(3));
            console.log(`${Object.entries(i.options)[k][1].value}`+
                        ` => ` +
                        `${Object.entries(i.options)[k][1].innerHTML}`);
            console.log(Object.values(i.options)[k].value ,
                        " => ",
                        Object.values(i.options)[k].innerHTML);
            console.log("=".repeat(25));
        }
     </script>
    

    When should I use double or single quotes in JavaScript?

    Just keep consistency in what you use. But don't let down your comfort level.

    "This is my string."; // :-|
    "I'm invincible."; // Comfortable :)
    'You can\'t beat me.'; // Uncomfortable :(
    'Oh! Yes. I can "beat" you.'; // Comfortable :)
    "Do you really think, you can \"beat\" me?"; // Uncomfortable :(
    "You're my guest. I can \"beat\" you."; // Sometimes, you've to :P
    'You\'re my guest too. I can "beat" you too.'; // Sometimes, you've to :P
    

    ECMAScript 6 update

    Using template literal syntax.

    `Be "my" guest. You're in complete freedom.`; // Most comfort :D
    

    How to delete a module in Android Studio

    In Android studio v1.0.2

    Method 1

    Go to project structure, File -> Project Structure..., as the following picture show, click - icon to remove the module.enter image description here

    Method 2

    Edit the file settings.gradle and remove the entry you are going to delete. e.g. edit the file from include ':app', ':apple' to include ':app'.

    That will work in most of the situation, however finally you have to delete the module from disk manually if you don't need it anymore.

    Check whether a path is valid in Python without creating a file at the path's target

    open(filename,'r')   #2nd argument is r and not w
    

    will open the file or give an error if it doesn't exist. If there's an error, then you can try to write to the path, if you can't then you get a second error

    try:
        open(filename,'r')
        return True
    except IOError:
        try:
            open(filename, 'w')
            return True
        except IOError:
            return False
    

    Also have a look here about permissions on windows

    Trying to mock datetime.date.today(), but not working

    I made this work by importing datetime as realdatetime and replacing the methods I needed in the mock with the real methods:

    import datetime as realdatetime
    
    @mock.patch('datetime')
    def test_method(self, mock_datetime):
        mock_datetime.today = realdatetime.today
        mock_datetime.now.return_value = realdatetime.datetime(2019, 8, 23, 14, 34, 8, 0)
    

    Jenkins - passing variables between jobs?

    You can use Hudson Groovy builder to do this.

    First Job in pipeline

    enter image description here

    Second job in pipeline

    enter image description here

    How to get base64 encoded data from html image

    You can try following sample http://jsfiddle.net/xKJB8/3/

    <img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
    <canvas id="myCanvas" />
    

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("preview");
    ctx.drawImage(img, 10, 10);
    alert(c.toDataURL());
    

    How to make a JFrame Modal in Swing java

    1. Create a new JPanel form
    2. Add your desired components and code to it

    YourJPanelForm stuff = new YourJPanelForm();
    JOptionPane.showMessageDialog(null,stuff,"Your title here bro",JOptionPane.PLAIN_MESSAGE);
    


    Your modal dialog awaits...

    How to make/get a multi size .ico file?

    I found an app for Mac OSX called ICOBundle that allows you to easily drop a selection of ico files in different sizes onto the ICOBundle.app, prompts you for a folder destination and file name, and it creates the multi-icon .ico file.

    Now if it were only possible to mix-in an animated gif version into that one file it'd be a complete icon set, sadly not possible and requires a separate file and code snippet.

    How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

    Here I am using iTextSharp dll for generating PDF file. I want to open PDF file instead of downloading it. So I am using below code which is working fine for me. Now pdf file is opening in browser ,now dowloading

            Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
            PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            Paragraph Text = new Paragraph("Hi , This is Test Content");
            pdfDoc.Add(Text);
            pdfWriter.CloseStream = false;
            pdfDoc.Close();
            Response.Buffer = true;
            Response.ContentType = "application/pdf";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.End();
    

    If you want to download file, add below line, after this Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");   
    

    One liner to check if element is in the list

    If he really wants a one liner without any collections, OK, he can have one:

    for(String s:new String[]{"a", "b", "c")) if (s.equals("a")) System.out.println("It's there");
    

    *smile*

    (Isn't it ugly? Please, don't use it in real code)

    session handling in jquery

    In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

    Consider using sessionStorage directly: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

    How to push objects in AngularJS between ngRepeat arrays

    Try this one also...

    _x000D_
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    _x000D_
    <body>_x000D_
    _x000D_
      <p>Click the button to join two arrays.</p>_x000D_
    _x000D_
      <button onclick="myFunction()">Try it</button>_x000D_
    _x000D_
      <p id="demo"></p>_x000D_
      <p id="demo1"></p>_x000D_
      <script>_x000D_
        function myFunction() {_x000D_
          var hege = [{_x000D_
            1: "Cecilie",_x000D_
            2: "Lone"_x000D_
          }];_x000D_
          var stale = [{_x000D_
            1: "Emil",_x000D_
            2: "Tobias"_x000D_
          }];_x000D_
          var hege = hege.concat(stale);_x000D_
          document.getElementById("demo1").innerHTML = hege;_x000D_
          document.getElementById("demo").innerHTML = stale;_x000D_
        }_x000D_
      </script>_x000D_
    _x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Is there any way to specify a suggested filename when using data: URI?

    I've looked a bit in firefox sources in netwerk/protocol/data/nsDataHandler.cpp

    data handler only parses content/type and charset, and looks if there is ";base64" in the string

    the rfc specifices no filename and at least firefox handles no filename for it, the code generates a random name plus ".part"

    I've also checked firefox log

    [b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=
    [b2e140]: Found extension '' (filename is '', handling attachment: 0)
    [b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''
    [b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''
    [b2e140]: Extension lookup on '' found: 0x0
    [b2e140]: Ext. lookup for '' found 0x0
    [b2e140]: OS gave back 0x43609a0 - found: 0
    [b2e140]: Searched extras (by type), rv 0x80004005
    [b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''
    [b2e140]: Type/Ext lookup found 0x43609a0
    

    interesting files if you want to look at mozilla sources:

    data uri handler: netwerk/protocol/data/nsDataHandler.cpp
    where mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp
    InternalLoad string in the log: docshell/base/nsDocShell.cpp
    

    I think you can stop searching a solution for now, because I suspect there is none :)

    as noticed in this thread html5 has download attribute, it works also on firefox 20 http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download

    Using GSON to parse a JSON array

    public static <T> List<T> toList(String json, Class<T> clazz) {
        if (null == json) {
            return null;
        }
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<T>(){}.getType());
    }
    

    sample call:

    List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
    

    How can I bind a background color in WPF/XAML?

    You assigned a string "Red". Your Background property should be of type Color:

    using System.Windows;
    using System.ComponentModel;
    
    namespace TestBackground88238
    {
        public partial class Window1 : Window, INotifyPropertyChanged
        {
    
            #region ViewModelProperty: Background
            private Color _background;
            public Color Background
            {
                get
                {
                    return _background;
                }
    
                set
                {
                    _background = value;
                    OnPropertyChanged("Background");
                }
            }
            #endregion
    
            //...//
    }
    

    Then you can use the binding to the SolidColorBrush like this:

    public Window1()
    {
        InitializeComponent();
        DataContext = this;
    
        Background = Colors.Red;
        Message = "This is the title, the background should be " + Background.toString() + ".";
    
    }
    

    not 100% sure about the .toString() method on Color-Object. It might tell you it is a Color-Class, but you will figur this out ;)

    Java - Find shortest path between 2 points in a distance weighted map

    Estimated sanjan:

    The idea behind Dijkstra's Algorithm is to explore all the nodes of the graph in an ordered way. The algorithm stores a priority queue where the nodes are ordered according to the cost from the start, and in each iteration of the algorithm the following operations are performed:

    1. Extract from the queue the node with the lowest cost from the start, N
    2. Obtain its neighbors (N') and their associated cost, which is cost(N) + cost(N, N')
    3. Insert in queue the neighbor nodes N', with the priority given by their cost

    It's true that the algorithm calculates the cost of the path between the start (A in your case) and all the rest of the nodes, but you can stop the exploration of the algorithm when it reaches the goal (Z in your example). At this point you know the cost between A and Z, and the path connecting them.

    I recommend you to use a library which implements this algorithm instead of coding your own. In Java, you might take a look to the Hipster library, which has a very friendly way to generate the graph and start using the search algorithms.

    Here you have an example of how to define the graph and start using Dijstra with Hipster.

    // Create a simple weighted directed graph with Hipster where
    // vertices are Strings and edge values are just doubles
    HipsterDirectedGraph<String,Double> graph = GraphBuilder.create()
      .connect("A").to("B").withEdge(4d)
      .connect("A").to("C").withEdge(2d)
      .connect("B").to("C").withEdge(5d)
      .connect("B").to("D").withEdge(10d)
      .connect("C").to("E").withEdge(3d)
      .connect("D").to("F").withEdge(11d)
      .connect("E").to("D").withEdge(4d)
      .buildDirectedGraph();
    
    // Create the search problem. For graph problems, just use
    // the GraphSearchProblem util class to generate the problem with ease.
    SearchProblem p = GraphSearchProblem
      .startingFrom("A")
      .in(graph)
      .takeCostsFromEdges()
      .build();
    
    // Search the shortest path from "A" to "F"
    System.out.println(Hipster.createDijkstra(p).search("F"));
    

    You only have to substitute the definition of the graph for your own, and then instantiate the algorithm as in the example.

    I hope this helps!

    nodemon not working: -bash: nodemon: command not found

    I ran into the same problem since I had changed my global path of npm packages before.

    Here's how I fixed it :

    When I installed nodemon using : npm install nodemon -g --save , my path for the global npm packages was not present in the PATH variable .

    If you just add it to the $PATH variable it will get fixed.

    Edit the ~/.bashrc file in your home folder and add this line :-

    export PATH=$PATH:~/npm
    

    Here "npm" is the path to my global npm packages . Replace it with the global path in your system

    PHP error: "The zip extension and unzip command are both missing, skipping."

    Actually composer nowadays seems to work without the zip command line command, so installing php-zip should be enough --- BUT it would display a warning:

    As there is no 'unzip' command installed zip files are being unpacked using the PHP zip extension. This may cause invalid reports of corrupted archives. Installing 'unzip' may remediate them.

    See also Is there a problem with using php-zip (composer warns about it)

    Converting byte array to String (Java)

    I suggest Arrays.toString(byte_array);

    It depends on your purpose. For example, I wanted to save a byte array exactly like the format you can see at time of debug that is something like this : [1, 2, 3] If you want to save exactly same value without converting the bytes to character format, Arrays.toString (byte_array) does this,. But if you want to save characters instead of bytes, you should use String s = new String(byte_array). In this case, s is equal to equivalent of [1, 2, 3] in format of character.

    Compiling with g++ using multiple cores

    I'm not sure about g++, but if you're using GNU Make then "make -j N" (where N is the number of threads make can create) will allow make to run multple g++ jobs at the same time (so long as the files do not depend on each other).

    Private Variables and Methods in Python

    Because thats coding convention. See here for more.

    How Do I Convert an Integer to a String in Excel VBA?

    The accepted answer is good for smaller numbers, most importantly while you are taking data from excel sheets. as the bigger numbers will automatically converted to scientific numbers i.e. e+10.
    So I think this will give you more general answer. I didn't check if it have any downfall or not.

    CStr(CDbl(#yourNumber#))
    

    this will work for e+ converted numbers! as the just CStr(7.7685099559e+11) will be shown as "7.7685099559e+11" not as expected: "776850995590" So I rather to say my answer will be more generic result.

    Regards, M

    How to exclude particular class name in CSS selector?

    In modern browsers you can do:

    .reMode_hover:not(.reMode_selected):hover{}
    

    Consult http://caniuse.com/css-sel3 for compatibility information.

    How to split (chunk) a Ruby array into parts of X elements?

    If you're using rails you can also use in_groups_of:

    foo.in_groups_of(3)
    

    How to prove that a problem is NP complete?

    In order to prove that a problem L is NP-complete, we need to do the following steps:

    1. Prove your problem L belongs to NP (that is that given a solution you can verify it in polynomial time)
    2. Select a known NP-complete problem L'
    3. Describe an algorithm f that transforms L' into L
    4. Prove that your algorithm is correct (formally: x ? L' if and only if f(x) ? L )
    5. Prove that algo f runs in polynomial time

    Where is debug.keystore in Android Studio

    On Windows, if the debug.keystore file is not in the location (C:\Users\username\.android), the debug.keystore file may also be found in the location where you have installed Android Studio.

    Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

    I changed the memory limit from .htaccess and this problem got resolved.

    I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

    php_value memory_limit 512M
    

    After scan was over, I removed this line to make the size as it was before.

    Can you split/explode a field in a MySQL query?

    I just had a similar issue with a field like that which I solved a different way. My use case was needing to take those ids in a comma separated list for use in a join.

    I was able to solve it using a like, but it was made easier because in addition to the comma delimiter the ids were also quoted like so:

    keys "1","2","6","12"

    Because of that, I was able to do a LIKE

    SELECT twwf.id, jtwi.id joined_id FROM table_with_weird_field twwf INNER JOIN join_table_with_ids jtwi ON twwf.delimited_field LIKE CONCAT("%\"", jtwi.id, "\"%")

    This basically just looks to see if the id from the table you're trying to join appears in the set and at that point you can join on it easily enough and return your records. You could also just create a view from something like this.

    It worked well for my use case where I was dealing with a Wordpress plugin that managed relations in the way described. The quotes really help though because otherwise you run the risk of partial matches (aka - id 1 within 18, etc).

    Test if characters are in a string

    Use this function from stringi package:

    > stri_detect_fixed("test",c("et","es"))
    [1] FALSE  TRUE
    

    Some benchmarks:

    library(stringi)
    set.seed(123L)
    value <- stri_rand_strings(10000, ceiling(runif(10000, 1, 100))) # 10000 random ASCII strings
    head(value)
    
    chars <- "es"
    library(microbenchmark)
    microbenchmark(
       grepl(chars, value),
       grepl(chars, value, fixed=TRUE),
       grepl(chars, value, perl=TRUE),
       stri_detect_fixed(value, chars),
       stri_detect_regex(value, chars)
    )
    ## Unit: milliseconds
    ##                               expr       min        lq    median        uq       max neval
    ##                grepl(chars, value) 13.682876 13.943184 14.057991 14.295423 15.443530   100
    ##  grepl(chars, value, fixed = TRUE)  5.071617  5.110779  5.281498  5.523421 45.243791   100
    ##   grepl(chars, value, perl = TRUE)  1.835558  1.873280  1.956974  2.259203  3.506741   100
    ##    stri_detect_fixed(value, chars)  1.191403  1.233287  1.309720  1.510677  2.821284   100
    ##    stri_detect_regex(value, chars)  6.043537  6.154198  6.273506  6.447714  7.884380   100
    

    How to use Select2 with JSON via Ajax request?

    This is how I fixed my issue, I am getting data in data variable and by using above solutions I was getting error could not load results. I had to parse the results differently in processResults.

    searchBar.select2({
                ajax: {
                    url: "/search/live/results/",
                    dataType: 'json',
                    headers : {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    delay: 250,
                    type: 'GET',
                    data: function (params) {
                        return {
                            q: params.term, // search term
                        };
                    },
                    processResults: function (data) {
                        var arr = []
                        $.each(data, function (index, value) {
                            arr.push({
                                id: index,
                                text: value
                            })
                        })
                        return {
                            results: arr
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; },
                minimumInputLength: 1
            });
    

    Is it possible to declare a public variable in vba and assign a default value?

    You can define the variable in General Declarations and then initialise it in the first event that fires in your environment.

    Alternatively, you could create yourself a class with the relevant properties and initialise them in the Initialise method

    OpenCV - Saving images to a particular folder of choice

    Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.

    Not working in Ubuntu and working in Windows

      import cv2
      img = cv2.imread('1.jpg', 1)
      path = '/tmp'
      cv2.imwrite(str(path) + 'waka.jpg',img)
      cv2.waitKey(0)
    

    I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.

    Example:

     import os
     final_path = os.path.join(path_1,path_2,path_3......)
    

    working in Ubuntu and Windows

     import cv2
     import os
     img = cv2.imread('1.jpg', 1)
     path = 'D:/OpenCV/Scripts/Images'
     cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
     cv2.waitKey(0)
    

    that code works fine on both Windows and Ubuntu :)

    Refresh Page and Keep Scroll Position

    If you don't want to use local storage then you could attach the y position of the page to the url and grab it with js on load and set the page offset to the get param you passed in, i.e.:

    //code to refresh the page
    var page_y = $( document ).scrollTop();
    window.location.href = window.location.href + '?page_y=' + page_y;
    
    
    //code to handle setting page offset on load
    $(function() {
        if ( window.location.href.indexOf( 'page_y' ) != -1 ) {
            //gets the number from end of url
            var match = window.location.href.split('?')[1].match( /\d+$/ );
            var page_y = match[0];
    
            //sets the page offset 
            $( 'html, body' ).scrollTop( page_y );
        }
    });
    

    Python function global variables?

    You must use the global declaration when you wish to alter the value assigned to a global variable.

    You do not need it to read from a global variable. Note that calling a method on an object (even if it alters the data within that object) does not alter the value of the variable holding that object (absent reflective magic).

    Changing route doesn't scroll to top in the new page

    I have finally gotten what I needed.

    I needed to scroll to the top, but wanted some transitions not to

    You can control this on a route-by-route level.
    I'm combining the above solution by @wkonkel and adding a simple noScroll: true parameter to some route declarations. Then I'm catching that in the transition.

    All in all: This floats to the top of the page on new transitions, it doesn't float to the top on Forward / Back transitions, and it allows you to override this behavior if necessary.

    The code: (previous solution plus an extra noScroll option)

      // hack to scroll to top when navigating to new URLS but not back/forward
      let wrap = function(method) {
        let orig = $window.window.history[method];
        $window.window.history[method] = function() {
          let retval = orig.apply(this, Array.prototype.slice.call(arguments));
          if($state.current && $state.current.noScroll) {
            return retval;
          }
          $anchorScroll();
          return retval;
        };
      };
      wrap('pushState');
      wrap('replaceState');
    

    Put that in your app.run block and inject $state... myApp.run(function($state){...})

    Then, If you don't want to scroll to the top of the page, create a route like this:

    .state('someState', {
      parent: 'someParent',
      url: 'someUrl',
      noScroll : true // Notice this parameter here!
    })
    

    Get HTML code using JavaScript with a URL

    You can use fetch to do that:

    fetch('some_url')
        .then(function (response) {
            switch (response.status) {
                // status "OK"
                case 200:
                    return response.text();
                // status "Not Found"
                case 404:
                    throw response;
            }
        })
        .then(function (template) {
            console.log(template);
        })
        .catch(function (response) {
            // "Not Found"
            console.log(response.statusText);
        });
    

    Asynchronous with arrow function version:

    (async () => {
        var response = await fetch('some_url');
        switch (response.status) {
            // status "OK"
            case 200:
                var template = await response.text();
    
                console.log(template);
                break;
            // status "Not Found"
            case 404:
                console.log('Not Found');
                break;
        }
    })();
    

    How to access command line arguments of the caller inside a function?

    My reading of the Bash Reference Manual says this stuff is captured in BASH_ARGV, although it talks about "the stack" a lot.

    #!/bin/bash
    
    function argv {
        for a in ${BASH_ARGV[*]} ; do
          echo -n "$a "
        done
        echo
    }
    
    function f {
        echo f $1 $2 $3
        echo -n f ; argv
    }
    
    function g {
        echo g $1 $2 $3
        echo -n g; argv
        f
    }
    
    f boo bar baz
    g goo gar gaz
    

    Save in f.sh

    $ ./f.sh arg0 arg1 arg2
    f boo bar baz
    farg2 arg1 arg0 
    g goo gar gaz
    garg2 arg1 arg0 
    f
    farg2 arg1 arg0 
    

    javascript regular expression to check for IP addresses

    Try this one.. Source from here.

    "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"