Programs & Examples On #Radial

Read specific columns with pandas or other python module

An easy way to do this is using the pandas library like this.

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name

The problem here was the skipinitialspace which remove the spaces in the header. So ' star_name' becomes 'star_name'

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. My solution was to make all vectors numeric.

How to get coordinates of an svg element?

The way to determine the coordinates depends on what element you're working with. For circles for example, the cx and cy attributes determine the center position. In addition, you may have a translation applied through the transform attribute which changes the reference point of any coordinates.

Most of the ways used in general to get screen coordinates won't work for SVGs. In addition, you may not want absolute coordinates if the line you want to draw is in the same container as the elements it connects.

Edit:

In your particular code, it's quite difficult to get the position of the node because its determined by a translation of the parent element. So you need to get the transform attribute of the parent node and extract the translation from that.

d3.transform(d3.select(this.parentNode).attr("transform")).translate

Working jsfiddle here.

Using SVG as background image

Try placing it on your body

body {
    height: 100%;
    background-image: url(../img/bg.svg);
    background-size:100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-size:cover;
}

Use CSS3 transitions with gradient backgrounds

I wanted to have a div appear like a 3D sphere and transition through colors. I discovered that gradient background colors don't transition (yet). I placed a radial gradient background in front of the element (using z-index) with a transitioning solid background.

/* overlay */
z-index : 1;
background : radial-gradient( ellipse at 25% 25%, rgba( 255, 255, 255, 0 ) 0%, rgba( 0, 0, 0, 1 ) 100% );

then the div.ball underneath:

transition : all 1s cubic-bezier(0.25, 0.46, 0.45, 0.94);

then changed the background color of the div.ball and voila!

https://codepen.io/keldon/pen/dzPxZP

Make <body> fill entire screen?

The goal is to make the <body> element take up the available height of the screen.

If you don't expect your content to take up more than the height of the screen, or you plan to make an inner scrollable element, set

body {
  height: 100vh;
}

otherwise, you want <body> to become scrollable when there is more content than the screen can hold, so set

body {
  min-height: 100vh;
}

this alone achieves the goal, albeit with a possible, and probably desirable, refinement.

Removing the margin of <body>.

body {
  margin: 0;
}

there are two main reasons for doing so.

  1. <body> reaches the edge of the window.
  2. <body> no longer has a scroll bar from the get-go.

P.S. if you want the background to be a radial gradient with its center in the center of the screen and not in the bottom right corner as with your example, consider using something like

_x000D_
_x000D_
body {
  min-height: 100vh;
  margin: 0;
  background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(0,0,0,1) 100%);
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=">
  <title>test</title>
</head>
<body>
</body>
</html>
_x000D_
_x000D_
_x000D_

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

How to write a confusion matrix in Python?

If you don't want scikit-learn to do the work for you...

    import numpy
    actual = numpy.array(actual)
    predicted = numpy.array(predicted)

    # calculate the confusion matrix; labels is numpy array of classification labels
    cm = numpy.zeros((len(labels), len(labels)))
    for a, p in zip(actual, predicted):
        cm[a][p] += 1

    # also get the accuracy easily with numpy
    accuracy = (actual == predicted).sum() / float(len(actual))

Or take a look at a more complete implementation here in NLTK.

How to input matrix (2D list) in Python?

If you want to take n lines of input where each line contains m space separated integers like:

1 2 3
4 5 6 
7 8 9 

Then you can use:

a=[] // declaration 
for i in range(0,n):   //where n is the no. of lines you want 
 a.append([int(j) for j in input().split()])  // for taking m space separated integers as input

Then print whatever you want like for the above input:

print(a[1][1]) 

O/P would be 5 for 0 based indexing

A Space between Inline-Block List Items

Solution:

ul {
    font-size: 0;
}

ul li {
    font-size: 14px;
    display: inline-block;
}

You must set parent font size to 0

Python: How to create a unique file name?

I didn't think your question was very clear, but if all you need is a unique file name...

import uuid

unique_filename = str(uuid.uuid4())

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

How to "comment-out" (add comment) in a batch/cmd?

You can comment something out using :: or REM:

your commands here
:: commenttttttttttt

or

your commands here
REM  commenttttttttttt

 

To do it on the same line as a command, you must add an ampersand:

your commands here      & ::  commenttttttttttt

or

your commands here      & REM  commenttttttttttt

 

Note:

  • Using :: in nested logic (IF-ELSE, FOR loops, etc...) will cause an error. In those cases, use REM instead.

How can I list ALL DNS records?

I've improved Josh's answer. I've noticed that dig only shows entries already present in the queried nameserver's cache, so it's better to pull an authoritative nameserver from the SOA (rather than rely on the default nameserver). I've also disabled the filtering of wildcard IPs because usually I'm usually more interested in the correctness of the setup.

The new script takes a -x argument for expanded output and a -s NS argument to choose a specific nameserver: dig -x example.com

#!/bin/bash
set -e; set -u
COMMON_SUBDOMAINS="www mail mx a.mx smtp pop imap blog en ftp ssh login"
EXTENDED=""

while :; do case "$1" in
  --) shift; break ;;
  -x) EXTENDED=y; shift ;;
  -s) NS="$2"; shift 2 ;;
  *) break ;;
esac; done
DOM="$1"; shift
TYPE="${1:-any}"

test "${NS:-}" || NS=$(dig +short  SOA "$DOM" | awk '{print $1}')
test "$NS" && NS="@$NS"

if test "$EXTENDED"; then
  dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
  wild_ips=$(dig +short "$NS" "*.$DOM" "$TYPE" | tr '\n' '|')
  wild_ips="${wild_ips%|}"
  for sub in $COMMON_SUBDOMAINS; do
    dig +nocmd $NS "$sub.$DOM" +noall +answer "$TYPE"
  done | cat  #grep -vE "${wild_ips}"
  dig +nocmd $NS "*.$DOM" +noall +answer "$TYPE"
else
  dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
fi

Java to Jackson JSON serialization: Money fields

You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).

public class MoneyBean {
    //...

    @JsonProperty("amountOfMoney")
    @JsonSerialize(using = MoneySerializer.class)
    private BigDecimal amount;

    //getters/setters...
}

public class MoneySerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
            JsonProcessingException {
        // put your desired money style here
        jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }
}

That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:

@Test
public void jsonSerializationTest() throws Exception {
     MoneyBean m = new MoneyBean();
     m.setAmount(new BigDecimal("20.3"));

     ObjectMapper mapper = new ObjectMapper();
     assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m));
}

How to implement a custom AlertDialog View

Custom AlertDialog

This full example includes passing data back to the Activity.

enter image description here

Create a custom layout

A layout with an EditText is used for this simple example, but you can replace it with anything you like.

custom_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:paddingLeft="20dp"
              android:paddingRight="20dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Use the dialog in code

The key parts are

  • using setView to assign the custom layout to the AlertDialog.Builder
  • sending any data back to the activity when a dialog button is clicked.

This is the full code from the example project shown in the image above:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showAlertDialogButtonClicked(View view) {

        // create an alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Name");

        // set the custom layout
        final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
        builder.setView(customLayout);

        // add a button
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // send data from the AlertDialog to the Activity
                EditText editText = customLayout.findViewById(R.id.editText);
                sendDialogDataToActivity(editText.getText().toString());
            }
        });

        // create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    // do something with the data coming from the AlertDialog
    private void sendDialogDataToActivity(String data) {
        Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
    }
}

Notes

  • If you find yourself using this in multiple places, then consider making a DialogFragment subclass as is described in the documentation.

See also

Best algorithm for detecting cycles in a directed graph

If DFS finds an edge that points to an already-visited vertex, you have a cycle there.

SQL update fields of one table from fields of another one

I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.

It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:

UPDATE B SET
     COLUMN1 = A.COLUMN1,
     COLUMN2 = A.COLUMN2,
     COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID

Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.

It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:

UPDATE B SET
    (COLUMN1, COLUMN2, COLUMN3) =
               (SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)

FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:

UPDATE B SET
     COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
     COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
     COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

Difference between jar and war in Java

WAR stands for Web application ARchive

JAR stands for Java ARchive

enter image description here

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

Pretty printing XML in Python

You can use popular external library xmltodict, with unparse and pretty=True you will get best result:

xmltodict.unparse(
    xmltodict.parse(my_xml), full_document=False, pretty=True)

full_document=False against <?xml version="1.0" encoding="UTF-8"?> at the top.

How do I get the value of a registry key and ONLY the value using powershell

Harry Martyrossian mentions in a comment on his own answer that the
Get-ItemPropertyValue cmdlet was introduced in Powershell v5, which solves the problem:

PS> Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'
C:\Program Files

Alternatives for PowerShell v4-:

Here's an attempt to retain the efficiency while eliminating the need for repetition of the value name, which, however, is still a little cumbersome:

& { (Get-ItemProperty `
      -LiteralPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
      -Name $args `
    ).$args } 'ProgramFilesDir'

By using a script block, the value name can be passed in once as a parameter, and the parameter variable ($args) can then simply be used twice inside the block.

Alternatively, a simple helper function can ease the pain:

function Get-RegValue([String] $KeyPath, [String] $ValueName) {
  (Get-ItemProperty -LiteralPath $KeyPath -Name $ValueName).$ValueName
}

Note: All solutions above bypass the problem described in Ian Kemp's's answer - the need to use explicit quoting for certain value names when used as property names; e.g., .'15.0' - because the value names are passed as parameters and property access happens via a variable; e.g., .$ValueName


As for the other answers:

  • Andy Arismendi's helpful answer explains the annoyance with having to repeat the value name in order to get the value data efficiently.
  • M Jeremy Carter's helpful answer is more convenient, but can be a performance pitfall for keys with a large number of values, because an object with a large number of properties must be constructed.

How do I get monitor resolution in Python?

In case you have PyQt4 installed, try the following code:

from PyQt4 import QtGui
import sys

MyApp = QtGui.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))

For PyQt5, the following will work:

from PyQt5 import QtWidgets
import sys

MyApp = QtWidgets.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))

Moving up one directory in Python

In Python 3.4 pathlib was introduced:

>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')

It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.

For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.

How to increase space between dotted border dots

IF you're only targeting modern browsers, AND you can have your border on a separate element from your content, then you can use the CSS scale transform to get a larger dot or dash:

border: 1px dashed black;
border-radius: 10px;
-webkit-transform: scale(8);
transform: scale(8);

It takes a lot of positional tweaking to get it to line up, but it works. By changing the thickness of the border, the starting size and the scale factor, you can get to just about thickness-length ratio you want. Only thing you can't touch is dash-to-gap ratio.

How do I vertically center text with CSS?

_x000D_
_x000D_
.box {  _x000D_
  width: 100%;_x000D_
  background: #000;_x000D_
  font-size: 48px;_x000D_
  color: #FFF;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.height {_x000D_
  line-height: 170px;_x000D_
  height: 170px;_x000D_
}_x000D_
_x000D_
.transform { _x000D_
  height: 170px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.transform p {_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  -ms-transform: translate(-50%, -50%);_x000D_
  transform: translate(-50%, -50%);_x000D_
}
_x000D_
<h4>Using Height</h4>_x000D_
<div class="box height">_x000D_
  Lorem ipsum dolor sit_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<h4>Using Transform</h4>_x000D_
<div class="box transform">_x000D_
  <p>Lorem ipsum dolor sit</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to hide html source & disable right click and text copy?

This code is used for disable the right click events and keyboard short cuts.

Just try with this code

_x000D_
_x000D_
document.onkeydown = function(e) {_x000D_
    if(e.keyCode == 123) {_x000D_
     return false;_x000D_
    }_x000D_
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }_x000D_
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }_x000D_
    if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }_x000D_
_x000D_
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)){_x000D_
     return false;_x000D_
    }      _x000D_
 }
_x000D_
_x000D_
_x000D_

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Just in case...
If you are using SoapUI Mock Service (as the Server), calling it from a C# WCF:

WCF --> SoapUI MockService

And in this case you are getting the same error:

The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8).

Edit your Mock Response at SoapUI and add a Header to it: enter image description here

In my scenario, this fix the problem.

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

After trying all the mentioned solutions I found the PlatformTarget somehow added to AnyCPU configuration in my project .csproj.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

Removing the line worked for me.

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

npx nodemon filename.js

This will work on macOS BigSur

String's Maximum length in Java - calling length() method

As mentioned in Takahiko Kawasaki's answer, java represents Unicode strings in the form of modified UTF-8 and in JVM-Spec CONSTANT_UTF8_info Structure, 2 bytes are allocated to length (and not the no. of characters of String).
To extend the answer, the ASM jvm bytecode library's putUTF8 method, contains this:

public ByteVector putUTF8(final String stringValue) {
    int charLength = stringValue.length();
    if (charLength > 65535) {   
   // If no. of characters> 65535, than however UTF-8 encoded length, wont fit in 2 bytes.
      throw new IllegalArgumentException("UTF8 string too large");
    }
    for (int i = 0; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= '\u0001' && charValue <= '\u007F') {
        // Unicode code-point encoding in utf-8 fits in 1 byte.
        currentData[currentLength++] = (byte) charValue;
      } else {
        // doesnt fit in 1 byte.
        length = currentLength;
        return encodeUtf8(stringValue, i, 65535);
      }
    }
    ...
}

But when code-point mapping > 1byte, it calls encodeUTF8 method:

final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength /*= 65535 */) {
    int charLength = stringValue.length();
    int byteLength = offset;
    for (int i = offset; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= 0x0001 && charValue <= 0x007F) {
        byteLength++;
      } else if (charValue <= 0x07FF) {
        byteLength += 2;
      } else {
        byteLength += 3;
      }
    }
   ...
}

In this sense, the max string length is 65535 bytes, i.e the utf-8 encoding length. and not char count
You can find the modified-Unicode code-point range of JVM, from the above utf8 struct link.

Ruby optional parameters

1) You cannot overload the method (Why doesn't ruby support method overloading?) so why not write a new method altogether?

2) I solved a similar problem using the splat operator * for an array of zero or more length. Then, if I want to pass a parameter(s) I can, it is interpreted as an array, but if I want to call the method without any parameter then I don't have to pass anything. See Ruby Programming Language pages 186/187

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

First, set customErrors = "Off" in the web.config and redeploy to get a more detailed error message that will help us diagnose the problem. You could also RDP into the instance and browse to the site from IIS locally to view the errors.

<system.web>
      <customErrors mode="Off" />

First guess though - you have some references (most likely Azure SDK references) that are not set to Copy Local = true. So, all your dependencies are not getting deployed.

Get to the detailed error first and update your question.

UPDATE: A second option now available in VS2013 is Remote Debugging a Cloud Service or Virtual Machine.

Replace words in the body text

I had the same problem. I wrote my own function using replace on innerHTML, but it would screw up anchor links and such.

To make it work correctly I used a library to get this done.

The library has an awesome API. After including the script I called it like this:

findAndReplaceDOMText(document.body, {
  find: 'texttofind',
  replace: 'texttoreplace'
  }
);

Multiple file extensions in OpenFileDialog

This is from MSDN sample:

(*.bmp, *.jpg)|*.bmp;*.jpg

So for your case

openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"

How to join (merge) data frames (inner, outer, left, right)

Update join. One other important SQL-style join is an "update join" where columns in one table are updated (or created) using another table.

Modifying the OP's example tables...

sales = data.frame(
  CustomerId = c(1, 1, 1, 3, 4, 6), 
  Year = 2000:2005,
  Product = c(rep("Toaster", 3), rep("Radio", 3))
)
cust = data.frame(
  CustomerId = c(1, 1, 4, 6), 
  Year = c(2001L, 2002L, 2002L, 2002L),
  State = state.name[1:4]
)

sales
# CustomerId Year Product
#          1 2000 Toaster
#          1 2001 Toaster
#          1 2002 Toaster
#          3 2003   Radio
#          4 2004   Radio
#          6 2005   Radio

cust
# CustomerId Year    State
#          1 2001  Alabama
#          1 2002   Alaska
#          4 2002  Arizona
#          6 2002 Arkansas

Suppose we want to add the customer's state from cust to the purchases table, sales, ignoring the year column. With base R, we can identify matching rows and then copy values over:

sales$State <- cust$State[ match(sales$CustomerId, cust$CustomerId) ]

# CustomerId Year Product    State
#          1 2000 Toaster  Alabama
#          1 2001 Toaster  Alabama
#          1 2002 Toaster  Alabama
#          3 2003   Radio     <NA>
#          4 2004   Radio  Arizona
#          6 2005   Radio Arkansas

# cleanup for the next example
sales$State <- NULL

As can be seen here, match selects the first matching row from the customer table.


Update join with multiple columns. The approach above works well when we are joining on only a single column and are satisfied with the first match. Suppose we want the year of measurement in the customer table to match the year of sale.

As @bgoldst's answer mentions, match with interaction might be an option for this case. More straightforwardly, one could use data.table:

library(data.table)
setDT(sales); setDT(cust)

sales[, State := cust[sales, on=.(CustomerId, Year), x.State]]

#    CustomerId Year Product   State
# 1:          1 2000 Toaster    <NA>
# 2:          1 2001 Toaster Alabama
# 3:          1 2002 Toaster  Alaska
# 4:          3 2003   Radio    <NA>
# 5:          4 2004   Radio    <NA>
# 6:          6 2005   Radio    <NA>

# cleanup for next example
sales[, State := NULL]

Rolling update join. Alternately, we may want to take the last state the customer was found in:

sales[, State := cust[sales, on=.(CustomerId, Year), roll=TRUE, x.State]]

#    CustomerId Year Product    State
# 1:          1 2000 Toaster     <NA>
# 2:          1 2001 Toaster  Alabama
# 3:          1 2002 Toaster   Alaska
# 4:          3 2003   Radio     <NA>
# 5:          4 2004   Radio  Arizona
# 6:          6 2005   Radio Arkansas

The three examples above all focus on creating/adding a new column. See the related R FAQ for an example of updating/modifying an existing column.

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Compile c++14-code with g++

For gcc 4.8.4 you need to use -std=c++1y in later versions, looks like starting with 5.2 you can use -std=c++14.

If we look at the gcc online documents we can find the manuals for each version of gcc and we can see by going to Dialect options for 4.9.3 under the GCC 4.9.3 manual it says:

‘c++1y’

The next revision of the ISO C++ standard, tentatively planned for 2014. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.

So up till 4.9.3 you had to use -std=c++1y while the gcc 5.2 options say:

‘c++14’ ‘c++1y’

The 2014 ISO C++ standard plus amendments. The name ‘c++1y’ is deprecated.

It is not clear to me why this is listed under Options Controlling C Dialect but that is how the documents are currently organized.

Arrow operator (->) usage in C

Yes, that's it.

It's just the dot version when you want to access elements of a struct/class that is a pointer instead of a reference.

struct foo
{
  int x;
  float y;
};

struct foo var;
struct foo* pvar;
pvar = malloc(sizeof(pvar));

var.x = 5;
(&var)->y = 14.3;
pvar->y = 22.4;
(*pvar).x = 6;

That's it!

Return JSON for ResponseEntity<String>

public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
    JSONObject resp = new JSONObject();
    resp.put("status", 0);
    resp.put("id", id);

    return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}

Crop image in PHP

Improved Crop image functionality in PHP on the fly.

http://www.example.com/cropimage.php?filename=a.jpg&newxsize=100&newysize=200&constrain=1

Code in cropimage.php

$basefilename = @basename(urldecode($_REQUEST['filename']));

$path = 'images/';
$outPath = 'crop_images/';
$saveOutput = false; // true/false ("true" if you want to save images in out put folder)
$defaultImage = 'no_img.png'; // change it with your default image

$basefilename = $basefilename;
$w = $_REQUEST['newxsize'];
$h = $_REQUEST['newysize'];

if ($basefilename == "") {
    $img = $path . $defaultImage;
    $percent = 100;
} else {
    $img = $path . $basefilename;

    $len = strlen($img);
    $ext = substr($img, $len - 3, $len);
    $img2 = substr($img, 0, $len - 3) . strtoupper($ext);
    if (!file_exists($img)) $img = $img2;
    if (file_exists($img)) {
        $percent = @$_GET['percent'];
        $constrain = @$_GET['constrain'];
        $w = $w;
        $h = $h;
    } else if (file_exists($path . $basefilename)) {
        $img = $path . $basefilename;
        $percent = $_GET['percent'];
        $constrain = $_GET['constrain'];
        $w = $w;
        $h = $h;
    } else {

        $img = $path . 'no_img.png';    // change with your default image
        $percent = @$_GET['percent'];
        $constrain = @$_GET['constrain'];
        $w = $w;
        $h = $h;

    }

}

// get image size of img
$x = @getimagesize($img);

// image width
$sw = $x[0];
// image height
$sh = $x[1];

if ($percent > 0) {
    // calculate resized height and width if percent is defined
    $percent = $percent * 0.01;
    $w = $sw * $percent;
    $h = $sh * $percent;
} else {
    if (isset ($w) AND !isset ($h)) {
        // autocompute height if only width is set
        $h = (100 / ($sw / $w)) * .01;
        $h = @round($sh * $h);
    } elseif (isset ($h) AND !isset ($w)) {
        // autocompute width if only height is set
        $w = (100 / ($sh / $h)) * .01;
        $w = @round($sw * $w);
    } elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
        // get the smaller resulting image dimension if both height
        // and width are set and $constrain is also set
        $hx = (100 / ($sw / $w)) * .01;
        $hx = @round($sh * $hx);

        $wx = (100 / ($sh / $h)) * .01;
        $wx = @round($sw * $wx);

        if ($hx < $h) {
            $h = (100 / ($sw / $w)) * .01;
            $h = @round($sh * $h);
        } else {
            $w = (100 / ($sh / $h)) * .01;
            $w = @round($sw * $w);
        }
    }
}

$im = @ImageCreateFromJPEG($img) or // Read JPEG Image
$im = @ImageCreateFromPNG($img) or // or PNG Image
$im = @ImageCreateFromGIF($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF

if (!$im) {
    // We get errors from PHP's ImageCreate functions...
    // So let's echo back the contents of the actual image.
    readfile($img);
} else {
    // Create the resized image destination
    $thumb = @ImageCreateTrueColor($w, $h);
    // Copy from image source, resize it, and paste to image destination
    @ImageCopyResampled($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);

    //Other format imagepng()

    if ($saveOutput) { //Save image
        $save = $outPath . $basefilename;
        @ImageJPEG($thumb, $save);
    } else { // Output resized image
        header("Content-type: image/jpeg");
        @ImageJPEG($thumb);
    }
}

MongoDB Show all contents from all collections

Before writing below queries first get into your cmd or PowerShell

TYPE:
mongo             //To get into MongoDB shell
use <Your_dbName>      //For Creating or making use of existing db

To List All Collection Names use any one from below options :-

show collections  //output every collection
  OR
show tables
  OR
db.getCollectionNames() //shows all collections as a list

To show all collections content or data use below listed code which had been posted by Bruno_Ferreira.

var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++) {    
   print('Collection: ' + collections[i]); // print the name of each collection
   db.getCollection(collections[i]).find().forEach(printjson); //and then print     the json of each of its elements
}

Converting Long to Date in Java returns 1970

Only set the time in mills on Calendar object

Calendar c = Calendar.getInstance();
c.setTimeInMillis(1385355600000l);
System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.DAY_OF_MONTH));
// get Date
System.out.println(c.getTime());

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

Here is a solution that creates a section that is expandable using somewhat material design, bootstrap 4.5/5 alpha and entirely non-javascript.

Style for head section

<style>
[data-toggle="collapse"] .fa:before {
    content: "\f077";
}

[data-toggle="collapse"].collapsed .fa:before {
    content: "\f078";
}
</style>

Body html

<div class="pt-3 pb-3" style="border-top: 1px solid #eeeeee; border-bottom: 1px solid #eeeeee; cursor: pointer;">
<a href="#expandId" class="text-dark float-right collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">
    <i class="fa" aria-hidden="false"></i>
</a>
<a href="#expandId" class="text-dark collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">Expand Header</a>
<div class="collapse" id="expandId">
    CONTENT GOES IN HERE
</div>

How do I perform a JAVA callback between classes?

Use the observer pattern. It works like this:

interface MyListener{
    void somethingHappened();
}

public class MyForm implements MyListener{
    MyClass myClass;
    public MyForm(){
        this.myClass = new MyClass();
        myClass.addListener(this);
    }
    public void somethingHappened(){
       System.out.println("Called me!");
    }
}
public class MyClass{
    private List<MyListener> listeners = new ArrayList<MyListener>();

    public void addListener(MyListener listener) {
        listeners.add(listener);
    }
    void notifySomethingHappened(){
        for(MyListener listener : listeners){
            listener.somethingHappened();
        }
    }
}

You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.

This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.

In my example:

MyClass is the producer here as its notifying a list of listeners.

MyListener is the interface.

MyForm is interested in when somethingHappened, so it is implementing MyListener and registering itself with MyClass. Now MyClass can inform MyForm about events without directly referencing MyForm. This is the strength of the observer pattern, it reduces dependency and increases reusability.

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

css 100% width div not taking up full width of parent

The problem is caused by your #grid having a width:1140px.

You need to set a min-width:1140px on the body.

This will stop the body from getting smaller than the #grid. Remove width:100% as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/

html, body{
    margin:0;
    padding:0;
    min-width: 1140px; /* this is the important part*/
}
#grid-container{
    background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
    width:1140px;
    margin:0px auto;
}

MySQL Trigger - Storing a SELECT in a variable

Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)

How to force child div to be 100% of parent div's height without specifying parent's height?

As shown earlier, flexbox is the easiest. eg.

#main{ display: flex; align-items:center;}

this will align all child elements to the center within the parent element.

Check if input value is empty and display an alert

Better one is here.

$('#submit').click(function()
{
    if( !$('#myMessage').val() ) {
       alert('warning');
    }
});

And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#submit').on('click',function()
{
    if( $('#myMessage').val().length === 0 ) {
        alert('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#submit').click(function()
{
      if( !document.getElementById('myMessage').value ) {
          alert('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).

Make an HTTP request with android

The most simple way is using the Android lib called Volley

Volley offers the following benefits:

Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.

You can send a http/https request as simple as this:

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="http://www.yourapi.com";
        JsonObjectRequest request = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (null != response) {
                         try {
                             //handle your response
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                    }
                }
            }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);

In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Upgrade python in a virtualenv

This approach always works for me:

# First of all, delete all broken links. Replace  my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs

Taken from:

SQL Row_Number() function in Where Clause

Select * from 
(
    Select ROW_NUMBER() OVER ( order by Id) as 'Row_Number', * 
    from tbl_Contact_Us
) as tbl
Where tbl.Row_Number = 5

How do I dynamically change the content in an iframe using jquery?

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

How do I get TimeSpan in minutes given two Dates?

See TimeSpan.TotalMinutes:

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

Could pandas use column as index?

You can change the index as explained already using set_index. You don't need to manually swap rows with columns, there is a transpose (data.T) method in pandas that does it for you:

> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                    ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> newdf = df.set_index('Locality').T
> newdf

Locality    ABBOTSFORD  ABERFELDIE
2005        427000      534000
2006        448000      600000

then you can fetch the dataframe column values and transform them to a list:

> newdf['ABBOTSFORD'].values.tolist()

[427000, 448000]

What are projection and selection?

Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).

In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.

Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

How to find a value in an array of objects in JavaScript?

There's already a lot of good answers here so why not one more, use a library like lodash or underscore :)

obj = {
   1 : { name : 'bob' , dinner : 'pizza' },
   2 : { name : 'john' , dinner : 'sushi' },
   3 : { name : 'larry', dinner : 'hummus' }
}

_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]

Error: Can't set headers after they are sent to the client

In my case, In a loop, I put res.render() so might have been tried to call multiple times.

How does the "final" keyword in Java work? (I can still modify an object.)

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

  1. variable
  2. method
  3. class

The final keyword can be applied with the variables, a final variable that has no value, is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

Java final variable:

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.

class Bike9{  
    final int speedlimit=90;//final variable  
    void run(){  
        speedlimit=400;  // this will make error
    }  

    public static void main(String args[]){  
    Bike9 obj=new  Bike9();  
    obj.run();  
    }  
}//end of class  

Java final class:

If you make any class as final, you cannot extend it.

Example of final class

final class Bike{}  

class Honda1 extends Bike{    //cannot inherit from final Bike,this will make error
  void run(){
      System.out.println("running safely with 100kmph");
   }  

  public static void main(String args[]){  
      Honda1 honda= new Honda();  
      honda.run();  
      }  
  }  

Java final method:

If you make any method as final, you cannot override it.

Example of final method (run() in Honda cannot override run() in Bike)

class Bike{  
  final void run(){System.out.println("running");}  
}  

class Honda extends Bike{  
   void run(){System.out.println("running safely with 100kmph");}  

   public static void main(String args[]){  
   Honda honda= new Honda();  
   honda.run();  
   }  
}  

shared from: http://www.javatpoint.com/final-keyword

Determine if two rectangles overlap each other?

For those of you who are using center points and half sizes for their rectangle data, instead of the typical x,y,w,h, or x0,y0,x1,x1, here's how you can do it:

#include <cmath> // for fabsf(float)

struct Rectangle
{
    float centerX, centerY, halfWidth, halfHeight;
};

bool isRectangleOverlapping(const Rectangle &a, const Rectangle &b)
{
    return (fabsf(a.centerX - b.centerX) <= (a.halfWidth + b.halfWidth)) &&
           (fabsf(a.centerY - b.centerY) <= (a.halfHeight + b.halfHeight)); 
}

How to do an Integer.parseInt() for a decimal number?

Use,

String s="0.01";
int i= new Double(s).intValue();

Convert list of dictionaries to a pandas DataFrame

In pandas 16.2, I had to do pd.DataFrame.from_records(d) to get this to work.

PHP Multiple Checkbox Array

add [] in the name of the attributes in the input tag

 <form action="" name="frm" method="post">
<input type="checkbox" name="hobby[]" value="coding">  coding &nbsp
<input type="checkbox" name="hobby[]" value="database">  database &nbsp
<input type="checkbox" name="hobby[]" value="software engineer">  soft Engineering <br>
<input type="submit" name="submit" value="submit"> 
</form>

for PHP Code :

<?php
 if(isset($_POST['submit']){
   $hobby = $_POST['hobby'];

   foreach ($hobby as $hobys=>$value) {
             echo "Hobby : ".$value."<br />";
        }
}
?>

How to plot ROC curve in Python

from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt

y_true = # true labels
y_probas = # predicted results
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_probas, pos_label=0)

# Print ROC curve
plt.plot(fpr,tpr)
plt.show() 

# Print AUC
auc = np.trapz(tpr,fpr)
print('AUC:', auc)

How to pass a type as a method parameter in Java

If you want to pass the type, than the equivalent in Java would be

java.lang.Class

If you want to use a weakly typed method, then you would simply use

java.lang.Object

and the corresponding operator

instanceof

e.g.

private void foo(Object o) {

  if(o instanceof String) {

  }

}//foo

However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.

The real question is what you actually want to achieve here, otherwise it is difficult to answer:

Or is there a better way?

Adding a newline into a string in C#

You can add a new line character after the @ symbol like so:

string newString = oldString.Replace("@", "@\n");  

You can also use the NewLine property in the Environment Class (I think it is Environment).

converting drawable resource image into bitmap

First Create Bitmap Image

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);

now set bitmap in Notification Builder Icon....

Notification.Builder.setLargeIcon(bmp);

OpenCV get pixel channel value from Mat image

Assuming the type is CV_8UC3 you would do this:

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        Vec3b bgrPixel = foo.at<Vec3b>(i, j);

        // do something with BGR values...
    }
}

Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.

EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:

Here is how you might go about this:

uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
        bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
        bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R

        // do something with BGR values...
    }
}

Or alternatively:

int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    uint8_t* rowPtr = foo.row(i);
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
        bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
        bgrPixel.val[2] = rowPtr[j*cn + 2]; // R

        // do something with BGR values...
    }
}

ImportError: No module named 'selenium'

I had a similar problem. It turned out that I had an alias defined for python like so:

alias python=/usr/bin/python3

Apparently virtualenv does not check or update your aliases.

So the solution for me was to remove the alias:

unalias python

Now when I run python, I get the one from the virtual environment. Problem solved.

How can I add 1 day to current date?

int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);

CodePen

_x000D_
_x000D_
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
_x000D_
_x000D_

When should I use GC.SuppressFinalize()?

SupressFinalize tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:

Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.

In general, most any Dispose() method should be able to call GC.SupressFinalize(), because it should clean up everything that would be cleaned up in the finalizer.

SupressFinalize is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()/finalizer should work properly with or without a call to GC.SupressFinalize().

Converting List<Integer> to List<String>

What you're doing is fine, but if you feel the need to 'Java-it-up' you could use a Transformer and the collect method from Apache Commons, e.g.:

public class IntegerToStringTransformer implements Transformer<Integer, String> {
   public String transform(final Integer i) {
      return (i == null ? null : i.toString());
   }
}

..and then..

CollectionUtils.collect(
   collectionOfIntegers, 
   new IntegerToStringTransformer(), 
   newCollectionOfStrings);

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

This can be achieved by assigning the header view manually in the UITableViewController's viewDidLoad method instead of using the delegate's viewForHeaderInSection and heightForHeaderInSection. For example in your subclass of UITableViewController, you can do something like this:

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    [headerView setBackgroundColor:[UIColor magentaColor]];
    [headerView setTextAlignment:NSTextAlignmentCenter];
    [headerView setText:@"Hello World"];
    [[self tableView] setTableHeaderView:headerView];
}

The header view will then disappear when the user scrolls. I don't know why this works like this, but it seems to achieve what you're looking to do.

Set database timeout in Entity Framework

I extended Ronnie's answer with a fluent implementation so you can use it like so:

dm.Context.SetCommandTimeout(120).Database.SqlQuery...

public static class EF
{
    public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
    {
        ((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;

        return db;
    }

    public static DbContext SetCommandTimeout(this DbContext db, int seconds)
    {
        return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
    } 
}

The view didn't return an HttpResponse object. It returned None instead

Because the view must return render, not just call it. Change the last line to

return render(request, 'auth_lifecycle/user_profile.html',
           context_instance=RequestContext(request))

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

Found out that there's no bug there. Just add:

<base href="/" />

to your <head />.

How to change TextBox's Background color?

webforms;

TextBox.Background = System.Drawing.Color.Red;

Mod of negative number is melting my brain

Adding some understanding.

By Euclidean definition the mod result must be always positive.

Ex:

 int n = 5;
 int x = -3;

 int mod(int n, int x)
 {
     return ((n%x)+x)%x;
 }

Output:

 -1

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

Best practice to run Linux service as a different user

After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:

  1. hop is right to point me back at /etc/init.d/functions: the daemon function already allows you to set an alternate user:

    daemon --user=my_user my_cmd &>/dev/null &
    

    This is implemented by wrapping the process invocation with runuser - more on this later.

  2. Jonathan Leffler is right: there is setuid in Python:

    import os
    os.setuid(501) # UID of my_user is 501
    

    I still don't think you can setuid from inside a JVM, however.

  3. Neither su nor runuser gracefully handle the case where you ask to run a command as the user you already are. E.g.:

    [my_user@my_host]$ id
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    [my_user@my_host]$ su my_user -c "id"
    Password: # don't want to be prompted!
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    

To workaround that behaviour of su and runuser, I've changed my init script to something like:

if [[ "$USER" == "my_user" ]]
then
    daemon my_cmd &>/dev/null &
else
    daemon --user=my_user my_cmd &>/dev/null &
fi

Thanks all for your help!

How to check the function's return value if true or false

you're comparing the result against a string ('false') not the built-in negative constant (false)

just use

if(ValidateForm() == false) {

or better yet

if(!ValidateForm()) {

also why are you calling validateForm twice?

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

SQL "between" not inclusive

You can use the date() function which will extract the date from a datetime and give you the result as inclusive date:

SELECT * FROM Cases WHERE date(created_at)='2013-05-01' AND '2013-05-01'

html table span entire width?

<table border="1"; width=100%>

works for me.

Should functions return null or an empty object?

I prefer null, since it's compatible with the null-coalescing operator (??).

get an element's id

You need to check if is a string to avoid getting a child element

var getIdFromDomObj = function(domObj){
   var id = domObj.id;
   return typeof id  === 'string' ? id : false;
};

How to sort an array in Bash

There is a workaround for the usual problem of spaces and newlines:

Use a character that is not in the original array (like $'\1' or $'\4' or similar).

This function gets the job done:

# Sort an Array may have spaces or newlines with a workaround (wa=$'\4')
sortarray(){ local wa=$'\4' IFS=''
             if [[ $* =~ [$wa] ]]; then
                 echo "$0: error: array contains the workaround char" >&2
                 exit 1
             fi

             set -f; local IFS=$'\n' x nl=$'\n'
             set -- $(printf '%s\n' "${@//$nl/$wa}" | sort -n)
             for    x
             do     sorted+=("${x//$wa/$nl}")
             done
       }

This will sort the array:

$ array=( a b 'c d' $'e\nf' $'g\1h')
$ sortarray "${array[@]}"
$ printf '<%s>\n' "${sorted[@]}"
<a>
<b>
<c d>
<e
f>
<gh>

This will complain that the source array contains the workaround character:

$ array=( a b 'c d' $'e\nf' $'g\4h')
$ sortarray "${array[@]}"
./script: error: array contains the workaround char

description

  • We set two local variables wa (workaround char) and a null IFS
  • Then (with ifs null) we test that the whole array $*.
  • Does not contain any woraround char [[ $* =~ [$wa] ]].
  • If it does, raise a message and signal an error: exit 1
  • Avoid filename expansions: set -f
  • Set a new value of IFS (IFS=$'\n') a loop variable x and a newline var (nl=$'\n').
  • We print all values of the arguments received (the input array $@).
  • but we replace any new line by the workaround char "${@//$nl/$wa}".
  • send those values to be sorted sort -n.
  • and place back all the sorted values in the positional arguments set --.
  • Then we assign each argument one by one (to preserve newlines).
  • in a loop for x
  • to a new array: sorted+=(…)
  • inside quotes to preserve any existing newline.
  • restoring the workaround to a newline "${x//$wa/$nl}".
  • done

Python: count repeated elements in the list

You can do that using count:

my_dict = {i:MyList.count(i) for i in MyList}

>>> print my_dict     #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

Or using collections.Counter:

from collections import Counter

a = dict(Counter(MyList))

>>> print a           #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

List all files and directories in a directory + subdirectories

I use the following code with a form that has 2 buttons, one for exit and the other to start. A folder browser dialog and a save file dialog. Code is listed below and works on my system Windows10 (64):

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Directory_List
{

    public partial class Form1 : Form
    {
        public string MyPath = "";
        public string MyFileName = "";
        public string str = "";

        public Form1()
        {
            InitializeComponent();
        }    
        private void cmdQuit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }    
        private void cmdGetDirectory_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            MyPath = folderBrowserDialog1.SelectedPath;    
            saveFileDialog1.ShowDialog();
            MyFileName = saveFileDialog1.FileName;    
            str = "Folder = " + MyPath + "\r\n\r\n\r\n";    
            DirectorySearch(MyPath);    
            var result = MessageBox.Show("Directory saved to Disk!", "", MessageBoxButtons.OK);
                Application.Exit();    
        }    
        public void DirectorySearch(string dir)
        {
                try
            {
                foreach (string f in Directory.GetFiles(dir))
                {
                    str = str + dir + "\\" + (Path.GetFileName(f)) + "\r\n";
                }    
                foreach (string d in Directory.GetDirectories(dir, "*"))
                {

                    DirectorySearch(d);
                }
                        System.IO.File.WriteAllText(MyFileName, str);

            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

pyplot axes labels for subplots

You can create a big subplot that covers the two subplots and then set the common labels.

import random
import matplotlib.pyplot as plt

x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]

fig = plt.figure()
ax = fig.add_subplot(111)    # The big subplot
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top=False, bottom=False, left=False, right=False)

ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Set common labels
ax.set_xlabel('common xlabel')
ax.set_ylabel('common ylabel')

ax1.set_title('ax1 title')
ax2.set_title('ax2 title')

plt.savefig('common_labels.png', dpi=300)

common_labels.png

Another way is using fig.text() to set the locations of the common labels directly.

import random
import matplotlib.pyplot as plt

x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Set common labels
fig.text(0.5, 0.04, 'common xlabel', ha='center', va='center')
fig.text(0.06, 0.5, 'common ylabel', ha='center', va='center', rotation='vertical')

ax1.set_title('ax1 title')
ax2.set_title('ax2 title')

plt.savefig('common_labels_text.png', dpi=300)

common_labels_text.png

How can I enable the MySQLi extension in PHP 7?

sudo phpenmod mysqli
sudo service apache2 restart

  • phpenmod moduleName enables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • phpdismod moduleName disables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • php -m lists the loaded modules

Simulate string split function in Excel formula

Some great worksheet-fu in the other answers but I think they've overlooked that you can define a user-defined function (udf) and call this from the sheet or a formula.

The next problem you have is to decide either to work with a whole array or with element.

For example this UDF function code

Public Function UdfSplit(ByVal sText As String, Optional ByVal sDelimiter As String = " ", Optional ByVal lIndex As Long = -1) As Variant
    Dim vSplit As Variant
    vSplit = VBA.Split(sText, sDelimiter)
    If lIndex > -1 Then
        UdfSplit = vSplit(lIndex)
    Else
        UdfSplit = vSplit
    End If
End Function

allows single elements with the following in one cell

=UdfSplit("EUR/USD","/",0)

or one can use a blocks of cells with

=UdfSplit("EUR/USD","/")

How can I make a horizontal ListView in Android?

Have you looked into using a HorizontalScrollView to wrap your list items? That will allow each of your list items to be horizontally scrollable (what you put in there is up to you, and can make them dynamic items similar to ListView). This will work well if you are only after a single row of items.

Importing project into Netbeans

Follow these steps:

  1. Open Netbeans
  2. Click File > New Project > JavaFX > JavaFX with existing sources
  3. Click Next
  4. Name the project
  5. Click Next
  6. Under Source Package Folders click Add Folder
  7. Select the nbproject folder under the zip file you wish to upload (Note: you need to unzip the folder)
  8. Click Next
  9. All the files will be included but you can exclude some if you wish
  10. Click Finish and the project should be there

If you don't have the source folder added do the following

  1. Under your projects directory tree right click on Source Packages
  2. Click New
  3. Click Java Package and name it with the name of the package the source files have
  4. Go to the directory location (i.e., using Windows Explorer not Netbeans) of those source files, highlight them all, then drag and drop them under that Java Package you just created
  5. Click Run
  6. Click Clean and Build Project

Now you can have fun and run the application.

How do you add CSS with Javascript?

You can also do this using DOM Level 2 CSS interfaces (MDN):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:

sheet.addRule('strong', 'color: red;', -1);

There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.

You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.

View tabular file such as CSV from command line

tblless in the Tabulator package wraps the unix column command, and also aligns numeric columns.

Center an element in Bootstrap 4 Navbar

I had a similar problem; the anchor text in my Bootstrap4 navbar wasn't centered. Simply added text-center in the anchor's class.

How do you search an amazon s3 bucket?

Given that you are in AWS...I would think you would want to use their CloudSearch tools. Put the data you want to search in their service...have it point to the S3 keys.

http://aws.amazon.com/cloudsearch/

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Sublime Text 2 - View whitespace characters

In selected text, SPACE is shown as dot (.) and TAB as a dash (-).

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Firstly, you need to be aware that UTC isn't a format, it's a time zone, effectively. So "converting from ISO8601 to UTC" doesn't really make sense as a concept.

However, here's a sample program using Joda Time which parses the text into a DateTime and then formats it. I've guessed at a format you may want to use - you haven't really provided enough information about what you're trying to do to say more than that. You may also want to consider time zones... do you want to display the local time at the specified instant? If so, you'll need to work out the user's time zone and convert appropriately.

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        String text = "2011-03-10T11:54:30.207Z";
        DateTimeFormatter parser = ISODateTimeFormat.dateTime();
        DateTime dt = parser.parseDateTime(text);

        DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
        System.out.println(formatter.print(dt));
    }
}

Amazon Interview Question: Design an OO parking lot

In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".

Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.

The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)

License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.

Jquery insert new row into table at a certain index

Note:

$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody

$("table#myTable tr").last().after(newRow);  // this will add new row outside tbody 
                                             //i.e. between thead and tbody
                                             //.before() will also work similar

Twitter Bootstrap Modal Form Submit

Simple

<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

What does "#include <iostream>" do?

# indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.

So, #include is a preprocessor directive that tells the preprocessor to include header files in the program.

< > indicate the start and end of the file name to be included.

iostream is a header file that contains functions for input/output operations (cin and cout).

Now to sum it up C++ to English translation of the command, #include <iostream> is:

Dear preprocessor, please include all the contents of the header file iostream at the very beginning of this program before compiler starts the actual compilation of the code.

How do I set up a private Git repository on GitHub? Is it even possible?

If you are a student you can get a free private repository at https://github.com/edu

Update

As noted in another answer, now there is an option for private repos also for simple users

String comparison using '==' vs. 'strcmp()'

strcmp() and === are both case sensitive but === is much faster

sample code: http://snipplr.com/view/758/

PostgreSQL visual interface similar to phpMyAdmin?

I would also highly recommend Adminer - http://www.adminer.org/

It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.

JQuery, Spring MVC @RequestBody and JSON - making it work together

In Addition you also need to be sure that you have

 <context:annotation-config/> 

in your SPring configuration xml.

I also would recommend you to read this blog post. It helped me alot. Spring blog - Ajax Simplifications in Spring 3.0

Update:

just checked my working code where I have @RequestBody working correctly. I also have this bean in my config:

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
    <ref bean="jacksonMessageConverter"/>
  </list>
</property>
</bean>

May be it would be nice to see what Log4j is saying. it usually gives more information and from my experience the @RequestBody will fail if your request's content type is not Application/JSON. You can run Fiddler 2 to test it, or even Mozilla Live HTTP headers plugin can help.

convert nan value to zero

You can use lambda function, an example for 1D array:

import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)

This will give you the result:

[0, 2, 3]

What does getActivity() mean?

getActivity()- Return the Activity this fragment is currently associated with.

Get string between two strings in a string

In C# 8.0 and above, you can use the range operator .. as in

var s = "header-THE_TARGET_STRING.7z";
var from = s.IndexOf("-") + "-".Length;
var to = s.IndexOf(".7z");
var versionString = s[from..to];  // THE_TARGET_STRING

See documentation for details.

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

adb connection over tcp not working now

Try to do port forwarding,

adb forward tcp:<PC port> tcp:<device port>.

like:

adb forward tcp:5555 tcp:5555.

sounds like 5555 port is captured so use other one. As I know 7612 is empty

[Edit]

C:\Users\m>adb forward tcp:7612 tcp:7612

C:\Users\m>adb tcpip 7612
restarting in TCP mode port: 7612

C:\Users\m>adb connect 192.168.1.12
connected to 192.168.1.12:7612

Be sure that you connect to the right IP address. (You can download Network Info 2 to check your IP)

How to get data by SqlDataReader.GetValue by column name

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

  1. Clean project
  2. Rebuild project
  3. Sync Gradle

it work for me

How to find out the MySQL root password

System:

  • CentOS Linux 7
  • mysql Ver 14.14 Distrib 5.7.25

Procedure:

  1. Open two shell sessions, logging in to one as the Linux root user and the other as a nonroot user with access to the mysql command.

  2. In your root session, stop the normal mysqld listener and start a listener which bypasses password authentication (note: this is a significant security risk as anyone with access to the mysql command may access your databases without a password. You may want to close active shell sessions and/or disable shell access before doing this):

    # systemctl stop mysqld
    # /usr/sbin/mysqld --skip-grant-tables -u mysql &

  3. In your nonroot session, log in to mysql and set the mysql root password:

    $ mysql
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

    mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
    Query OK, 0 rows affected, 1 warning (0.01 sec)

    mysql> quit;

  4. In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:

    # kill %1
    # systemctl start mysqld

  5. In your nonroot session, test the new root password you configured above:

    $ mysql -u root -p
    Enter password:
    Welcome to the MySQL monitor. Commands end with ; or \g.
    ...
    mysql>

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Remove the external scripts in your index.html

Change this:

<script src="http://code.highcharts.com/highcharts-more.js"></script>

to

<script src="project_folder/highcharts-more.js"></script>

Use jQuery to get the file input's selected filename without the path

Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?

How to create a .NET DateTime from ISO 8601 format

DateTime.ParseExact(...) allows you to tell the parser what each character represents.

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

how to find my angular version in my project?

For Angular 2+ you can run this in the console:

document.querySelector('[ng-version]').getAttribute('ng-version')

For AngularJS 1.x:

angular.version.full

SQL Server: Make all UPPER case to Proper Case/Title Case

I think you will find that the following is more efficient:

IF OBJECT_ID('dbo.ProperCase') IS NOT NULL
    DROP FUNCTION dbo.ProperCase
GO
CREATE FUNCTION dbo.PROPERCASE (
    @str VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
    SET @str = ' ' + @str
    SET @str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z')
    RETURN RIGHT(@str, LEN(@str) - 1)
END
GO

The replace statement could be cut and pasted directly into a SQL query. It is ultra ugly, however by replacing @str with the column you are interested in, you will not pay a price for an implicit cursor like you will with the udfs thus posted. I find that even using my UDF it is much more efficient.

Oh and instead of generating the replace statement by hand use this:

-- Code Generator for expression
DECLARE @x  INT,
    @c  CHAR(1),
    @sql    VARCHAR(8000)
SET @x = 0
SET @sql = '@str' -- actual variable/column you want to replace
WHILE @x < 26
BEGIN
    SET @c = CHAR(ASCII('a') + @x)
    SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+  ''', '' ' + UPPER(@c) + ''')'
    SET @x = @x + 1
END
PRINT @sql

Anyway it depends on the number of rows. I wish you could just do s/\b([a-z])/uc $1/, but oh well we work with the tools we have.

NOTE you would have to use this as you would have to use it as....SELECT dbo.ProperCase(LOWER(column)) since the column is in uppercase. It actually works pretty fast on my table of 5,000 entries (not even one second) even with the lower.

In response to the flurry of comments regarding internationalization I present the following implementation that handles every ascii character relying only on SQL Server's Implementation of upper and lower. Remember, the variables we are using here are VARCHAR which means that they can only hold ASCII values. In order to use further international alphabets, you have to use NVARCHAR. The logic would be similar but you would need to use UNICODE and NCHAR in place of ASCII AND CHAR and the replace statement would be much more huge....

-- Code Generator for expression
DECLARE @x  INT,
    @c  CHAR(1),
    @sql    VARCHAR(8000),
    @count  INT
SEt @x = 0
SET @count = 0
SET @sql = '@str' -- actual variable you want to replace
WHILE @x < 256
BEGIN
    SET @c = CHAR(@x)
    -- Only generate replacement expression for characters where upper and lowercase differ
    IF @x = ASCII(LOWER(@c)) AND @x != ASCII(UPPER(@c))
    BEGIN
        SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+  ''', '' ' + UPPER(@c) + ''')'
        SET @count = @count + 1
    END
    SET @x = @x + 1
END
PRINT @sql
PRINT 'Total characters substituted: ' + CONVERT(VARCHAR(255), @count)

Basically the premise of the my method is trading pre-computing for efficiency. The full ASCII implementation is as follows:

IF OBJECT_ID('dbo.ProperCase') IS NOT NULL
    DROP FUNCTION dbo.ProperCase
GO
CREATE FUNCTION dbo.PROPERCASE (
    @str VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
    SET @str = ' ' + @str
SET @str =     REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z'), ' š', ' Š'), ' œ', ' Œ'), ' ž', ' Ž'), ' à', ' À'), ' á', ' Á'), ' â', ' Â'), ' ã', ' Ã'), ' ä', ' Ä'), ' å', ' Å'), ' æ', ' Æ'), ' ç', ' Ç'), ' è', ' È'), ' é', ' É'), ' ê', ' Ê'), ' ë', ' Ë'), ' ì', ' Ì'), ' í', ' Í'), ' î', ' Î'), ' ï', ' Ï'), ' ð', ' Ð'), ' ñ', ' Ñ'), ' ò', ' Ò'), ' ó', ' Ó'), ' ô', ' Ô'), ' õ', ' Õ'), ' ö', ' Ö'), ' ø', ' Ø'), ' ù', ' Ù'), ' ú', ' Ú'), ' û', ' Û'), ' ü', ' Ü'), ' ý', ' Ý'), ' þ', ' Þ'), ' ÿ', ' Ÿ')
    RETURN RIGHT(@str, LEN(@str) - 1)
END
GO

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.


See also How can I add to List<? extends Number> data structures?

How to get .app file of a xcode application

  1. xCode window tab
  2. Organizer
  3. Right click to the archive you want to get app
  4. Show in finder
  5. Right click to (ProductName….). xcarchive file
  6. Show package contents
  7. Products
  8. Applications

Finally - THERE IS YOUR .APP PROJECT FILE !

How do I escape a single quote in SQL Server?

Double quotes option helped me

SET QUOTED_IDENTIFIER OFF;
insert into my_table values("hi, my name's tim.");
SET QUOTED_IDENTIFIER ON;

Store query result in a variable using in PL/pgSQL

Create Learning Table:

CREATE TABLE "public"."learning" (
    "api_id" int4 DEFAULT nextval('share_api_api_id_seq'::regclass) NOT NULL,
    "title" varchar(255) COLLATE "default"
);

Insert Data Learning Table:

INSERT INTO "public"."learning" VALUES ('1', 'Google AI-01');
INSERT INTO "public"."learning" VALUES ('2', 'Google AI-02');
INSERT INTO "public"."learning" VALUES ('3', 'Google AI-01');

Step: 01

CREATE OR REPLACE FUNCTION get_all (pattern VARCHAR) RETURNS TABLE (
        learn_id INT,
        learn_title VARCHAR
) AS $$
BEGIN
    RETURN QUERY SELECT
        api_id,
        title
    FROM
        learning
    WHERE
        title = pattern ;
END ; $$ LANGUAGE 'plpgsql';

Step: 02

SELECT * FROM get_all('Google AI-01');

Step: 03

DROP FUNCTION get_all();

Demo: enter image description here

CSS-Only Scrollable Table with fixed headers

This answer will be used as a placeholder for the not fully supported position: sticky and will be updated over time. It is currently advised to not use the native implementation of this in a production environment.

See this for the current support: https://caniuse.com/#feat=css-sticky


Use of position: sticky

An alternative answer would be using position: sticky. As described by W3C:

A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.

This described exactly the behavior of a relative static header. It would be easy to assign this to the <thead> or the first <tr> HTML-tag, as this should be supported according to W3C. However, both Chrome, IE and Edge have problems assigning a sticky position property to these tags. There also seems to be no priority in solving this at the moment.

What does seem to work for a table element is assigning the sticky property to a table-cell. In this case the <th> cells.

Because a table is not a block-element that respects the static size you assign to it, it is best to use a wrapper element to define the scroll-overflow.

The code

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  height: 150px;_x000D_
  overflow: auto_x000D_
}_x000D_
_x000D_
table th {_x000D_
  position: -webkit-sticky;_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
_x000D_
/* == Just general styling, not relevant :) == */_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th {_x000D_
  background-color: #1976D2;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  padding: 1em .5em;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
  color: #212121;_x000D_
}_x000D_
_x000D_
table tr:nth-child(odd) {_x000D_
  background-color: #BBDEFB;_x000D_
}
_x000D_
<div>_x000D_
  <table border="0">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>head1</th>_x000D_
        <th>head2</th>_x000D_
        <th>head3</th>_x000D_
        <th>head4</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tr>_x000D_
      <td>row 1, cell 1</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this example I use a simple <div> wrapper to define the scroll-overflow done with a static height of 150px. This can of course be any size. Now that the scrolling box has been defined, the sticky <th> elements will corespondent "to the nearest ancestor with a scrolling box", which is the div-wrapper.


Use of a position: sticky polyfill

Non-supported devices can make use of a polyfill, which implements the behavior through code. An example is stickybits, which resembles the same behavior as the browser's implemented position: sticky.

Example with polyfill: http://jsfiddle.net/7UZA4/6957/

Testing socket connection in Python

You should really post:

  1. The complete source code of your example
  2. The actual result of it, not a summary

Here is my code, which works:

import socket, sys

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

(family, socktype, proto, garbage, address) = \
         socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)

try:
    s.connect(address) 
except Exception, e:
    alert("Something's wrong with %s. Exception type is %s" % (address, e))

When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:

Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')

How can I compare a date and a datetime in Python?

Use the .date() method to convert a datetime to a date:

if item_date.date() > from_date:

Alternatively, you could use datetime.today() instead of date.today(). You could use

from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)

to eliminate the time part afterwards.

Is there a way to get colored text in GitHubflavored Markdown?

You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:

```diff
+ this text is highlighted in green
- this text is highlighted in red
```

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

Initialize 2D array

Shorter way is do it as follows:

private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

How to properly export an ES6 class in Node 4?

Several of the other answers come close, but honestly, I think you're better off going with the cleanest, simplest syntax. The OP requested a means of exporting a class in ES6 / ES2015. I don't think you can get much cleaner than this:

'use strict';

export default class ClassName {
  constructor () {
  }
}

SQL Server - NOT IN

One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

Here are some examples for insert ... on conflict ... (pg 9.5+) :

  • Insert, on conflict - do nothing.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict do nothing;`  
    
  • Insert, on conflict - do update, specify conflict target via column.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict(id)
    do update set name = 'new_name', size = 3;  
    
  • Insert, on conflict - do update, specify conflict target via constraint name.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict on constraint dummy_pkey
    do update set name = 'new_name', size = 4;
    

How to get a list of all files that changed between two Git commits?

  • To list all unstaged tracked changed files:

    git diff --name-only
    
  • To list all staged tracked changed files:

    git diff --name-only --staged
    
  • To list all staged and unstaged tracked changed files:

    { git diff --name-only ; git diff --name-only --staged ; } | sort | uniq
    
  • To list all untracked files (the ones listed by git status, so not including any ignored files):

    git ls-files --other --exclude-standard
    

If you're using this in a shell script, and you want to programmatically check if these commands returned anything, you'll be interested in git diff's --exit-code option.

IntelliJ Organize Imports

ALT+ENTER was far from eclipse habit ,in IDEA for me mouse over did not work , so in setting>IDESetting>Keymap>Show intention actions and quick-fixes I changed it to mouse left click , It did not support mouse over! but mouse left click was OK and closest to my intention.

I need an unordered list without any bullets

You can remove bullets by setting the list-style-type to none on the CSS for the parent element (typically a <ul>), for example:

ul {
  list-style-type: none;
}

You might also want to add padding: 0 and margin: 0 to that if you want to remove indentation as well.

See Listutorial for a great walkthrough of list formatting techniques.

Create a shortcut on Desktop

With additional options such as hotkey, description etc.

At first, Project > Add Reference > COM > Windows Script Host Object Model.

using IWshRuntimeLibrary;

private void CreateShortcut()
{
  object shDesktop = (object)"Desktop";
  WshShell shell = new WshShell();
  string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\Notepad.lnk";
  IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
  shortcut.Description = "New shortcut for a Notepad";
  shortcut.Hotkey = "Ctrl+Shift+N";
  shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
  shortcut.Save();
}

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

Search  = ^([A-Za-z0-9]+)$
Replace = able:"\1"

Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

Search = ^(.+)$

^ points to the start of the line.
$ points to the end of the line.

\1 will be the source match within the parentheses.

What does "\r" do in the following script?

'\r' means 'carriage return' and it is similar to '\n' which means 'line break' or more commonly 'new line'

in the old days of typewriters, you would have to move the carriage that writes back to the start of the line, and move the line down in order to write onto the next line.

in the modern computer era we still have this functionality for multiple reasons. but mostly we use only '\n' and automatically assume that we want to start writing from the start of the line, since it would not make much sense otherwise.

however, there are some times when we want to use JUST the '\r' and that would be if i want to write something to an output, and the instead of going down to a new line and writing something else, i want to write something over what i already wrote, this is how many programs in linux or in windows command line are able to have 'progress' information that changes on the same line.

nowadays most systems use only the '\n' to denote a newline. but some systems use both together.

you can see examples of this given in some of the other answers, but the most common are:

  • windows ends lines with '\r\n'
  • mac ends lines with '\r'
  • unix/linux use '\n'

and some other programs also have specific uses for them.

for more information about the history of these characters

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

There is no other way to do it other than what you described. Think about it - how can anyone know what classes extend ClassX without scanning each class on the classpath?

Eclipse can only tell you about the super and subclasses in what seems to be an "efficient" amount of time because it already has all of the type data loaded at the point where you press the "Display in Type Hierarchy" button (since it is constantly compiling your classes, knows about everything on the classpath, etc).

Convert nullable bool? to bool

You can use the null-coalescing operator: x ?? something, where something is a boolean value that you want to use if x is null.

Example:

bool? myBool = null;
bool newBool = myBool ?? false;

newBool will be false.

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

I had a similar problem and resolved it by removing any copies/backups of the .cs file from the directory.

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

laravel-5 passing variable to JavaScript

Try this - https://github.com/laracasts/PHP-Vars-To-Js-Transformer Is simple way to append PHP variables to Javascript.

Including one C source file in another?

is it ok? yes, it will compile

is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file

How to force open links in Chrome not download them?

To open docs automatically in Chrome without them being saved;

  1. Go to the the three vertical dots on your top far right corner in Chrome.

  2. Scroll down to Settings and click.

  3. Scroll down to Show advance settings...

  4. Scroll down to Downloads under Download location: click the Change button and chose tmp folder. Then just close the screen.

  5. Click on any attachments and a small box to the left will appear, it should automatically open if you click on it.

  6. When the bottom left box appears it will contain an arrow; click on it and choose the option "Always open files of this type". Going forward it will open the file instantly instead of the small box appearing to the left and you having to click on it to open. You will have to do it just once for various files such PDF, Excel 2010, Excel 2013 Word, ect.

Show two digits after decimal point in c++

Using header file stdio.h you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().

It simply printf specific digits after decimal point.

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
   double total=100;
   printf("%.2lf",total);//this prints 100.00 like as C
}

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case, I had inserted [(ngModel)] on label rather than input. There is also a caveat, I tried running after correctly the above error in the specified line but the error wouldn't go. If there are other places where you have committed the same mistake, it still throws you the same error at the same line

Git stash pop- needs merge, unable to refresh index

git reset if you don't want to commit these changes.

Select elements by attribute in CSS

    [data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

redirect while passing arguments

I found that none of the answers here applied to my specific use case, so I thought I would share my solution.

I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:

/app/4903294/my-great-car?email=coolguy%40gmail.com to

/public/4903294/my-great-car?email=coolguy%40gmail.com

Here's the solution that worked for me.

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))

Hope this helps someone!

RestSharp JSON Parameter Posting

This is what worked for me, for my case it was a post for login request :

var client = new RestClient("http://www.example.com/1/2");
var request = new RestRequest();

request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", body , ParameterType.RequestBody);

var response = client.Execute(request);
var content = response.Content; // raw content as string  

body :

{
  "userId":"[email protected]" ,
  "password":"welcome" 
}

How to create an empty R vector to add new items

In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2

For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors

How can I style an Android Switch?

It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio

A good description of all the tools are at AndroidOnRocks.com (site offline now)

However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick

How to select where ID in Array Rails ActiveRecord without exception

To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.

begin
  current_user.comments.find(ids)
rescue
  #do something in case of exception found
end

Here's more info on exceptions in ruby.

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

C++ calling base class constructors

Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

class A {..}
class B : A {...}
class C : B {...}
C c;

When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

Derived() : Base(5)
{      
}

If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

SVG fill color transparency / alpha?

To change transparency on an svg code the simplest way is to open it on any text editor and look for the style attributes. It depends on the svg creator the way the styles are displayed. As i am an Inkscape user the usual way it set the style values is through a style tag just as if it were html but using svg native attributes like fill, stroke, stroke-width, opacity and so on. opacity affects the whole svg object, or path or group in which its stated and fill-opacity, stroke-opacity will affect just the fill and the stroke transparency. That said, I have also used and tasted to just use fill and instead of using#fff use instead the rgba standard like this rgba(255, 255, 255, 1) just as in css. This works fine for must modern browsers.

Keep in mind that if you intend to further reedit your svg the best practice, in my experience, is to always keep an untouched version at hand. Inkscape is more flexible with hand changed svgs but Illustrator and CorelDraw may have issues importing and edited svg.

Example

<path style="fill:#ff0000;fill-opacity:1;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>

Example 2

<path style="fill:#ff0000;fill-opacity:.5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>

Example 3

<path style="fill:rgba(255, 0, 0, .5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>

Notice that in the last example the fill-opacity has been removed as rgba standard covers both color and alpha channel.

How to log a method's execution time exactly in milliseconds?

In Swift, I'm using:

In my Macros.swift I just added

var startTime = NSDate()
func TICK(){ startTime =  NSDate() }
func TOCK(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__){
    println("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}

you can now just call anywhere

TICK()

// your code to be tracked

TOCK()

Swift 5.0

   var startTime = NSDate()
func TICK(){ startTime =  NSDate() }
func TOCK(function: String = #function, file: String = #file, line: Int = #line){
    print("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
  • this code is based on Ron's code translate to Swift, he has the credits
  • I'm using start date at global level, any suggestion to improve are welcome

ios simulator: how to close an app

Command + shift +h Press H 2 times

Note :- Press H 2 times

Java for loop multiple variables

The for loop can only contain three parameters, you have used 4. Please restate the question, what do you want to achieve?

How to pause for specific amount of time? (Excel/VBA)

The declaration for Sleep in kernel32.dll won't work in 64-bit Excel. This would be a little more general:

#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Passing JavaScript array to PHP through jQuery $.ajax

This worked for me:

$.ajax({
    url:"../messaging/delete.php",
    type:"POST",
    data:{messages:selected},
    success:function(data){
     if(data === "done"){

     }
     info($("#notification"), data);
    },
    beforeSend:function(){
         info($("#notification"),"Deleting "+count+" messages");
    },
    error:function(jqXHR, textStatus, errorMessage){
        error($("#notification"),errorMessage);
    }
});

And this for your PHP:

$messages = $_POST['messages']
foreach($messages as $msg){
    echo $msg;
}

Is there a way to use shell_exec without waiting for the command to complete?

On Windows 2003, to call another script without waiting, I used this:

$commandString = "start /b c:\\php\\php.EXE C:\\Inetpub\\wwwroot\\mysite.com\\phpforktest.php --passmsg=$testmsg"; 
pclose(popen($commandString, 'r'));

This only works AFTER giving changing permissions on cmd.exe - add Read and Execute for IUSR_YOURMACHINE (I also set write to Deny).

How can I align two divs horizontally?

if you have two divs, you can use this to align the divs next to each other in the same row:

_x000D_
_x000D_
#keyword {_x000D_
    float:left;_x000D_
    margin-left:250px;_x000D_
    position:absolute;_x000D_
}_x000D_
_x000D_
#bar {_x000D_
    text-align:center;_x000D_
}
_x000D_
<div id="keyword">_x000D_
Keywords:_x000D_
</div>_x000D_
<div id="bar">_x000D_
    <input type = textbox   name ="keywords" value="" onSubmit="search()" maxlength=40>_x000D_
    <input type = button   name="go" Value="Go ahead and find" onClick="search()">_x000D_
</div>
_x000D_
_x000D_
_x000D_

SQL Server - stop or break execution of a SQL script

Is this a stored procedure? If so, I think you could just do a Return, such as "Return NULL";

How do I combine a background-image and CSS3 gradient on the same element?

You could use multiple background: linear-gradient(); calls, but try this:

If you want the images to be completely fused together where it doesn't look like the elements load separately due to separate HTTP requests then use this technique. Here we're loading two things on the same element that load simultaneously...

Just make sure you convert your pre-rendered 32-bit transparent png image/texture to base64 string first and use it within the background-image css call (in place of INSERTIMAGEBLOBHERE in this example).

I used this technique to fuse a wafer looking texture and other image data that's serialized with a standard rgba transparency / linear gradient css rule. Works better than layering multiple art and wasting HTTP requests which is bad for mobile. Everything is loaded client side with no file operation required, but does increase document byte size.

 div.imgDiv   {
      background: linear-gradient(to right bottom, white, rgba(255,255,255,0.95), rgba(255,255,255,0.95), rgba(255,255,255,0.9), rgba(255,255,255,0.9), rgba(255,255,255,0.85), rgba(255,255,255,0.8) );
      background-image: url("data:image/png;base64,INSERTIMAGEBLOBHERE");
 }

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had the same problem. I changed the order of the scripts in the head part, and it worked for me. Every script the plugin needs - needs to stay close.

For example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript"> 
$(document).ready(function() {
    $('#slider').cycle({
            fx: 'fade' 
        });
    });
</script>

How to rollback just one step using rake db:migrate

  try {
        $result=DB::table('users')->whereExists(function ($Query){
            $Query->where('id','<','14162756');
            $Query->whereBetween('password',[14162756,48384486]);
            $Query->whereIn('id',[3,8,12]);
        });
    }catch (\Exception $error){
        Log::error($error);
        DB::rollBack(1);
        return redirect()->route('bye');
    }

Using RegEx in SQL Server

You will have to build a CLR procedure that provides regex functionality, as this article illustrates.

Their example function uses VB.NET:

Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here  


Namespace SimpleTalk.Phil.Factor
    Public Class RegularExpressionFunctions
        'RegExIsMatch function
        <SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
        Public Shared Function RegExIsMatch( _
                                            ByVal pattern As SqlString, _
                                            ByVal input As SqlString, _
                                            ByVal Options As SqlInt32) As SqlBoolean
            If (input.IsNull OrElse pattern.IsNull) Then
                Return SqlBoolean.False
            End If
            Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
            RegExOption = Options
            Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
        End Function
    End Class      ' 
End Namespace

...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:

sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE

IF EXISTS ( SELECT   1
            FROM     sys.objects
            WHERE    object_id = OBJECT_ID(N'dbo.RegExIsMatch') ) 
   DROP FUNCTION dbo.RegExIsMatch
go

IF EXISTS ( SELECT   1
            FROM     sys.assemblies asms
            WHERE    asms.name = N'RegExFunction ' ) 
   DROP ASSEMBLY [RegExFunction]

CREATE ASSEMBLY RegExFunction 
           FROM '%FILE%'
GO

CREATE FUNCTION RegExIsMatch
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options int
   )
RETURNS BIT
AS EXTERNAL NAME 
   RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO

--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT  dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
        dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
        dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
        dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
        dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)

How do I check if a Key is pressed on C++

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews's code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()

'mvn' is not recognized as an internal or external command,

Make sure you have your maven bin directory in the path and the JAVA_HOME property set

LINQ Inner-Join vs Left-Join

I think if you want to use extension methods you need to use the GroupJoin

var query =
    people.GroupJoin(pets,
                     person => person,
                     pet => pet.Owner,
                     (person, petCollection) =>
                        new { OwnerName = person.Name,
                              Pet = PetCollection.Select( p => p.Name )
                                                 .DefaultIfEmpty() }
                    ).ToList();

You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship.

I think it's a little easier with the LINQ Query syntax

var query = (from person in context.People
             join pet in context.Pets on person equals pet.Owner
             into tempPets
             from pets in tempPets.DefaultIfEmpty()
             select new { OwnerName = person.Name, Pet = pets.Name })
            .ToList();

How to get the instance id from within an ec2 instance?

See this post - note that the IP address in the URL given is constant (which confused me at first), but the data returned is specific to your instance.

How can I start PostgreSQL server on Mac OS X?

To start the PostgreSQL server:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

To end the PostgreSQL server:

pg_ctl -D /usr/local/var/postgres stop -s -m fast

You can also create an alias via CLI to make it easier:

alias pg-start='pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start'
alias pg-stop='pg_ctl -D /usr/local/var/postgres stop -s -m fast'

With these you can just type "pg-start" to start PostgreSQL and "pg-stop" to shut it down.

How to set timer in android?

I use this way:

String[] array={
       "man","for","think"
}; int j;

then below the onCreate

TextView t = findViewById(R.id.textView);

    new CountDownTimer(5000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {}

        @Override
        public void onFinish() {
            t.setText("I "+array[j] +" You");
            j++;
            if(j== array.length-1) j=0;
            start();
        }
    }.start();

it's easy way to solve this problem.

How to download and save a file from Internet using Java?

When using Java 7+ use the following method to download a file from the Internet and save it to some directory:

private static Path download(String sourceURL, String targetDirectory) throws IOException
{
    URL url = new URL(sourceURL);
    String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
    Path targetPath = new File(targetDirectory + File.separator + fileName).toPath();
    Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

    return targetPath;
}

Documentation here.

Downloading an entire S3 bucket?

AWS CLI is the best option to download an entire S3 bucket locally.

  1. Install AWS CLI.

  2. Configure AWS CLI for using default security credentials and default AWS Region.

  3. To download the entire S3 bucket use command

    aws s3 sync s3://yourbucketname localpath

Reference to use AWS cli for different AWS services: https://docs.aws.amazon.com/cli/latest/reference/

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

Bad Request, Your browser sent a request that this server could not understand

In my case is a cookie-related issue, I had many cookies with value extremely big, and that was causing the problem.

You can replicate this issue here on stackoverflow.com, just open the console and type this:

[ ...Array(5) ].forEach((i, idx) => {
    document.cookie = `stackoverflow_cookie${idx}=${'a'.repeat(4000)}`;
});

What is that?

I am creating 5 cookies with a string of length or value of 4000 bytes; then reload the page and you will see the same issue.

I tried it on google.com and you'll get the error but they automatically clear the cookies for you, which is a nice fallback to start fresh.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Neither one of the solutions worked form me. The only one that worked for me in Spring form is:

action="./upload?${_csrf.parameterName}=${_csrf.token}"

REPLACED WITH:

action="./upload?_csrf=${_csrf.token}"

(Spring 5 with enabled csrf in java configuration)

What is memoization and how can I use it in Python?

Just wanted to add to the answers already provided, the Python decorator library has some simple yet useful implementations that can also memoize "unhashable types", unlike functools.lru_cache.

How to add a RequiredFieldValidator to DropDownList control?

For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />

Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.

If databinding you will need to insert the "Please select" value afterwards as follows

this.ddl1.Items.Insert(0, "Please select");

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Encoding targetEncoding = Encoding.GetEncoding(1252);
// Encode a string into an array of bytes.
Byte[] encodedBytes = targetEncoding.GetBytes(utfString);
// Show the encoded byte values.
Console.WriteLine("Encoded bytes: " + BitConverter.ToString(encodedBytes));
// Decode the byte array back to a string.
String decodedString = Encoding.Default.GetString(encodedBytes);

removing bold styling from part of a header

<h1 style="font-weight: normal;"></h1>

try this?

What is the correct syntax for 'else if'?

In python "else if" is spelled "elif".
Also, you need a colon after the elif and the else.

Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).

So your code should read:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

function(input('input:'))

How to tell git to use the correct identity (name and email) for a given project?

One solution is to run manually a shell function that sets my environment to work or personal, but I am pretty sure that I will often forget to switch to the correct identity resulting in committing under the wrong identity.

That was exactly my problem. I have written a hook script which warns you if you have any github remote and not defined a local username.

Here's how you set it up:

  1. Create a directory to hold the global hook

    mkdir -p ~/.git-templates/hooks

  2. Tell git to copy everything in ~/.git-templates to your per-project .git directory when you run git init or clone

    git config --global init.templatedir '~/.git-templates'

  3. And now copy the following lines to ~/.git-templates/hooks/pre-commit and make the file executable (don't forget this otherwise git won't execute it!)

#!/bin/bash

RED='\033[0;31m' # red color
NC='\033[0m' # no color

GITHUB_REMOTE=$(git remote -v | grep github.com)
LOCAL_USERNAME=$(git config --local user.name)

if [ -n "$GITHUB_REMOTE" ] && [ -z "$LOCAL_USERNAME" ]; then
    printf "\n${RED}ATTENTION: At least one Github remote repository is configured, but no local username. "
    printf "Please define a local username that matches your Github account.${NC} [pre-commit hook]\n\n"
    exit 1
fi

If you use other hosts for your private repositories you have to replace github.com according to your needs.

Now every time you do a git init or git clone git will copy this script to the repository and executes it before any commit is done. If you have not set a local username it will output a warning and won't let you commit.

What is the regex for "Any positive integer, excluding 0"

This should only allow decimals > 0

^([0-9]\.\d+)|([1-9]\d*\.?\d*)$

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

How do I disable a jquery-ui draggable?

Change draggable attribute from

<span draggable="true">Label</span>

to

<span draggable="false">Label</span>

application/x-www-form-urlencoded or multipart/form-data?

If you need to use Content-Type=x-www-urlencoded-form then DO NOT use FormDataCollection as parameter: In asp.net Core 2+ FormDataCollection has no default constructors which is required by Formatters. Use IFormCollection instead:

 public IActionResult Search([FromForm]IFormCollection type)
    {
        return Ok();
    }

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Using CSS td width absolute, position

This may not be what you want to hear, but display: table-cell does not respect width and will be collapsed based on the width of the entire table. You can get around this easily just by having a display: block element inside of the table cell itself whose width you specify, e.g

<td><div style="width: 300px;">wide</div></td>

This shouldn't make much of a difference if the <table> itself is position: fixed or absolute because the position of the cells are all static relative to the table.

http://jsfiddle.net/ExplosionPIlls/Mkq8L/4/

EDIT: I can't take credit, but as the comments say you can just use min-width instead of width on the table cell instead.

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.