Programs & Examples On #Linkify

An Android utility class with which you can easily link to for example webpages, phone numbers or e-mail adresses.

select unique rows based on single distinct column

Quick one in TSQL

SELECT a.*
FROM emails a
INNER JOIN 
  (SELECT email,
    MIN(id) as id
  FROM emails 
  GROUP BY email 
) AS b
  ON a.email = b.email 
  AND a.id = b.id;

What is the optimal algorithm for the game 2048?

I wrote a 2048 solver in Haskell, mainly because I'm learning this language right now.

My implementation of the game slightly differs from the actual game, in that a new tile is always a '2' (rather than 90% 2 and 10% 4). And that the new tile is not random, but always the first available one from the top left. This variant is also known as Det 2048.

As a consequence, this solver is deterministic.

I used an exhaustive algorithm that favours empty tiles. It performs pretty quickly for depth 1-4, but on depth 5 it gets rather slow at a around 1 second per move.

Below is the code implementing the solving algorithm. The grid is represented as a 16-length array of Integers. And scoring is done simply by counting the number of empty squares.

bestMove :: Int -> [Int] -> Int
bestMove depth grid = maxTuple [ (gridValue depth (takeTurn x grid), x) | x <- [0..3], takeTurn x grid /= [] ]

gridValue :: Int -> [Int] -> Int
gridValue _ [] = -1
gridValue 0 grid = length $ filter (==0) grid  -- <= SCORING
gridValue depth grid = maxInList [ gridValue (depth-1) (takeTurn x grid) | x <- [0..3] ]

I thinks it's quite successful for its simplicity. The result it reaches when starting with an empty grid and solving at depth 5 is:

Move 4006
[2,64,16,4]
[16,4096,128,512]
[2048,64,1024,16]
[2,4,16,2]

Game Over

Source code can be found here: https://github.com/popovitsj/2048-haskell

How to prettyprint a JSON file?

Here's a simple example of pretty printing JSON to the console in a nice way in Python, without requiring the JSON to be on your computer as a local file:

import pprint
import json 
from urllib.request import urlopen # (Only used to get this example)

# Getting a JSON example for this example 
r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
text = r.read() 

# To print it
pprint.pprint(json.loads(text))

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

openCV video saving in python

This is an answer was only tested in MacOS but it will probably also work in Linux and Windows.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Get the Default resolutions
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

# Define the codec and filename.
out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:

        # write the  frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

Run Java Code Online

Compilr is an online java compiler. It provides syntax highlighting and reports any errors back to you. It's a project I'm working on, so if you have any feedback please leave a comment!

regular expression for finding 'href' value of a <a> link

I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href attribute of each links. It will match whether double or single quotes are used.

<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1

You can view a full explanation of this regex at here.

Snippet playground:

_x000D_
_x000D_
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
  console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
  Text to match:_x000D_
  <input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
  _x000D_
  <button>Match</button>_x000D_
 </label>
_x000D_
_x000D_
_x000D_

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

How to get the query string by javascript?

If you're referring to the URL in the address bar, then

window.location.search

will give you just the query string part. Note that this includes the question mark at the beginning.

If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

url.substring(url.indexOf("?"))

That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

ORA-28000: the account is locked error getting frequently

Here other solution to only unlock the blocked user. From your command prompt log as SYSDBA:

sqlplus "/ as sysdba"

Then type the following command:

alter user <your_username> account unlock;

How to let PHP to create subdomain automatically for each user?

In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.

Using .text() to retrieve only text not nested in child tags

I liked this reusable implementation based on the clone() method found here to get only the text inside the parent element.

Code provided for easy reference:

$("#foo")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

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

POSIX defines a function: wait(NULL);. It's the shorthand for waitpid(-1, NULL, 0);, which will suspends the execution of the calling process until any one child process exits. Here, 1st argument of waitpid indicates wait for any child process to end.

In your case, have the parent call it from within your else branch.

Installing python module within code

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

How to use MapView in android using google map V2?

I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

You can find complete project here: github-link

MainActivity.kt

class MainActivity : AppCompatActivity() {

val position = LatLng(-33.920455, 18.466941)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    with(mapView) {
        // Initialise the MapView
        onCreate(null)
        // Set the map ready callback to receive the GoogleMap object
        getMapAsync{
            MapsInitializer.initialize(applicationContext)
            setMapLocation(it)
        }
    }
}

private fun setMapLocation(map : GoogleMap) {
    with(map) {
        moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
        addMarker(MarkerOptions().position(position))
        mapType = GoogleMap.MAP_TYPE_NORMAL
        setOnMapClickListener {
            Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
        }
    }
}

override fun onResume() {
    super.onResume()
    mapView.onResume()
}

override fun onPause() {
    super.onPause()
    mapView.onPause()
}

override fun onDestroy() {
    super.onDestroy()
    mapView.onDestroy()
}

override fun onLowMemory() {
    super.onLowMemory()
    mapView.onLowMemory()
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="API_KEY_HERE" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.google.android.gms.maps.MapView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/mapView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

ImportError: No module named google.protobuf

I also have this issue and have been looking into it for a long time. It seems that there is no such problem on python 3+. The problem is actually on google.protobuf

Solution 1:

pip uninstall protobuf
pip uninstall google
pip install google
pip install protobuf
pip install google-cloud

Solution 2:

create an __init__.py in "google" folder.

cd /path/to/your/env/lib/python2.7/site-packages/google
touch __init__.py

Hopefully it will work.

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

How to convert int to char with leading zeros?

You can also use FORMAT() function introduced in SQL Server 2012. http://technet.microsoft.com/library/hh213505.aspx

DECLARE @number1 INT, @number2 INT

SET @number1 = 1
SET @number2 = 867

SELECT FORMAT(@number1, 'd10')
SELECT FORMAT(@number2, 'd10')

How to convert java.lang.Object to ArrayList?

You can create a util method that converts any collection to a java list

public static List<?> convertObjectToList(Object obj) {
    List<?> list = new ArrayList<>();
    if (obj.getClass().isArray()) {
        list = Arrays.asList((Object[])obj);
    } else if (obj instanceof Collection) {
        list = new ArrayList<>((Collection<?>)obj);
    }
    return list;
}

you can also mix with this validation below:

public static boolean isCollection(Object obj) {
  return obj.getClass().isArray() || obj instanceof Collection;
}

Making button go full-width?

use

<div class="btn-group btn-group-justified">
  ...
</div>

but it only works for <a> elements and not <button> elements.

see: http://getbootstrap.com/components/#btn-groups-justified

Pretty printing XML in Python

I had some problems with minidom's pretty print. I'd get a UnicodeError whenever I tried pretty-printing a document with characters outside the given encoding, eg if I had a ß in a document and I tried doc.toprettyxml(encoding='latin-1'). Here's my workaround for it:

def toprettyxml(doc, encoding):
    """Return a pretty-printed XML document in a given encoding."""
    unistr = doc.toprettyxml().replace(u'<?xml version="1.0" ?>',
                          u'<?xml version="1.0" encoding="%s"?>' % encoding)
    return unistr.encode(encoding, 'xmlcharrefreplace')

Declare global variables in Visual Studio 2010 and VB.NET

There is no way to declare global variables as you're probably imagining them in VB.NET.

What you can do (as some of the other answers have suggested) is declare everything that you want to treat as a global variable as static variables instead within one particular class:

Public Class GlobalVariables
    Public Shared UserName As String = "Tim Johnson"
    Public Shared UserAge As Integer = 39
End Class

However, you'll need to fully-qualify all references to those variables anywhere you want to use them in your code. In this sense, they are not the type of global variables with which you may be familiar from other languages, because they are still associated with some particular class.

For example, if you want to display a message box in your form's code with the user's name, you'll have to do something like this:

Public Class Form1: Inherits Form

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        MessageBox.Show("Hello, " & GlobalVariables.UserName)
    End Sub

End Class

You can't simply access the variable by typing UserName outside of the class in which it is defined—you must also specify the name of the class in which it is defined.


If the practice of fully-qualifying your variables horrifies or upsets you for whatever reason, you can always import the class that contains your global variable declarations (here, GlobalVariables) at the top of each code file (or even at the project level, in the project's Properties window). Then, you could simply reference the variables by their name.

Imports GlobalVariables

Note that this is exactly the same thing that the compiler is doing for you behind-the-scenes when you declare your global variables in a Module, rather than a Class. In VB.NET, which offers modules for backward-compatibility purposes with previous versions of VB, a Module is simply a sealed static class (or, in VB.NET terms, Shared NotInheritable Class). The IDE allows you to call members from modules without fully-qualifying or importing a reference to them. Even if you decide to go this route, it's worth understanding what is happening behind the scenes in an object-oriented language like VB.NET. I think that as a programmer, it's important to understand what's going on and what exactly your tools are doing for you, even if you decide to use them. And for what it's worth, I do not recommend this as a "best practice" because I feel that it tends towards obscurity and clean object-oriented code/design. It's much more likely that a C# programmer will understand your code if it's written as shown above than if you cram it into a module and let the compiler handle everything.


Note that like at least one other answer has alluded to, VB.NET is a fully object-oriented language. That means, among other things, that everything is an object. Even "global" variables have to be defined within an instance of a class because they are objects as well. Any time you feel the need to use global variables in an object-oriented language, that a sign you need to rethink your design. If you're just making the switch to object-oriented programming, it's more than worth your while to stop and learn some of the basic patterns before entrenching yourself any further into writing code.

How do I center text horizontally and vertically in a TextView?

Use in the XML file.

Layout file

<TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:text="@string/stringtext"/>

or:

Use this inside the Java class

TextView textView =(TextView)findViewById(R.id.texviewid);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

Execution failed for task ':app:processDebugResources' even with latest build tools

After updating my Android SDK I stumbled upon this very problem and I tried many ways without success. What was most irritating to me when searching for a fix, were the lots of answers suggesting to change the CompileSdkVersion to a certain number while obviously this number changes with time, so here's what I did instead.

I created a new project and ran it on the emulator to make sure it's working, then checked its "\android\app\build.gradle" file and copied the numeric value of CompileSdkVersion and pasted into the same file in my other project that could not be built properly anymore. Now my problem's gone. Hope that helps.

'ssh-keygen' is not recognized as an internal or external command

I just had this issue and thought I'd share what I thought was an easier way around this.

Open git-bash and run the same command with the addition of -C since you're commenting in your email address: ssh-keygen -t rsa -C "[email protected]" command. That's it.

git-bash should have been installed when you installed git. If you can't find it you can check C:\Program Files\Git\Git Bash

The first time I did this it failed to create the .ssh folder for me so I had to open a standard Command Prompt and mkdir C:\Users\yourusername\.ssh

Passing an integer by reference in Python

In Python, everything is passed by value, but if you want to modify some state, you can change the value of an integer inside a list or object that's passed to a method.

Convert seconds to Hour:Minute:Second

Use function gmdate() only if seconds are less than 86400 (1 day) :

$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05

See: gmdate()

Run the Demo


Convert seconds to format by 'foot' no limit* :

$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05

See: floor(), sprintf(), arithmetic operators

Run the Demo


Example use of DateTime extension:

$seconds = 8525;
$zero    = new DateTime("@0");
$offset  = new DateTime("@$seconds");
$diff    = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05

See: DateTime::__construct(), DateTime::modify(), clone, sprintf()

Run the Demo


MySQL example range of the result is constrained to that of the TIME data type, which is from -838:59:59 to 838:59:59 :

SELECT SEC_TO_TIME(8525);
# 02:22:05

See: SEC_TO_TIME

Run the Demo


PostgreSQL example:

SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05

Run the Demo

Use formula in custom calculated field in Pivot Table

Some of it is possible, specifically accessing subtotals:

"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)

enter image description here

  • And make sure the field in question is a number field that can be summed, it does not work for text fields for which only count is normally informative.

Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/

How to get MAC address of client using PHP?

<?php

    ob_start();
    system('ipconfig/all');
    $mycom=ob_get_contents(); 
    ob_clean(); 
    $findme = "Physical";
    $pmac = strpos($mycom, $findme); 
    $mac=substr($mycom,($pmac+36),17);

    echo $mac;
?>

This prints the mac address of client machine

Set database timeout in Entity Framework

Try this on your context:

public class MyDatabase : DbContext
{
    public MyDatabase ()
        : base(ContextHelper.CreateConnection("Connection string"), true)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180; // seconds
    }
}

If you want to define the timeout in the connection string, use the Connection Timeout parameter like in the following connection string:

<connectionStrings>

<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />

</connectionStrings>

Source: How to: Define the Connection String

How to send authorization header with axios

res.setHeader('Access-Control-Allow-Headers',
            'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');

Blockquote : you have to add OPTIONS & Authorization to the setHeader()

this change has fixed my problem, just give a try!

How to obtain the last path segment of a URI

I'm using the following in a utility class:

public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
  throws URISyntaxException {
    return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}

public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
    return uri.toString().contains("/")
        ? (ellipsis.length == 0 ? "..." : ellipsis[0])
          + uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
        : uri.toString();
}

How to remove from a map while iterating it?

The C++20 draft contains the convenience function std::erase_if.

So you can use that function to do it as a one-liner.

std::map<K, V> map_obj;
//calls needs_removing for each element and erases it, if true was reuturned
std::erase_if(map_obj,needs_removing);
//if you need to pass only part of the key/value pair
std::erase_if(map_obj,[](auto& kv){return needs_removing(kv.first);});

Sending arrays with Intent.putExtra

This code sends array of integer values

Initialize array List

List<Integer> test = new ArrayList<Integer>();

Add values to array List

test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);

Send the array list values to target activity

intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);

here you get values on targetActivty

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");

I need to round a float to two decimal places in Java

You can make use of DecimalFormat to give you the style you wish.

DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number));  // prints 1.30E7

Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

I think groupby should work.

df.groupby(['A', 'B']).max()['C']

If you need a dataframe back you can chain the reset index call.

df.groupby(['A', 'B']).max()['C'].reset_index()

Why isn't Python very good for functional programming?

Another reason not mentioned above is that many built-in functions and methods of built-in types modify an object but do not return the modified object. If those modified objects were returned, that would make functional code cleaner and more concise. For example, if some_list.append(some_object) returned some_list with some_object appended.

Angular 2 Cannot find control with unspecified name attribute on formArrays

This was happening for me because I had fromArrayName instead of formArrayName somewhere

How to add a border just on the top side of a UIView

If I'm building from within the storyboard, I prefer add an UIView behind my useful UIView... If I want to create a border on the top of my UIView, I just increase the height of the background UIView by my border width.. The same can be done for any other side :)

C++ String Declaring

Preferred string type in C++ is string, defined in namespace std, in header <string> and you can initialize it like this for example:

#include <string>

int main()
{
   std::string str1("Some text");
   std::string str2 = "Some text";
}

More about it you can find here and here.

How to close existing connections to a DB

Short Answer:

You get "close existing connections to destination database" option only in "Databases context >> Restore Wizard" and NOT ON context of any particular database.

Long Answer:

Right Click on the Databases under your Server-Name as shown below:

and select the option: "Restore Database..." from it.

db

In the "Restore Database" wizard,

  1. select one of your databases to restore
  2. in the left vertical menu, click on "Options"

db1

Here you can find the checkbox saying, "close existing connections to destination database"

db3

Just check it, and you can proceed for the restore operation.

It automatically will resume all connections after completion of the Restore.

jQuery check/uncheck radio button onclick

DiegoP,

I was having the same trouble, until I realized that the check on the box doesnt go off until the attribute is removed. That means even if checked value is made false, it will remain there.

Hence use the removeAttr() function and remove the checked attrib and it WILL DEFINITELY WORK.

Install a Windows service using a Windows command prompt?

I must add one more point in this thread. To install/uninstall 64-bit version of assemblies one should use 64-bit version of tool. To install a service, the command should be:

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
"C:\YourFolder\YourService.exe"

and to uninstall the command should be:

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" -u
"C:\YourFolder\YourService.exe"

Required attribute on multiple checkboxes with the same name?

Here is improvement for icova's answer. It also groups inputs by name.

$(function(){
  var allRequiredCheckboxes = $(':checkbox[required]');
  var checkboxNames = [];

  for (var i = 0; i < allRequiredCheckboxes.length; ++i){
    var name = allRequiredCheckboxes[i].name;
    checkboxNames.push(name);
  }

  checkboxNames = checkboxNames.reduce(function(p, c) {
    if (p.indexOf(c) < 0) p.push(c);
    return p;
  }, []);

  for (var i in checkboxNames){
    !function(){
      var name = checkboxNames[i];
      var checkboxes = $('input[name="' + name + '"]');
      checkboxes.change(function(){
        if(checkboxes.is(':checked')) {
          checkboxes.removeAttr('required');
        } else {
          checkboxes.attr('required', 'required');
        }
      });
    }();
  }

});

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

It is not clear why running a SELECT statement should involve enabling constraints. I don't know C# or related technologies, but I do know Informix database. There is something odd going on with the system if your querying code is enabling (and presumably also disabling) constraints.

You should also avoid the old-fashioned, non-standard Informix OUTER join notation. Unless you are using an impossibly old version of Informix, you should be using the SQL-92 style of joins.

Your question seems to mention two outer joins, but you only show one in the example query. That, too, is a bit puzzling.

The joining conditions between 'e' and the rest of the tables is:

AND c.crsnum = e.crsnum  
AND c.batch_no = e.batch_no  
AND d.lect_code= e.lect_code 

This is an unusual combination. Since we do not have the relevant subset of the schema with the relevant referential integrity constraints, it is hard to know whether this is correct or not, but it is a little unusual to join between 3 tables like that.

None of this is a definitive answer to you problem; however, it may provide some guidance.

How to print an exception in Python?

In Python 2.6 or greater it's a bit cleaner:

except Exception as e: print(e)

In older versions it's still quite readable:

except Exception, e: print e

Save multiple sheets to .pdf

Similar to Tim's answer - but with a check for 2007 (where the PDF export is not installed by default):

Public Sub subCreatePDF()

    If Not IsPDFLibraryInstalled Then
        'Better show this as a userform with a proper link:
        MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041". 
        Exit Sub
    End If

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=ActiveWorkbook.Path & Application.PathSeparator & _
        ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

Private Function IsPDFLibraryInstalled() As Boolean
'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm)
    IsPDFLibraryInstalled = _
        (Dir(Environ("commonprogramfiles") & _
        "\Microsoft Shared\OFFICE" & _
        Format(Val(Application.Version), "00") & _
        "\EXP_PDF.DLL") <> "")
End Function

jQuery text() and newlines

Using the CSS white-space property is probably the best solution. Use Firebug or Chrome Developer Tools to identify the source of the extra padding you were seeing.

How to move an element into another element?

You can use:

To Insert After,

jQuery("#source").insertAfter("#destination");

To Insert inside another element,

jQuery("#source").appendTo("#destination");

AngularJS ng-style with a conditional expression

I am doing like below for multiple and independent conditions and it works like charm:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

php form action php self

How about leaving it empty, what is wrong with that?

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="">

</form>

Also, you can omit the action attribute and it will work as expected.

Generate unique random numbers between 1 and 100

The above techniques are good if you want to avoid a library, but depending if you would be alright with a library, I would suggest checking out Chance for generating random stuff in JavaScript.

Specifically to solve your question, using Chance it's as easy as:

_x000D_
_x000D_
// One line!_x000D_
var uniques = chance.unique(chance.natural, 8, {min: 1, max: 100});_x000D_
_x000D_
// Print it out to the document for this snippet so we can see it in action_x000D_
document.write(JSON.stringify(uniques));
_x000D_
<script src="http://chancejs.com/chance.min.js"></script>
_x000D_
_x000D_
_x000D_

Disclaimer, as the author of Chance, I am a bit biased ;)

String or binary data would be truncated. The statement has been terminated

SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12 introduced trace flag 460 in order to return the details of truncation warnings. You can enable it at the query level or at the server level.

Query level

INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO

Server Level

DBCC TRACEON(460, -1);
GO

From SQL Server 2019 you can enable it at database level:

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

The old output message is:

Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.

The new output message is:

Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.

In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

How do I output the results of a HiveQL query to CSV?

Just to cover more following steps after kicking off the query: INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select books from table;

In my case, the generated data under temp folder is in deflate format, and it looks like this:

$ ls
000000_0.deflate  
000001_0.deflate  
000002_0.deflate  
000003_0.deflate  
000004_0.deflate  
000005_0.deflate  
000006_0.deflate  
000007_0.deflate

Here's the command to unzip the deflate files and put everything into one csv file:

hadoop fs -text "file:///home/lvermeer/temp/*" > /home/lvermeer/result.csv

How to set div's height in css and html

<div style="height: 100px;"> </div>

OR

<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px;  }

MessageBox Buttons?

if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
         //do stuff if yess
}
else
{
         //do stuff if No
}

How to hide columns in an ASP.NET GridView with auto-generated columns?

@nCdy: index_of_cell should be replaced by an integer, corresponding to the index number of the cell that you wish to hide in the .Cells collection.

For example, suppose that your GridView presents the following columns:

CONTACT NAME | CONTACT NUMBER | CUSTOMERID | ADDRESS LINE 1 | POST CODE

And you want the CUSTOMERID column not to be displayed. Since collections indexes are 0-based, your CUSTOMERID column's index is..........? That's right, 2!! Very good. Now... guess what you should put in there, to replace 'index_of_cell'??

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

The final keyword is used to declare constants.

final int FILE_TYPE = 3;

The finally keyword is used in a try catch statement to specify a block of code to execute regardless of thrown exceptions.

try
{
  //stuff
}
catch(Exception e)
{
  //do stuff
}
finally
{
  //this is always run
}

And finally (haha), finalize im not entirely sure is a keyword, but there is a finalize() function in the Object class.

ECMAScript 6 arrow function that returns an object

You can always check this out for more custom solutions:

x => ({}[x.name] = x);

CSS: Truncate table cells, but fit as much as possible

The problem is the 'table-layout:fixed' which create evenly-spaced-fixed-width columns. But disabling this css-property will kill the text-overflow because the table will become as large as possible (and than there is noting to overflow).

I'm sorry but in this case Fred can't have his cake and eat it to.. unless the landlord gives Celldito less space to work with in the first place, Fred cannot use his..

How can I find the length of a number?

Well without converting the integer to a string you could make a funky loop:

var number = 20000;
var length = 0;
for(i = number; i > 1; ++i){
     ++length;
     i = Math.floor(i/10);
}

alert(length);?

Demo: http://jsfiddle.net/maniator/G8tQE/

How do I loop through items in a list box and then remove those item?

How about:

foreach(var s in listBox1.Items.ToArray())
{
    MessageBox.Show(s);
    //do stuff with (s);
    listBox1.Items.Remove(s);
}

The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.

Rename a file using Java

Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)

  String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
  File newFile = new File(newFilePath);

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {
    e.printStackTrace();
  }

Javascript: Call a function after specific time period

sounds like you're looking for setInterval. It's as easy as this:

function FetchData() {
  // do something
}
setInterval(FetchData, 60000);

if you only want to call something once, theres setTimeout.

Handle JSON Decode Error when nothing returned

If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//EDIT (Oct 2020):

As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Removing Java 8 JDK from Mac

If you have installed jdk8 on your Mac but now you want to remove it, just run below command "sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk"

Get Application Name/ Label via ADB Shell or Terminal

just enter the following command on command prompt after launching the app:

adb shell dumpsys window windows | find "mCurrentFocus"

if executing the command on linux terminal replace find by grep

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Try this:

To accept theirs changes: git merge --strategy-option theirs

To accept yours: git merge --strategy-option ours

The right way of setting <a href=""> when it's a local file

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

disable horizontal scroll on mobile web

Just apply width:100%; to body

Javascript code for showing yesterday's date and todays date

Get yesterday date in javascript

You have to run code and check it output

_x000D_
_x000D_
    var today = new Date();_x000D_
    var yesterday = new Date(today);_x000D_
    _x000D_
    yesterday.setDate(today.getDate() - 1);_x000D_
    console.log("Original Date : ",yesterday);_x000D_
_x000D_
    const monthNames = [_x000D_
  "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"_x000D_
];_x000D_
    var month = today.getMonth() + 1_x000D_
    yesterday = yesterday.getDate() + ' ' + monthNames[month] + ' ' + yesterday.getFullYear()_x000D_
   _x000D_
    console.log("Modify Date : ",yesterday);
_x000D_
_x000D_
_x000D_

Clear text input on click with AngularJS

In Your Controller

$scope.clearSearch = function() {
     $scope.searchAll = '';
}

How to get label of select option with jQuery?

<SELECT id="sel" onmouseover="alert(this.options[1].text);"
<option value=1>my love</option>
<option value=2>for u</option>
</SELECT>

Placing an image to the top right corner - CSS

Position the div relatively, and position the ribbon absolutely inside it. Something like:

#content {
  position:relative;
}

.ribbon {
  position:absolute;
  top:0;
  right:0;
}

Error: could not find function ... in R

This error can occur even if the name of the function is valid if some mandatory arguments are missing (i.e you did not provide enough arguments).
I got this in an Rcpp context, where I wrote a C++ function with optionnal arguments, and did not provided those arguments in R. It appeared that optionnal arguments from the C++ were seen as mandatory by R. As a result, R could not find a matching function for the correct name but an incorrect number of arguments.

Rcpp Function : SEXP RcppFunction(arg1, arg2=0) {}
R Calls :
RcppFunction(0) raises the error
RcppFunction(0, 0) does not

How to create a sub array from another array in Java?

I you are using java prior to version 1.6 use System.arraycopy() instead. Or upgrade your environment.

Where are Magento's log files located?

To create your custom log file, try this code

Mage::log('your debug message', null, 'yourlog_filename.log');

Refer this Answer

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

XAMPP - MySQL shutdown unexpectedly

In my case in which I synced my mysql data and htdocs to dropbox, I just needed to delete the conflicted files in mysql/data folder and subfolders. The conflicted files can be identified by its names, dropbox will tell you that. It has solved the problem for me.

ip address validation in python using regex

try:
    parts = ip.split('.')
    return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
except ValueError:
    return False # one of the 'parts' not convertible to integer
except (AttributeError, TypeError):
    return False # `ip` isn't even a string

How do I split an int into its digits?

cast it to a string or char[] and loop on it

Remove certain characters from a string

You can use Replace function as;

REPLACE ('Your String with cityname here', 'cityname', 'xyz')
--Results
'Your String with xyz here'

If you apply this to a table column where stringColumnName, cityName both are columns of YourTable

SELECT REPLACE(stringColumnName, cityName, '')
FROM YourTable

Or if you want to remove 'cityName' string from out put of a column then

SELECT REPLACE(stringColumnName, 'cityName', '')
FROM yourTable

EDIT: Since you have given more details now, REPLACE function is not the best method to sort your problem. Following is another way of doing it. Also @MartinSmith has given a good answer. Now you have the choice to select again.

SELECT RIGHT (O.Ort, LEN(O.Ort) - LEN(C.CityName)-1) As WithoutCityName
FROM   tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004'

How can I check whether a variable is defined in Node.js?

It sounds like you're doing property checking on an object! If you want to check a property exists (but can be values such as null or 0 in addition to truthy values), the in operator can make for some nice syntax.

var foo = { bar: 1234, baz: null };
console.log("bar in foo:", "bar" in foo); // true
console.log("baz in foo:", "baz" in foo); // true
console.log("otherProp in foo:", "otherProp" in foo) // false
console.log("__proto__ in foo:", "__proto__" in foo) // true

As you can see, the __proto__ property is going to be thrown here. This is true for all inherited properties. For further reading, I'd recommend the MDN page:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Fit background image to div

background-position-x: center;
background-position-y: center;

How can I nullify css property?

To get rid of the fixed height property you can set it to the default value:

height: auto;

Disable time in bootstrap date time picker

Initialize your datetimepicker like this

For disable time

$(document).ready(function(){
    $('#dp3').datetimepicker({
      pickTime: false
    });
});

For disable date

$(document).ready(function(){
    $('#dp3').datetimepicker({
      pickDate: false
    });
});

To disable both date and time

$(document).ready(function(){
   $("#dp3").datetimepicker('disable'); 
});

please refer following documentation if you have any doubt

http://eonasdan.github.io/bootstrap-datetimepicker/#options

MySQL: Quick breakdown of the types of joins

Full Outer join don't exist in mysql , you might need to use a combination of left and right join.

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

The syntax is:

=GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])

Sample usage:

=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
=GOOGLEFINANCE("GOOG","price",TODAY()-30,TODAY())
=GOOGLEFINANCE(A2,A3)
=117.80*Index(GOOGLEFINANCE("CURRENCY:EURGBP", "close", DATE(2014,1,1)), 2, 2)

For instance if you'd like to convert the rate on specific date, here is some more advanced example:

=IF($C2 = "GBP", "", Index(GoogleFinance(CONCATENATE("CURRENCY:", C2, "GBP"), "close", DATE(year($A2), month($A2), day($A2)), DATE(year($A2), month($A2), day($A2)+1), "DAILY"), 2))

where $A2 is your date (e.g. 01/01/2015) and C2 is your currency (e.g. EUR).

See more samples at Docs editors Help at Google.

Spring profiles and testing

public class LoginTest extends BaseTest {
    @Test
    public void exampleTest( ){ 
        // Test
    }
}

Inherits from a base test class (this example is testng rather than jUnit, but the ActiveProfiles is the same):

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }

MyActiveProfileResolver can contain any logic required to determine which profile to use:

public class MyActiveProfileResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        // This can contain any custom logic to determine which profiles to use
        return new String[] { "exampleProfile" };
    }
}

This sets the profile which is then used to resolve dependencies required by the test.

How to change font in ipython notebook

Using Jupyterthemes, one can easily change look of notebook.

pip install jupyterthemes

jt -fs 15 

By default code font size is set to 11 . Trying above will change font size. It can be reset using.

jt -r 

This will reset all jupyter theme changes to default.

jQuery: Load Modal Dialog Contents via Ajax

$(function ()    {
    $('<div>').dialog({
        modal: true,
        open: function ()
        {
            $(this).load('Sample.htm');
        },         
        height: 400,
        width: 400,
        title: 'Dynamically Loaded Page'
    });
});

http://www.devcurry.com/2010/06/load-page-dynamically-inside-jquery-ui.html

Align contents inside a div

Below are the methods which have always worked for me

  1. By using flex layout model:

Set the display of the parent div to display: flex; and the you can align the child elements inside the div using the justify-content: center; (to align the items on main axis) and align-items: center; (to align the items on cross axis).

If you have more than one child element and want to control the way they are arranged (column/rows), then you can also add flex-direction property.

Working example:

_x000D_
_x000D_
.parent {_x000D_
  align-items: center;_x000D_
  border: 1px solid black;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  height: 250px;_x000D_
  width: 250px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  border: 1px solid black;_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2. (older method) Using position, margin properties and fixed size

Working example:

_x000D_
_x000D_
.parent {_x000D_
  border: 1px solid black;_x000D_
  height: 250px;_x000D_
  position: relative;_x000D_
  width: 250px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  border: 1px solid black;_x000D_
  margin: auto;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  height: 50px;_x000D_
  position: absolute;_x000D_
  width: 50px;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to customize the background/border colors of a grouped table view cell?

Thanks for this super helpful post. In case anyone out there (like me!) wants to just have a completely empty cell background in lieu of customizing it through images/text/other content in IB and cannot figure out how the hell to get rid of the dumb border/padding/background even though you set it to clear in IB... here's the code I used that did the trick!


- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {

    static NSString *cellId = @"cellId";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellId];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"EditTableViewCell" owner:self options:nil];
        cell = cellIBOutlet;
        self.cellIBOutlet = nil;
    }

    cell.backgroundView = [[[UIView alloc] initWithFrame: CGRectZero] autorelease];
    [cell.backgroundView setNeedsDisplay];

    ... any other cell customizations ...

    return cell;
}

Hopefully that'll help someone else! Seems to work like a charm.

Why use #define instead of a variable

Most common use (other than to declare constants) is an include guard.

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Since others have covered the differences, I'll hit the uses.

TIFF is usually used by scanners. It makes huge files and is not really used in applications.

BMP is uncompressed and also makes huge files. It is also not really used in applications.

GIF used to be all over the web but has fallen out of favor since it only supports a limited number of colors and is patented.

JPG/JPEG is mainly used for anything that is photo quality, though not for text. The lossy compression used tends to mar sharp lines.

PNG isn't as small as JPEG but is lossless so it's good for images with sharp lines. It's in common use on the web now.

Personally, I usually use PNG everywhere I can. It's a good compromise between JPG and GIF.

Is there a CSS selector by class prefix?

It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):

div[class^="status-"], div[class*=" status-"]

Notice the space character in the second attribute selector. This picks up div elements whose class attribute meets either of these conditions:

  • [class^="status-"] — starts with "status-"

  • [class*=" status-"] — contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class attributes dynamically).

Naturally, this also works in jQuery, as demonstrated here.

The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"] will match the following element, which may be undesirable:

<div id='D' class='foo-class foo-status-bar bar-class'></div>

If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.

If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status- prefix its own status class instead as Gumbo suggests.

How do I send a JSON string in a POST request in Go

you can just use post to post your json.

values := map[string]string{"username": username, "password": password}

jsonValue, _ := json.Marshal(values)

resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))

Vagrant ssh authentication failure

Mac Solution:

  1. Added local ssh id_rsa key to vagrant private key

    vi /Users//.vagrant/machines/default/virtualbox/private_key

    /Users//.ssh/id_rsa

  2. copied public key /Users//.ssh/id_rsa.pub on vagrant box authorized_keys

ssh vagrant@localhost -p 2222 (password: vagrant) ls -la cd .ssh

  1. chmod 0600 ~/.ssh/authorized_keys

  2. vagrant reload

Problem resolved.

Thanks to

How to sum up elements of a C++ vector?

One more option which I did not notice in the answers is using std::reduce which is introduced in c++17.

But you may notice many compilers not supporting it (Above GCC 10 may be good). But eventually the support will come.

With std::reduce, the advantage comes when using the execution policies. Specifying execution policy is optional. When the execution policy specified is std::execution::par, the algorithm may use hardware parallel processing capabilities. The gain may be more clear when using big size vectors.

Example:

//SAMPLE
std::vector<int> vec = {2,4,6,8,10,12,14,16,18};
    
//WITHOUT EXECUTION POLICY
int sum = std::reduce(vec.begin(),vec.end());
    
//TAKING THE ADVANTAGE OF EXECUTION POLICIES
int sum2 = std::reduce(std::execution::par,vec.begin(),vec.end());
    
std::cout << "Without execution policy  " << sum << std::endl;
std::cout << "With execution policy  " << sum2 << std::endl;

You need <numeric> header for std::reduce. And '<execution>' for execution policies.

How do I comment on the Windows command line?

Sometimes, it is convenient to add a comment to a command line. For that, you can use "&REM misc comment text" or, now that I know about it, "&:: misc comment text". For example:

REM SET Token="4C6F72656D20697073756D20646F6C6F" &REM This token is for localhost
SET Token="722073697420616D65742C20636F6E73" &REM This token is for production

This makes it easy to keep track of multiple sets of values when doing exploration, tests of concept, etc. This approach works because '&' introduces a new command on the same line.

Python integer division yields float

The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.

Python maps operators like +, -, * and / to special functions, such that e.g. a + b is equivalent to

a.__add__(b)

Regarding division in Python 2, there is by default only / which maps to __div__ and the result is dependent on the input types (e.g. int, float).

Python 2.2 introduced the __future__ feature division, which changed the division semantics the following way (TL;DR of PEP 238):

  • / maps to __truediv__ which must "return a reasonable approximation of the mathematical result of the division" (quote from PEP 238)
  • // maps to __floordiv__, which should return the floored result of /

With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__ in Python's object model.

If you want to use the same code in Python 2 and Python 3 use

from __future__ import division

and stick to the PEP 238 semantics of / and //.

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

How can I import a database with MySQL from terminal?

Below command is working on ubuntu 16.04, I am not sure it is working or not other Linux platforms.

Export SQL file:

$ mysqldump -u [user_name] -p [database_name] > [database_name.sql]  

Example : mysqldump -u root -p max_development > max_development.sql

Import SQL file:

$ mysqldump -u [user_name] -p [database_name] < [file_name.sql]

Example: mysqldump -u root -p max_production < max_development.sql

Note SQL file should exist same directory

No provider for Router?

I had the error of

No provider for Router

It happens when you try to navigate in any service.ts

this.router.navigate(['/home']); like codes in services cause that error.

You should handle navigating in your components. for example: at login.component

login().subscribe(
        (res) => this.router.navigate(['/home']),
        (error: any) => this.handleError(error));

Annoying errors happens when we are newbie :)

100% width Twitter Bootstrap 3 template

For Bootstrap 3, you would need to use a custom wrapper and set its width to 100%.

.container-full {
  margin: 0 auto;
  width: 100%;
}

Here is a working example on Bootply

If you prefer not to add a custom class, you can acheive a very wide layout (not 100%) by wrapping everything inside a col-lg-12 (wide layout demo)

Update for Bootstrap 3.1

The container-fluid class has returned in Bootstrap 3.1, so this can be used to create a full width layout (no additional CSS required)..

Bootstrap 3.1 demo

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

I had the same issue. Jenkins's build was falling because of this error..after long hours troubleshooting.

Link to download ojdbc as per your requirement - https://www.oracle.com/database/technologies/maven-central-guide.html

I have downloaded in my maven/bin location and executed the below command.

mvn install:install-file -Dfile=ojdbc8-12.2.0.1.jar -DgroupId=com.oracle -DartifactId=ojdbc8 -Dversion=12.2.0.1 -Dpackaging=jar

POM.xml

<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>

Package php5 have no installation candidate (Ubuntu 16.04)

You must use prefix "php5.6-" instead of "php5-" as in ubuntu 14.04 and olders:

sudo apt-get install php5.6 php5.6-mcrypt

"starting Tomcat server 7 at localhost has encountered a prob"

Open the terminal in ubuntu (ctrl+shift+t)
sudo gedit /etc/tomcat7/server.xml

change the default port in the server.xml,from 8080 to anything like 8081,8181,8008. Then save the file .

Now the project will work nicely without any interruption.

Base64: java.lang.IllegalArgumentException: Illegal character

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);
}

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));
}

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

The output looks like:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

python dictionary sorting in descending order based on values

sort dictionary 'in_dict' by value in decreasing order

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}

VS Code - Search for text in all files in a directory

Select your folder, Press ? + ? + F Don't know about windows but this works for mac :)

100% width in React Native Flexbox

Simply add alignSelf: "stretch" to your item's stylesheet.

line1: {
    backgroundColor: '#FDD7E4',
    alignSelf: 'stretch',
    textAlign: 'center',
},

Is it possible to opt-out of dark mode on iOS 13?

You can do: add this new key UIUserInterfaceStyle to Info.plist and set its value to Light. and check alert controller appears with light mode.

UIUserInterfaceStyle Light If you are force light/dark mode in your whole application regardless of the user's settings by adding the key UIUserInterfaceStyle to your Info.plist file and setting its value to either Light or Dark.

TypeScript and field initializers

I wanted a solution that would have the following:

  • All the data objects are required and must be filled by the constructor.
  • No need to provide defaults.
  • Can use functions inside the class.

Here is the way that I do it:

export class Person {
  id!: number;
  firstName!: string;
  lastName!: string;

  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  constructor(data: OnlyData<Person>) {
    Object.assign(this, data);
  }
}

const person = new Person({ id: 5, firstName: "John", lastName: "Doe" });
person.getFullName();

All the properties in the constructor are mandatory and may not be omitted without a compiler error.

It is dependant on the OnlyData that filters out getFullName() out of the required properties and it is defined like so:

// based on : https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c
type FilterFlags<Base, Condition> = { [Key in keyof Base]: Base[Key] extends Condition ? never : Key };
type AllowedNames<Base, Condition> = FilterFlags<Base, Condition>[keyof Base];
type SubType<Base, Condition> = Pick<Base, AllowedNames<Base, Condition>>;
type OnlyData<T> = SubType<T, (_: any) => any>;

Current limitations of this way:

  • Requires TypeScript 2.8
  • Classes with getters/setters

How to insert text into the textarea at the current cursor position?

Use selectionStart/selectionEnd properties of the input element (works for <textarea> as well)

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //MOZILLA and others
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
            + myValue
            + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

Select option padding not working in chrome

Not padding but if your goal is to simply make it larger, you can increase the font-size. And using it with font-size-adjust reduces the font-size back to normal on select and not on options, so it ends up making the option larger.

Not sure if it works on all browsers, or will keep working in current.

Tested on Chrome 85 & Firefox 81.

screenshot (on Firefox)

_x000D_
_x000D_
select {
    font-size: 2em;
    font-size-adjust: 0.3;
}
_x000D_
<label>
  Select: <select>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
          </select>
</label>
_x000D_
_x000D_
_x000D_

Group by in LINQ

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key,
                           /**/car = g.Select(g=>g.car).FirstOrDefault()/**/}

Python string.join(list) on object array rather than string array

another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you'll find my answer useful.

Dynamic tabs with user-click chosen components

there is component ready to use (rc5 compatible) ng2-steps which uses Compiler to inject component to step container and service for wiring everything together (data sync)

    import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';

import { StepsService } from './ng2-steps';

@Directive({
  selector:'[ng2-step]'
})
export class StepDirective implements OnInit{

  @Input('content') content:any;
  @Input('index') index:string;
  public instance;

  constructor(
    private compiler:Compiler,
    private viewContainerRef:ViewContainerRef,
    private sds:StepsService
  ){}

  ngOnInit(){
    //Magic!
    this.compiler.compileComponentAsync(this.content).then((cmpFactory)=>{
      const injector = this.viewContainerRef.injector;
      this.viewContainerRef.createComponent(cmpFactory, 0,  injector);
    });
  }

}

How to use bootstrap-theme.css with bootstrap 3?

Bootstrap-theme.css is the additional CSS file, which is optional for you to use. It gives 3D effects on the buttons and some other elements.

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

Setting QT_PLUGIN_PATH env variable to <...>/plugins directory also worked for me.

Calculate date from week number

Personally I'd take advantage of the culture info to get the day of the week and loop down to the culture's first day of the week. I'm not sure if I'm explaining it properly, here's an example:

    public DateTime GetFirstDayOfWeek(int year, int weekNumber)
    {
        return GetFirstDayOfWeek(year, weekNumber, Application.CurrentCulture);
    }

    public DateTime GetFirstDayOfWeek(int year, int weekNumber,
        System.Globalization.CultureInfo culture)
    {
        System.Globalization.Calendar calendar = culture.Calendar;
        DateTime firstOfYear = new DateTime(year, 1, 1, calendar);
        DateTime targetDay = calendar.AddWeeks(firstOfYear, weekNumber);
        DayOfWeek firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;

        while (targetDay.DayOfWeek != firstDayOfWeek)
        {
            targetDay = targetDay.AddDays(-1);
        }

        return targetDay;
    }

Node.js fs.readdir recursive directory search

klaw and klaw-sync are worth considering for this sort of thing. These were part of node-fs-extra.

reading external sql script in python

according me, it is not possible

solution:

  1. import .sql file on mysql server

  2. after

    import mysql.connector
    import pandas as pd
    

    and then you use .sql file by convert to dataframe

Group a list of objects by an attribute

Using Java 8

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Student {

    String stud_id;
    String stud_name;
    String stud_location;

    public String getStud_id() {
        return stud_id;
    }

    public String getStud_name() {
        return stud_name;
    }

    public String getStud_location() {
        return stud_location;
    }



    Student(String sid, String sname, String slocation) {

        this.stud_id = sid;
        this.stud_name = sname;
        this.stud_location = slocation;

    }
}

class Temp
{
    public static void main(String args[])
    {

        Stream<Student> studs = 
        Stream.of(new Student("1726", "John", "New York"),
                new Student("4321", "Max", "California"),
                new Student("2234", "Max", "Los Angeles"),
                new Student("7765", "Sam", "California"));
        Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location)));
                System.out.println(map);//print by name and then location
    }

}

The result will be:

{
    Max={
        Los Angeles=[Student@214c265e], 
        California=[Student@448139f0]
    }, 
    John={
        New York=[Student@7cca494b]
    }, 
    Sam={
        California=[Student@7ba4f24f]
    }
}

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

Git error on git pull (unable to update local ref)

I had the same issue on my debian server as the disk is full. No temp file could be created as no space left on device. After cleaning some files, it worked out fine.

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

Add 10 seconds to a Date

There's a setSeconds method as well:

var t = new Date();
t.setSeconds(t.getSeconds() + 10);

For a list of the other Date functions, you should check out MDN


setSeconds will correctly handle wrap-around cases:

_x000D_
_x000D_
var d;_x000D_
d = new Date('2014-01-01 10:11:55');_x000D_
alert(d.getMinutes() + ':' + d.getSeconds()); //11:55_x000D_
d.setSeconds(d.getSeconds() + 10);_x000D_
alert(d.getMinutes() + ':0' + d.getSeconds()); //12:05
_x000D_
_x000D_
_x000D_

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

You may also get this error if you have a name clash of a view and a module. I've got the error when i distribute my view files under views folder, /views/view1.py, /views/view2.py and imported some model named table.py in view2.py which happened to be a name of a view in view1.py. So naming the view functions as v_table(request,id) helped.

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

How can I return the current action in an ASP.NET MVC view?

You can get these data from RouteData of a ViewContext

ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["action"]

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

Limiting number of displayed results when using ngRepeat

here is anaother way to limit your filter on html, for example I want to display 3 list at time than i will use limitTo:3

  <li ng-repeat="phone in phones | limitTo:3">
    <p>Phone Name: {{phone.name}}</p>
  </li>

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

How to change colour of blue highlight on select box dropdown

try this.. I know it's an old post but it might help somebody

select option:hover,
    select option:focus,
    select option:active {
        background: linear-gradient(#000000, #000000);
        background-color: #000000 !important; /* for IE */
        color: #ffed00 !important;
    }

    select option:checked {
        background: linear-gradient(#d6d6d6, #d6d6d6);
        background-color: #d6d6d6 !important; /* for IE */
        color: #000000 !important;
    }

if var == False

I think what you are looking for is the 'not' operator?

if not var

Reference page: http://www.tutorialspoint.com/python/logical_operators_example.htm

Newline in string attribute

<TextBlock Text="Stuff on line1&#x0a;Stuff on line 2"/>

You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf, then you can use &#x0d;&#x0a;

By the way, note the syntax: It's the ampersand, a pound, the letter x, then the hex value of the character you want, and then finally a semi-colon.

ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.

Why are static variables considered evil?

Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.

I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.

AngularJS toggle class using ng-class

How to use conditional in ng-class:

Solution 1:

<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>

Solution 2:

<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>

Solution 3 (angular v.1.1.4+ introduced support for ternary operator):

<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>

Plunker

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

It looks like your XML document has the root element "Group" instead of "group". You can:

  1. Change the root element on your XML to be "group"
  2. Add the annotation @XmlRootElement(name="Group") to the Group classs.

How to fix "Headers already sent" error in PHP

A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php tag, can cause this ! Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.

I have seen these things ;)

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

A workaround for CONTAINS: If you don't want to create a full text Index on the column, and performance is not one of your priorities you could use the LIKE statement which doesn't need any prior configuration:

Example: find all Products that contains the letter Q:

SELECT ID, ProductName
FROM [ProductsDB].[dbo].[Products]
WHERE [ProductsDB].[dbo].[Products].ProductName LIKE '%Q%'

Is there a way to select sibling nodes?

var childNodeArray = document.getElementById('somethingOtherThanid').childNodes;

When is null or undefined used in JavaScript?

A property, when it has no definition, is undefined. null is an object. It's type is null. undefined is not an object, its type is undefined.

This is a good article explaining the difference and also giving some examples.

null vs undefined

How to force two figures to stay on the same page in LaTeX?

If you want them both on the same page and they'll both take up basically the whole page, then the best idea is to tell LaTeX to put them both on a page of their own!

\begin{figure}[p]

It would probably be against sound typographic principles (e.g., ugly) to have two figures on a page with only a few lines of text above or below them.


By the way, the reason that [!h] works is because it's telling LaTeX to override its usual restrictions on how much space should be devoted to floats on a page with text. As implied above, there's a reason the restrictions are there. Which isn't to say they can be loosened somewhat; see the FAQ on doing that.

Adding days to a date in Python

Sometimes we need to use searching by from date & to date. If we use date__range then we need to add 1 day to to_date otherwise queryset will be empty.

Example:

from datetime import timedelta  

from_date  = parse_date(request.POST['from_date'])

to_date    = parse_date(request.POST['to_date']) + timedelta(days=1)

attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])

Get DataKey values in GridView RowCommand

foreach (GridViewRow gvr in gvMyGridView.Rows)
{
    string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}

You can use this code while doing an iteration with foreach or for any GridView event like OnRowDataBound.

Here you can input multiple values for DataKeyNames by separating with comma ,. For example, DataKeyNames="ProductID,ItemID,OrderID".

You can now access each of DataKeys by providing its index like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();

You can also use Key Name instead of its index to get the values from DataKeyNames collection like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();

Parsing PDF files (especially with tables) with PDFBox

I've had decent success with parsing text files generated by the pdftotext utility (sudo apt-get install poppler-utils).

File convertPdf() throws Exception {
    File pdf = new File("mypdf.pdf");
    String outfile = "mytxt.txt";
    String proc = "/usr/bin/pdftotext";
    ProcessBuilder pb = new ProcessBuilder(proc,"-layout",pdf.getAbsolutePath(),outfile); 
    Process p = pb.start();

    p.waitFor();

    return new File(outfile);
}

Getting a map() to return a list in Python 3.x

Using list comprehension in python and basic map function utility, one can do this also:

chi = [x for x in map(chr,[66,53,0,94])]

Skip rows during csv import pandas

Also be sure that your file is actually a CSV file. For example, if you had an .xls file, and simply changed the file extension to .csv, the file won't import and will give the error above. To check to see if this is your problem open the file in excel and it will likely say:

"The file format and extension of 'Filename.csv' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?"

To fix the file: open the file in Excel, click "Save As", Choose the file format to save as (use .cvs), then replace the existing file.

This was my problem, and fixed the error for me.

Background color in input and text fields

input[type="text"], textarea {

  background-color : #d1d1d1; 

}

Hope that helps :)

Edit: working example, http://jsfiddle.net/C5WxK/

Display number with leading zeros

Use a format string - http://docs.python.org/lib/typesseq-strings.html

For example:

python -c 'print "%(num)02d" % {"num":5}'

How to convert BigInteger to String in java

Use m.toString() or String.valueOf(m). String.valueOf uses toString() but is null safe.

Xcode warning: "Multiple build commands for output file"

In the Project Navigator, select your Xcode Project file. This will show you the project settings as well as the targets in the project. Look in the "Copy Bundle Resources" Build Phase. You should find the offending files in that list twice. Delete the duplicate reference.

Xcode is complaining that you are trying to bundle the same file with your application two times.

OVER clause in Oracle

You can use it to transform some aggregate functions into analytic:

SELECT  MAX(date)
FROM    mytable

will return 1 row with a single maximum,

SELECT  MAX(date) OVER (ORDER BY id)
FROM    mytable

will return all rows with a running maximum.

Is there a limit on number of tcp/ip connections between machines on linux?

Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux

What's the difference between IFrame and Frame?

The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A frameset allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.

Read IFrames security summary.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

I know this question is too old to be about Java 8, but for those using Java 8 you can easily use removeIf():

Collection<Integer> l = new ArrayList<Integer>();

for (int i=0; i < 10; ++i) {
    l.add(new Integer(4));
    l.add(new Integer(5));
    l.add(new Integer(6));
}

l.removeIf(i -> i.intValue() == 5);

how to use concatenate a fixed string and a variable in Python

I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'

Disable browser 'Save Password' functionality

IMHO,
The best way is to randomize the name of the input field that has type=password. Use a prefix of "pwd" and then a random number. Create the field dynamically and present the form to the user.

Your log-in form will look like...

<form>
   <input type=password id=pwd67584 ...>
   <input type=text id=username ...>
   <input type=submit>
</form>

Then, on the server side, when you analyze the form posted by the client, catch the field with a name that starts with "pwd" and use it as 'password'.

How to find the .NET framework version of a Visual Studio project?

It depends which version of Visual Studio:

  • In 2002, all projects use .Net 1.0
  • In 2003, all projects use .Net 1.1
  • In 2005, all projects use .Net 2.0
  • In 2008, projects use .Net 2.0, 3.0, or 3.5; you can change the version in Project Properties
  • In 2010, projects use .Net 2.0, 3.0, 3.5, or 4.0; you can change the version in Project Properties
  • In 2012, projects use .Net 2.0, 3.0, 3.5, 4.0 or 4.5; you can change the version in Project Properties

Newer versions of Visual Studio support many versions of the .Net framework; check your project type and properties.

Accessing MVC's model property from Javascript

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

Remove all occurrences of char from string

here is a lambda function which removes all characters passed as string

BiFunction<String,String,String> deleteChars = (fromString, chars) -> {
  StringBuilder buf = new StringBuilder( fromString );
  IntStream.range( 0, buf.length() ).forEach( i -> {
    while( i < buf.length() && chars.indexOf( buf.charAt( i ) ) >= 0 )
      buf.deleteCharAt( i );
  } );
  return( buf.toString() );
};

String str = "TextX XYto modifyZ";
deleteChars.apply( str, "XYZ" ); // –> "Text to modify"

This solution takes into acount that the resulting String – in difference to replace() – never becomes larger than the starting String when removing characters. So it avoids the repeated allocating and copying while appending character-wise to the StringBuilder as replace() does.
Not to mention the pointless generation of Pattern and Matcher instances in replace() that are never needed for removal.
In difference to replace() this solution can delete several characters in one swoop.

Better way to Format Currency Input editText?

just an additional comment to the approved answer. You may get a crash when moving the cursor on edittext field due to parsing. I did a try catch statement, but implement your own code.

@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(!s.toString().equals(current)){
        amountEditText.removeTextChangedListener(this);

            String cleanString = s.toString().replaceAll("[$,.]", "");

            try{
                double parsed = Double.parseDouble(cleanString);
                String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
                current = formatted;
                amountEditText.setText(formatted);
                amountEditText.setSelection(formatted.length());
            } catch (Exception e) {

            }

            amountEditText.addTextChangedListener(this);
        }
    }

Is there a performance difference between i++ and ++i in C?

I have been reading through most of the answers here and many of the comments, and I didn't see any reference to the one instance that I could think of where i++ is more efficient than ++i (and perhaps surprisingly --i was more efficient than i--). That is for C compilers for the DEC PDP-11!

The PDP-11 had assembly instructions for pre-decrement of a register and post-increment, but not the other way around. The instructions allowed any "general-purpose" register to be used as a stack pointer. So if you used something like *(i++) it could be compiled into a single assembly instruction, while *(++i) could not.

This is obviously a very esoteric example, but it does provide the exception where post-increment is more efficient(or I should say was, since there isn't much demand for PDP-11 C code these days).

Call a global variable inside module

Sohnee solutions is cleaner, but you can also try

window["bootbox"]

What does string::npos mean in this code?

size_t is an unsigned variable, thus 'unsigned value = - 1' automatically makes it the largest possible value for size_t: 18446744073709551615

Get the value of checked checkbox?

If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.

  $(document).on("change", ".messageCheckbox", function(evnt){
    var data = $(".messageCheckbox");
    data.each(function(){
      console.log(this.defaultValue, this.checked);
      // Do something... 
    });
  }); /* END LISTENER messageCheckbox */

Check if a radio button is checked jquery

Something like this:

 $("input[name=test]").is(":checked");

Using the jQuery is() function should work.

How to take the nth digit of a number in python

First treat the number like a string

number = 9876543210
number = str(number)

Then to get the first digit:

number[0]

The fourth digit:

number[3]

EDIT:

This will return the digit as a character, not as a number. To convert it back use:

int(number[0])

from unix timestamp to datetime

The /Date(ms + timezone)/ is a ASP.NET syntax for JSON dates. You might want to use a library like momentjs for parsing such dates. It would come in handy if you need to manipulate or print the dates any time later.

How to add an object to an ArrayList in Java

You have to use new operator here to instantiate. For example:

Contacts.add(new Data(name, address, contact));

How to get annotations of a member variable?

package be.fery.annotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;

@Entity
public class User {
    @Id
    private Long id;

    @Column(name = "ADDRESS_ID")
    private Address address;

    @PrePersist
    public void doStuff(){

    }
}

And a testing class:

    package be.fery.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationIntrospector {

    public AnnotationIntrospector() {
        super();
    }

    public Annotation[] findClassAnnotation(Class<?> clazz) {
        return clazz.getAnnotations();
    }

    public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {

        Annotation[] annotations = null;
        try {
            Class<?>[] params = null;
            Method method = clazz.getDeclaredMethod(methodName, params);
            if (method != null) {
                annotations = method.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
        Annotation[] annotations = null;
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                annotations = field.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        AnnotationIntrospector ai = new AnnotationIntrospector();
        Annotation[] annotations;
        Class<User> userClass = User.class;
        String methodDoStuff = "doStuff";
        String fieldId = "id";
        String fieldAddress = "address";

        // Find class annotations
        annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
        System.out.println("Annotation on class '" + userClass.getName()
                + "' are:");
        showAnnotations(annotations);

        // Find method annotations
        annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
        System.out.println("Annotation on method '" + methodDoStuff + "' are:");
        showAnnotations(annotations);

        // Find field annotations
        annotations = ai.findFieldAnnotation(User.class, fieldId);
        System.out.println("Annotation on field '" + fieldId + "' are:");
        showAnnotations(annotations);

        annotations = ai.findFieldAnnotation(User.class, fieldAddress);
        System.out.println("Annotation on field '" + fieldAddress + "' are:");
        showAnnotations(annotations);

    }

    public static void showAnnotations(Annotation[] ann) {
        if (ann == null)
            return;
        for (Annotation a : ann) {
            System.out.println(a.toString());
        }
    }

}

Hope it helps...

;-)

Add newline to VBA or Visual Basic 6

Use this code between two words:

& vbCrLf &

Using this, the next word displays on the next line.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

./gradlew wrapper --gradle-version=5.4.1 --distribution-type=bin

https://gradle.org/install/#manually

To check:

 ./gradlew tasks

To input it without command:

go to-> gradle/wrapper/gradle-wrapper.properties distribution url and change it to the updated zip version

output:

 ./gradlew tasks
Downloading https://services.gradle.org/distributions/gradle-5.4.1-bin.zip
...................................................................................

Welcome to Gradle 5.4.1!

Here are the highlights of this release:
 - Run builds with JDK12
 - New API for Incremental Tasks
 - Updates to native projects, including Swift 5 support

For more details see https://docs.gradle.org/5.4.1/release-notes.html

Starting a Gradle Daemon (subsequent builds will be faster)

> Starting Daemon 

SQL JOIN vs IN performance?

Funny you mention that, I did a blog post on this very subject.

See Oracle vs MySQL vs SQL Server: Aggregation vs Joins

Short answer: you have to test it and individual databases vary a lot.

Notice: Array to string conversion in

Store the Value of $_SESSION['username'] into a variable such as $username

$username=$_SESSION['username'];

$get = @mysql_query("SELECT money FROM players WHERE username = 
 '$username'");

it should work!

How to allow users to check for the latest app version from inside the app?

I did using in-app updates. This will only with devices running Android 5.0 (API level 21) or higher,

CodeIgniter: Load controller within controller

Just use

..............

self::index();

..............

Remove useless zero digits from decimals in PHP

Complicated way but works:

$num = '125.0100';
$index = $num[strlen($num)-1];
$i = strlen($num)-1;
while($index == '0') {
   if ($num[$i] == '0') {
     $num[$i] = '';
     $i--;
   }

   $index = $num[$i];
}

//remove dot if no numbers exist after dot
$explode = explode('.', $num);
if (isset($explode[1]) && intval($explode[1]) <= 0) {
   $num = intval($explode[0]);
}

echo $num; //125.01

the solutions above are the optimal way but in case you want to have your own you could use this. What this algorithm does it starts at the end of string and checks if its 0, if it is it sets to empty string and then goes to the next character from back untill the last character is > 0

In Android, how do I set margins in dp programmatically?

For a quick one-line setup use

((LayoutParams) cvHolder.getLayoutParams()).setMargins(0, 0, 0, 0);

but be carfull for any wrong use to LayoutParams, as this will have no if statment instance chech

Select data from date range between two dates

SELECT * from Product_sales where
(From_date BETWEEN '2013-01-03'AND '2013-01-09') OR 
(To_date BETWEEN '2013-01-03' AND '2013-01-09') OR 
(From_date <= '2013-01-03' AND To_date >= '2013-01-09')

You have to cover all possibilities. From_Date or To_Date could be between your date range or the record dates could cover the whole range.

If one of From_date or To_date is between the dates, or From_date is less than start date and To_date is greater than the end date; then this row should be returned.

Can I use break to exit multiple nested 'for' loops?

  while (i<n) {
    bool shouldBreakOuter = false;
    for (int j=i + 1; j<n; ++j) {
      if (someCondition) {
          shouldBreakOuter = true;
      }
    }

    if (shouldBreakOuter == true)
      break;

  }

Returning a value even if no result

k-a-f's answer works for selecting one column, if selecting multiple column, we can.

DECLARE a BIGINT DEFAULT 1;
DECLARE b BIGINT DEFAULT "name";

SELECT id, name from table into a,b;

Then we just need to check a,b for values.

REST API Best practices: Where to put parameters?

I generally tend towards #2, As a query argument (i.e. /api/resource?parameter=value ).

A third option is to actually post the parameter=value in the body.

This is because it works better for multi parameter resources and is more extendable for future use.

No matter which one you pick, make sure you only pick one, don't mix and match. That leads towards a confusing API.

Excel SUMIF between dates

To SUMIFS between dates, use the following:

=SUMIFS(B:B,A:A,">="&DATE(2012,1,1),A:A,"<"&DATE(2012,6,1))

C/C++ Struct vs Class

Other that the differences in the default access (public/private), there is no difference.

However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."

Note that C unions work with C++, but not the other way around. For example

union WorksWithCppOnly{
    WorksWithCppOnly():a(0){}
    friend class FloatAccessor;
    int a;
private:
    float b;
};

And likewise

typedef union friend{
    int a;
    float b;
} class;

only works in C

denied: requested access to the resource is denied : docker

My issue was very simply using invalid characters (an extra /) in my image name:

myusername/something/image

is an invalid image name. Try myusername/something-image. Hope this helps someone.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I just encountered the same problem and it had to do with some files being lost or corrupted. To correct the issue, just run check disk:

chkdsk /F e:

This can be run from the search windows box or from a cmd prompt. The /F fixes any issues it finds, like recovering the files. Once this finishes running, you can delete the files and folders like normal.

Vue.js unknown custom element

I had the same error

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

however, I totally forgot to run npm install && npm run dev to compiling the js files.

maybe this helps newbies like me.

How to un-commit last un-pushed git commit without losing the changes

If you pushed the changes, you can undo it and move the files back to stage without using another branch.

git show HEAD > patch
git revert HEAD
git apply patch

It will create a patch file that contain the last branch changes. Then it revert the changes. And finally, apply the patch files to the working tree.