Programs & Examples On #Invokelater

A method provided by the SwingUtilities class in Java that executes asynchronously code on the AWT event dispatching thread in order to correctly manipulate UI elements.

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

I had the same problem and I Changed this

<configuration>
    <source>1.7</source>
    <target>1.7</target>
 </configuration>

here 1.7 is my JDK version.it was solved.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

Displaying Image in Java

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DisplayImage {

    public static void main(String avg[]) throws IOException
    {
        DisplayImage abc=new DisplayImage();
    }

    public DisplayImage() throws IOException
    {
        BufferedImage img=ImageIO.read(new File("f://images.jpg"));
        ImageIcon icon=new ImageIcon(img);
        JFrame frame=new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(200,300);
        JLabel lbl=new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

How to draw in JPanel? (Swing/graphics Java)

Here is a simple example. I suppose it will be easy to understand:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

And the output looks like this:

Output

How to set border on jPanel?

JPanel jPanel = new JPanel();

jPanel.setBorder(BorderFactory.createLineBorder(Color.black));

Here not only jPanel, you can add border to any Jcomponent

What does it mean: The serializable class does not declare a static final serialVersionUID field?

From the javadoc:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

Fastest way to download a GitHub project

Use

git clone https://github.com/<path>/repository
or
git clone https://github.com/<path>/<master>.git

examples

git clone https://github.com/spring-projects/spring-data-graph-examples
git clone https://github.com/spring-projects/spring-data-graph-examples.git

Visual Studio replace tab with 4 spaces?

First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces

How can I show the table structure in SQL Server query?

I was trying 'DESC table_name' but then this worked for me in psql:

select * 
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='table_name'; 

Angular redirect to login page

1. Create a guard as seen below. 2. Install ngx-cookie-service to get cookies returned by external SSO. 3. Create ssoPath in environment.ts (SSO Login redirection). 4. Get the state.url and use encodeURIComponent.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from 
  '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '../../../environments/environment.prod';

@Injectable()
export class AuthGuardService implements CanActivate {
  private returnUrl: string;
  constructor(private _router: Router, private cookie: CookieService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.cookie.get('MasterSignOn')) {
      return true;
    } else {
      let uri = window.location.origin + '/#' + state.url;
      this.returnUrl = encodeURIComponent(uri);      
      window.location.href = environment.ssoPath +  this.returnUrl ;   
      return false;      
    }
  }
}

Difference between application/x-javascript and text/javascript content types

Use type="application/javascript"

In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.

http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Use "application/javascript", because "text/javascript" is obsolete:

RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt

  1. Deployed Scripting Media Types and Compatibility

    Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:

    +-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+

Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.

x-javascript is experimental, don't use it.

Set inputType for an EditText Programmatically?

This may be of help to others like me who wanted to toggle between password and free-text mode. I tried using the input methods suggested but it only worked in one direction. I could go from password to text but then I could not revert. For those trying to handle a toggle (eg a show Password check box) use

       @Override
        public void onClick(View v)
        {
            if(check.isChecked())
            {
                edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                Log.i(TAG, "Show password");
            }
            else
            {
                edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                Log.i(TAG, "Hide password");
            }
        }

I have to credit this for the solution. Wish I had found that a few hours ago!

Using the last-child selector

If you think you can use Javascript, then since jQuery support last-child, you can use jQuery's css method and the good thing it will support almost all the browsers

Example Code:

$(function(){
   $("#nav li:last-child").css("border-bottom","1px solid #b5b5b5")
})

You can find more info about here : http://api.jquery.com/css/#css2

YAML Multi-Line Arrays

If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]

How to find sitemap.xml path on websites?

I don't think there's a standard as to the location of the sitemap. That's the reason why you should specify an arbitrary URL to your sitemap when you're adding one using Google's Webmaster Tools.

How to convert string to integer in UNIX

The standard solution:

 expr $d1 - $d2

You can also do:

echo $(( d1 - d2 ))

but beware that this will treat 07 as an octal number! (so 07 is the same as 7, but 010 is different than 10).

Regex - Should hyphens be escaped?

Typically you would always put the hyphen first in the [] match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]

Using getline() in C++

If you're using getline() after cin >> something, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore().

It would be something like this:

string messageVar;
cout << "Type your message: ";
cin.ignore(); 
getline(cin, messageVar);

This happens because the >> operator leaves a newline \n character in the input buffer. This may become a problem when you do unformatted input, like getline(), which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n that was left hanging there in your previous operation.

First letter capitalization for EditText

I encountered the same problem, just sharing what I found out. Might help you and others...

Try this on your layout.add the line below in your EditText.

android:inputType="textCapWords|textCapSentences"

works fine on me.. hope it works also on you...

How can I make a "color map" plot in matlab?

gevang's answer is great. There's another way as well to do this directly by using pcolor. Code:

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure;
subplot(1,3,1);
pcolor(X,Y,Z); 
subplot(1,3,2);
pcolor(X,Y,Z); shading flat;
subplot(1,3,3);
pcolor(X,Y,Z); shading interp;

Output:

enter image description here

Also, pcolor is flat too, as show here (pcolor is the 2d base; the 3d figure above it is generated using mesh):

enter image description here

How to open google chrome from terminal?

I'm not sure how extensively you've searched, but this seems to be similar to what you're searching for:

https://apple.stackexchange.com/questions/83630/create-a-terminal-command-to-open-file-with-chrome

(I just assumed you're using Mac since you used the word "terminal")

Passing Objects By Reference or Value in C#

I guess its clearer when you do it like this. I recommend downloading LinqPad to test things like this.

void Main()
{
    var Person = new Person(){FirstName = "Egli", LastName = "Becerra"};

    //Will update egli
    WontUpdate(Person);
    Console.WriteLine("WontUpdate");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateImplicitly(Person);
    Console.WriteLine("UpdateImplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateExplicitly(ref Person);
    Console.WriteLine("UpdateExplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
}

//Class to test
public class Person{
    public string FirstName {get; set;}
    public string LastName {get; set;}

    public string printName(){
        return $"First name: {FirstName} Last name:{LastName}";
    }
}

public static void WontUpdate(Person p)
{
    //New instance does jack...
    var newP = new Person(){FirstName = p.FirstName, LastName = p.LastName};
    newP.FirstName = "Favio";
    newP.LastName = "Becerra";
}

public static void UpdateImplicitly(Person p)
{
    //Passing by reference implicitly
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

public static void UpdateExplicitly(ref Person p)
{
    //Again passing by reference explicitly (reduntant)
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

And that should output

WontUpdate

First name: Egli, Last name: Becerra

UpdateImplicitly

First name: Favio, Last name: Becerra

UpdateExplicitly

First name: Favio, Last name: Becerra

How to get config parameters in Symfony2 Twig Templates

The above given ans are correct and works fine. I used in a different way.

config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: app.yml }
    - { resource: app_twig.yml }

app.yml

parameters:
  app.version:           1.0.1

app_twig.yml

twig:
  globals:
    version: %app.version%

Inside controller:

$application_version = $this->container->getParameter('app.version');
// Here using app.yml

Inside template/twig file:

Project version {{ version }}!
{#  Here using app_twig.yml content.  #}
{#  Because in controller we used $application_version  #}

To use controller output:

Controller:

public function indexAction() {
        $application_version = $this->container->getParameter('app.version');
        return array('app_version' => $application_version);
    }

template/twig file :

Project version {{ app_version }}

I mentioned the different for better understand.

How to reference image resources in XAML?

If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:

<Image Source="/Icons/play_small.png" />

That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:

var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;

var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();

this.image1.Source = bitmapImage;

Display the binary representation of a number in C?

This code should handle your needs up to 64 bits.



char* pBinFill(long int x,char *so, char fillChar); // version with fill
char* pBin(long int x, char *so);                    // version without fill
#define width 64

char* pBin(long int x,char *so)
{
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 { // fill in array from right to left
  s[i--]=(x & 1) ? '1':'0';  // determine bit
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 i++;   // point to last valid character
 sprintf(so,"%s",s+i); // stick it in the temp string string
 return so;
}

char* pBinFill(long int x,char *so, char fillChar)
{ // fill in array from right to left
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 {
  s[i--]=(x & 1) ? '1':'0';
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 while(i>=0) s[i--]=fillChar;    // fill with fillChar 
 sprintf(so,"%s",s);
 return so;
}

void test()
{
 char so[width+1]; // working buffer for pBin
 long int   val=1;
 do
 {
   printf("%ld =\t\t%#lx =\t\t0b%s\n",val,val,pBinFill(val,so,0));
   val*=11; // generate test data
 } while (val < 100000000);
}

Output:
00000001 = 0x000001 =   0b00000000000000000000000000000001
00000011 = 0x00000b =   0b00000000000000000000000000001011
00000121 = 0x000079 =   0b00000000000000000000000001111001
00001331 = 0x000533 =   0b00000000000000000000010100110011
00014641 = 0x003931 =   0b00000000000000000011100100110001
00161051 = 0x02751b =   0b00000000000000100111010100011011
01771561 = 0x1b0829 =   0b00000000000110110000100000101001
19487171 = 0x12959c3 =  0b00000001001010010101100111000011

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I had similar issue on Windows 7. At first I setup M2, M2_HOME under User variable but when I echoed %PATH% , I did not see maven bin directory listed under PATH. Then I setup M2, M2_HOME under system variable and it worked.

Generating an array of letters in the alphabet

Surprised no one has suggested a yield solution:

public static IEnumerable<char> Alphabet()
{
    for (char letter = 'A'; letter <= 'Z'; letter++)
    {
        yield return letter;
    }
}

Example:

foreach (var c in Alphabet())
{
    Console.Write(c);
}

How do I create my own URL protocol? (e.g. so://...)

The portion with the HTTP://,FTP://, etc are called URI Schemes

You can register your own through the registry.

HKEY_CLASSES_ROOT/
  your-protocol-name/
    (Default)    "URL:your-protocol-name Protocol"
    URL Protocol ""
    shell/
      open/
        command/
          (Default) PathToExecutable

Sources: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml, http://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx

CSS: Auto resize div to fit container width

I have updated your jsfiddle and here is CSS changes you need to do:

#content
{
    min-width:700px;
    margin-right: -210px;
    width:100%;
    float:left;
    background-color:AppWorkspace;
}

How can I make Java print quotes, like "Hello"?

There are two easy methods:

  1. Use backslash \ before double quotes.
  2. Use two single quotes instead of double quotes like '' instead of "

For example:

System.out.println("\"Hello\"");                       
System.out.println("''Hello''"); 

How to select a node of treeview programmatically in c#?

TreeViewItem tempItem = new TreeViewItem();
TreeViewItem tempItem1 = new TreeViewItem(); 
tempItem =  (TreeViewItem) treeView1.Items.GetItemAt(0);    // Selecting the first of the top level nodes
tempItem1 = (TreeViewItem)tempItem.Items.GetItemAt(0);      // Selecting the first child of the first first level node
SelectedCategoryHeaderString = tempItem.Header.ToString();  // gets the header for the first top level node
SelectedCategoryHeaderString = tempItem1.Header.ToString(); // gets the header for the first child node of the first top level node
tempItem.IsExpanded = true;         //  will expand the first node

How to copy sheets to another workbook using vba?

try this one

Sub Get_Data_From_File()

     'Note: In the Regional Project that's coming up we learn how to import data from multiple Excel workbooks
    ' Also see BONUS sub procedure below (Bonus_Get_Data_From_File_InputBox()) that expands on this by inlcuding an input box
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
         'copy data from A1 to E20 from first sheet
        OpenBook.Sheets(1).Range("A1:E20").Copy
        ThisWorkbook.Worksheets("SelectFile").Range("A10").PasteSpecial xlPasteValues
        OpenBook.Close False
        
    End If
    Application.ScreenUpdating = True
End Sub

or this one:

Get_Data_From_File_InputBox()

Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim ShName As String
Dim Sh As Worksheet
On Error GoTo Handle:

FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*.xls*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False

If FileToOpen <> False Then
    Set OpenBook = Application.Workbooks.Open(FileToOpen)
    ShName = Application.InputBox("Enter the sheet name to copy", "Enter the sheet name to copy")
    For Each Sh In OpenBook.Worksheets
        If UCase(Sh.Name) Like "*" & UCase(ShName) & "*" Then
            ShName = Sh.Name
        End If
    Next Sh

    'copy data from the specified sheet to this workbook - updae range as you see fit
    OpenBook.Sheets(ShName).Range("A1:CF1100").Copy
    ThisWorkbook.ActiveSheet.Range("A10").PasteSpecial xlPasteValues
    OpenBook.Close False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub

Handle: If Err.Number = 9 Then MsgBox "The sheet name does not exist. Please check spelling" Else MsgBox "An error has occurred." End If OpenBook.Close False Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub

both work as

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

How can I repeat a character in Bash?

for i in {1..100}
do
  echo -n '='
done
echo

Java generics - get class?

Short answer: You can't.

Long answer:

Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:

public class Foo<T> 
{
    private Class<T> type;

    public Foo(Class<T> type) { this.type = type; } 
}

Usage example:

Foo<Integer> test = new Foo<Integer>(Integer.class);

How do I create a MessageBox in C#?

I got the same error 'System.Windows.Forms.MessageBox' is a 'type' but is used like a 'variable', even if using:

MessageBox.Show("Hello, World!");

I guess my initial attempts with invalid syntax caused some kind of bug and I ended up fixing it by adding a space between "MessageBox.Show" and the brackets ():

MessageBox.Show ("Hello, World!");

Now using the original syntax without the extra space works again:

MessageBox.Show("Hello, World!");

How can I debug a Perl script?

I would also recommend using the Perl debugger.

However, since you asked about something like shell's -x have a look at the Devel::Trace module which does something similar.

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

How to select records without duplicate on just one field in SQL?

In MySQL a special column function GROUP_CONCAT can be used:

SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'computers' AND
    TABLE_NAME='Laptop' AND
    COLUMN_NAME NOT IN ('code')
ORDER BY ORDINAL_POSITION;

It should be mentioned that the information schema in MySQL covers all database server, not certain databases. That is why if different databases contains tables with identical names, search condition of the WHERE clause should specify the schema name: TABLE_SCHEMA='computers'.

Strings are concatenated with the CONCAT function in MySQL. The final solution of our problem can be expressed in MySQL as:

SELECT CONCAT('SELECT ',
(SELECT GROUP_CONCAT(COLUMN_NAME)
 FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_SCHEMA='computers' AND
    TABLE_NAME='Laptop' AND
        COLUMN_NAME NOT IN ('code')
 ORDER BY ORDINAL_POSITION
), ' FROM Laptop');

http://www.sql-ex.ru/help/select20.php

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

OpenCV - Saving images to a particular folder of choice

The solution provided by ebeneditos works perfectly.

But if you have cv2.imwrite() in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite() individually.

As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()

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

Now if you want to modify the path, you just have to change the path variable.

Edited based on solution provided by Kallz

SQL like search string starts with

You need to use the wildcard % :

SELECT * from games WHERE (lower(title) LIKE 'age of empires III%');

Abstraction vs Encapsulation in Java

In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.

Get distance between two points in canvas

The distance between two coordinates x and y! x1 and y1 is the first point/position, x2 and y2 is the second point/position!

_x000D_
_x000D_
function diff (num1, num2) {_x000D_
  if (num1 > num2) {_x000D_
    return (num1 - num2);_x000D_
  } else {_x000D_
    return (num2 - num1);_x000D_
  }_x000D_
};_x000D_
_x000D_
function dist (x1, y1, x2, y2) {_x000D_
  var deltaX = diff(x1, x2);_x000D_
  var deltaY = diff(y1, y2);_x000D_
  var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));_x000D_
  return (dist);_x000D_
};
_x000D_
_x000D_
_x000D_

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

One other cause may be using lombok.

@Builder - causes to save Collections.emptyList() even if you say .myCollection(new ArrayList());

@Singular - ignores the class level defaults and leaves field null even if the class field was declared as myCollection = new ArrayList()

My 2 cents, just spent 2 hours with the same :)

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.

The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME). The other is a a user-defined exception thrown when the foreign key between EMP(MGR) and EMP(EMPNO) is violated (because a manager must be an existing employee).

create or replace procedure new_emp
    ( p_name in emp.ename%type
      , p_sal in emp.sal%type
      , p_job in emp.job%type
      , p_dept in emp.deptno%type
      , p_mgr in emp.mgr%type 
      , p_hired in emp.hiredate%type := sysdate )
is
    invalid_manager exception;
    PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
    dummy varchar2(1);
begin
    -- check hiredate is valid
    if trunc(p_hired) > trunc(sysdate) 
    then
        raise_application_error
            (-20000
             , 'NEW_EMP::hiredate cannot be in the future'); 
    end if;

    insert into emp
        ( ename
          , sal
          , job
          , deptno
          , mgr 
          , hiredate )
    values      
        ( p_name
          , p_sal
          , p_job
          , p_dept
          , p_mgr 
          , trunc(p_hired) );
exception
    when dup_val_on_index then
        raise_application_error
            (-20001
             , 'NEW_EMP::employee called '||p_name||' already exists'
             , true); 
    when invalid_manager then
        raise_application_error
            (-20002
             , 'NEW_EMP::'||p_mgr ||' is not a valid manager'); 

end;
/

How it looks:

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;

*
ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;

*
ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1


SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)

PL/SQL procedure successfully completed.

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;

*
ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1

Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.

There is more useful information in the PL/SQL User's Guide.

Argparse: Required arguments listed under "optional arguments"?

Building off of @Karl Rosaen

parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

Count all duplicates of each value

SELECT   col,
         COUNT(dupe_col) AS dupe_cnt
FROM     TABLE
GROUP BY col
HAVING   COUNT(dupe_col) > 1
ORDER BY COUNT(dupe_col) DESC

How do I return a char array from a function?

Best as an out parameter:

void testfunc(char* outStr){
  char str[10];
  for(int i=0; i < 10; ++i){
    outStr[i] = str[i];
  }
}

Called with

int main(){
  char myStr[10];
  testfunc(myStr);
  // myStr is now filled
}

splitting a string into an array in C++ without using vector

It is possible to turn the string into a stream by using the std::stringstream class (its constructor takes a string as parameter). Once it's built, you can use the >> operator on it (like on regular file based streams), which will extract, or tokenize word from it:

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    string line = "test one two three.";
    string arr[4];
    int i = 0;
    stringstream ssin(line);
    while (ssin.good() && i < 4){
        ssin >> arr[i];
        ++i;
    }
    for(i = 0; i < 4; i++){
        cout << arr[i] << endl;
    }
}

Oracle JDBC intermittent Connection Issue

I was facing exactly the same problem. With Windows Vista I could not reproduce the problem but on Ubuntu I reproduced the 'connection reset'-Error constantly.

I found http://forums.oracle.com/forums/thread.jspa?threadID=941911&tstart=0&messageID=3793101

According to a user on that forum:

I opened a ticket with Oracle and this is what they told me.

java.security.SecureRandom is a standard API provided by sun. Among various methods offered by this class void nextBytes(byte[]) is one. This method is used for generating random bytes. Oracle 11g JDBC drivers use this API to generate random number during login. Users using Linux have been encountering SQLException("Io exception: Connection reset").

The problem is two fold

  1. The JVM tries to list all the files in the /tmp (or alternate tmp directory set by -Djava.io.tmpdir) when SecureRandom.nextBytes(byte[]) is invoked. If the number of files is large the method takes a long time to respond and hence cause the server to timeout

  2. The method void nextBytes(byte[]) uses /dev/random on Linux and on some machines which lack the random number generating hardware the operation slows down to the extent of bringing the whole login process to a halt. Ultimately the the user encounters SQLException("Io exception: Connection reset")

Users upgrading to 11g can encounter this issue if the underlying OS is Linux which is running on a faulty hardware.

Cause The cause of this has not yet been determined exactly. It could either be a problem in your hardware or the fact that for some reason the software cannot read from dev/random

Solution Change the setup for your application, so you add the next parameter to the java command:

-Djava.security.egd=file:/dev/../dev/urandom

We made this change in our java.security file and it has gotten rid of the error.

which solved my problem.

Python string class like StringBuilder in C#?

Python has several things that fulfill similar purposes:

  • One common way to build large strings from pieces is to grow a list of strings and join it when you are done. This is a frequently-used Python idiom.
    • To build strings incorporating data with formatting, you would do the formatting separately.
  • For insertion and deletion at a character level, you would keep a list of length-one strings. (To make this from a string, you'd call list(your_string). You could also use a UserString.MutableString for this.
  • (c)StringIO.StringIO is useful for things that would otherwise take a file, but less so for general string building.

SSH Key - Still asking for password and passphrase

I had to execute:

eval `ssh-agent -s`
ssh-add

Note: You will have to do this again after every restart. If you want to avoid it, then enter it in your ".bashrc" file which is in C:\Users\<<USERNAME>>\.bashrc on windows. It is probably hidden, so make sure that you can see hidden files.

Solution found here.

Load image from url

loadImage("http://relinjose.com/directory/filename.png");

Here you go

void loadImage(String image_location) {
    URL imageURL = null;
    if (image_location != null) {
        try {
            imageURL = new URL(image_location);         
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
            ivdpfirst.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //set any default
    }
}

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

SQL Server Configuration Manager not found

From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.

How to save data in an android app

OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)

I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.

So you really need a multi-point system:

1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.

2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.

3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.

3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.

File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
    fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
    fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
    fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory

I recommend simple CSV files for your data, so that other applications can read them easily.

Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.

How to gracefully handle the SIGKILL signal in Java

There is one way to react to a kill -9: that is to have a separate process that monitors the process being killed and cleans up after it if necessary. This would probably involve IPC and would be quite a bit of work, and you can still override it by killing both processes at the same time. I assume it will not be worth the trouble in most cases.

Whoever kills a process with -9 should theoretically know what he/she is doing and that it may leave things in an inconsistent state.

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

You can use a while loop.

Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
    Map.Entry<String, String> entry = iterator.next();
    if(entry.getKey().equals("test")) {
        iterator.remove();
    } 
}

JavaScript: How to find out if the user browser is Chrome?

To know the names of different desktop browsers (Firefox, IE, Opera, Edge, Chrome). Except Safari.

function getBrowserName() {
  var browserName = '';
  var userAgent = navigator.userAgent;
  (typeof InstallTrigger !== 'undefined') && (browserName = 'Firefox');
  ( /* @cc_on!@*/ false || !!document.documentMode) && (browserName = 'IE');
  (!!window.chrome && userAgent.match(/OPR/)) && (browserName = 'Opera');
  (!!window.chrome && userAgent.match(/Edge/)) && (browserName = 'Edge');
  (!!window.chrome && !userAgent.match(/(OPR|Edge)/)) && (browserName = 'Chrome');

  /**
   * Expected returns
   * Firefox, Opera, Edge, Chrome
   */
  return browserName;
}

Works in the following browser versions:

Opera - 58.0.3135.79
Firefox - 65.0.2 (64-bit)
IE - 11.413.15063 (JS Fiddle no longer supports IE just paste in Console)
Edge - 44.17763.1.0
Chrome - 72.0.3626.121 (Official Build) (64-bit)

View the gist here and the fiddle here

The original code snippet no longer worked for Chrome and I forgot where I found it. It had safari before but I no longer have access to safari so I cannot verify anymore.

Only the Firefox and IE codes were part of the original snippet.

The checking for Opera, Edge, and Chrome is straight forward. They have differences in the userAgent. OPR only exists in Opera. Edge only exists in Edge. So to check for Chrome these string shouldn't be there.

As for the Firefox and IE, I cannot explain what they do.

I'll be adding this functionality to a package i'm writing

.htaccess redirect www to non-www with SSL/HTTPS

Ref: Apache redirect www to non-www and HTTP to HTTPS

http://example.com

http://www.example.com

https://www.example.com

to

https://example.com

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

If instead of example.com you want the default URL to be www.example.com, then simply change the third and the fifth lines:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

What does the function then() mean in JavaScript?

.then returns a promise in async function.

Good Example would be:

var doSome = new Promise(function(resolve, reject){
    resolve('I am doing something');
});

doSome.then(function(value){
    console.log(value);
});

To add another logic to it, you can also add the reject('I am the rejected param') call the function and console.log it.

Read a file one line at a time in node.js?

This is my favorite way of going through a file, a simple native solution for a progressive (as in not a "slurp" or all-in-memory way) file read with modern async/await. It's a solution that I find "natural" when processing large text files without having to resort to the readline package or any non-core dependency.

let buf = '';
for await ( const chunk of fs.createReadStream('myfile') ) {
    const lines = buf.concat(chunk).split(/\r?\n/);
    buf = lines.pop();
    for( const line of lines ) {
        console.log(line);
    }
}
if(buf.length) console.log(buf);  // last line, if file does not end with newline

You can adjust encoding in the fs.createReadStream or use chunk.toString(<arg>). Also this let's you better fine-tune the line splitting to your taste, ie. use .split(/\n+/) to skip empty lines and control the chunk size with { highWaterMark: <chunkSize> }.

Don't forget to create a function like processLine(line) to avoid repeating the line processing code twice due to the ending buf leftover. Unfortunately, the ReadStream instance does not update its end-of-file flags in this setup, so there's no way, afaik, to detect within the loop that we're in the last iteration without some more verbose tricks like comparing the file size from a fs.Stats() with .bytesRead. Hence the final buf processing solution, unless you're absolutely sure your file ends with a newline \n, in which case the for await loop should suffice.

? If you prefer the evented asynchronous version, this would be it:

let buf = '';
fs.createReadStream('myfile')
.on('data', chunk => {
    const lines = buf.concat(chunk).split(/\r?\n/);
    buf = lines.pop();
    for( const line of lines ) {
        console.log(line);
    }
})
.on('end', () => buf.length && console.log(buf) );

? Now if you don't mind importing the stream core package, then this is the equivalent piped stream version, which allows for chaining transforms like gzip decompression:

const { Writable } = require('stream');
let buf = '';
fs.createReadStream('myfile').pipe(
    new Writable({
        write: (chunk, enc, next) => {
            const lines = buf.concat(chunk).split(/\r?\n/);
            buf = lines.pop();
            for (const line of lines) {
                console.log(line);
            }
            next();
        }
    })
).on('finish', () => buf.length && console.log(buf) );

Rails - controller action name to string

Rails 2.X: @controller.action_name

Rails 3.1.X: controller.action_name, action_name

Rails 4.X: action_name

Eloquent - where not equal to

Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition

The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)

Code::where(function ($query) {
            $query->where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id');                  
        })->get();

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

What does it mean to inflate a view from an xml file?

A layman definition for inflation might be to convert the XML code to Java code. Just a way to understand, e.g., if we have a tag in XML, OS has to create a corresponding Java object in memory, so inflatter reads the XMLtags, and creates the corresponding objects in Java.

How to add Button over image using CSS?

You need to give relative or absolute or fixed positioning to your container (#shop) and set its zIndex to say 100.

You also need to give say relative positioning to your elements with the class content and lower zIndex say 97.

Do the above-mentioned with your images too and set their zIndex to 91.

And then position your button higher by setting its position to absolute and zIndex to 95

See the DEMO

HTML

<div id="shop">

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

  </div>

CSS

#shop{
    background-image: url("images/shop_bg.png");
    background-repeat: repeat-x;    
    height:121px;
    width: 984px;
    margin-left: 20px;
    margin-top: 13px;
    position:relative;
    z-index:100
}

#shop .content{    
    width: 182px; /*328 co je 1/3 - 20margin left*/
    height: 121px;
    line-height: 20px;
    margin-top: 0px;
    margin-left: 9px;
    margin-right:0px;
    display:inline-block;
    position:relative;
    z-index:97

}

img{

    position:relative;
    z-index:91

}

.span{

    width:70px;
    height:40px;
    border:1px solid red;
    position:absolute;
    z-index:95;
    right:60px;
    bottom:-20px;

}

Is there a numpy builtin to reject outliers from a list

I wanted to do something similar, except setting the number to NaN rather than removing it from the data, since if you remove it you change the length which can mess up plotting (i.e. if you're only removing outliers from one column in a table, but you need it to remain the same as the other columns so you can plot them against each other).

To do so I used numpy's masking functions:

def reject_outliers(data, m=2):
    stdev = np.std(data)
    mean = np.mean(data)
    maskMin = mean - stdev * m
    maskMax = mean + stdev * m
    mask = np.ma.masked_outside(data, maskMin, maskMax)
    print('Masking values outside of {} and {}'.format(maskMin, maskMax))
    return mask

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

This answer may have to be modified depending on what you were trying to achieve with position: fixed;. If all you want is two columns side by side then do the following:

http://jsfiddle.net/8weSA/1/

I floated both columns to the left.

Note: I added min-height to each column for illustrative purposes and I simplified your CSS.

_x000D_
_x000D_
body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  float: left;_x000D_
  min-height: 450px;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
    Left_x000D_
  </div>_x000D_
  <div id="rightcolumn">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you would like the left column to stay in place as you scroll do the following:

http://jsfiddle.net/8weSA/2/

Here we float the right column to the right while adding position: relative; to #wrapper and position: fixed; to #leftcolumn.

Note: I again used min-height for illustrative purposes and can be removed for your needs.

_x000D_
_x000D_
body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  min-height: 750px;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
  min-height: 100px;_x000D_
  position: fixed;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
  float: right;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
    Left_x000D_
  </div>_x000D_
  <div id="rightcolumn">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

spring autowiring with unique beans: Spring expected single matching bean but found 2

If you have 2 beans of the same class autowired to one class you shoud use @Qualifier (Spring Autowiring @Qualifier example).

But it seems like your problem comes from incorrect Java Syntax.

Your object should start with lower case letter

SuggestionService suggestion;

Your setter should start with lower case as well and object name should be with Upper case

public void setSuggestion(final Suggestion suggestion) {
    this.suggestion = suggestion;
}

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

Was facing the same issue and unfortunately nothing here was working. Finally, I came across this link: https://blogs.msdn.microsoft.com/jjameson/2009/11/18/the-copy-local-bug-in-visual-studio/

Turns out the solution is sort of dumb: set copy-local for the microsoft.web.infrastructure dll to False, then set it back to True.

By the way, I think what is happening is that there are two versions of the microsoft.web.infrastructure dll, one that is pre-installed in the GAC, and another one that is now a nuget package. I think one is masking the other, hence causing issues. In my particular case, on my build server, I need it to be copied over to a folder (this folder is then zipped and sent off to deployment). I guess the system had a copy locally and just thought "nah, it'll be fine"

Is there a way to detect if a browser window is not currently active?

There are 3 typical methods used to determine if the user can see the HTML page, however none of them work perfectly:

  • The W3C Page Visibility API is supposed to do this (supported since: Firefox 10, MSIE 10, Chrome 13). However, this API only raises events when the browser tab is fully overriden (e.g. when the user changes from one tab to another one). The API does not raise events when the visibility cannot be determined with 100% accuracy (e.g. Alt+Tab to switch to another application).

  • Using focus/blur based methods gives you a lot of false positive. For example, if the user displays a smaller window on top of the browser window, the browser window will lose the focus (onblur raised) but the user is still able to see it (so it still need to be refreshed). See also http://javascript.info/tutorial/focus

  • Relying on user activity (mouse move, clicks, key typed) gives you a lot of false positive too. Think about the same case as above, or a user watching a video.

In order to improve the imperfect behaviors described above, I use a combination of the 3 methods: W3C Visibility API, then focus/blur and user activity methods in order to reduce the false positive rate. This allows to manage the following events:

  • Changing browser tab to another one (100% accuracy, thanks to the W3C Page Visibility API)
  • Page potentially hidden by another window, e.g. due to Alt+Tab (probabilistic = not 100% accurate)
  • User attention potentially not focused on the HTML page (probabilistic = not 100% accurate)

This is how it works: when the document lose the focus, the user activity (such as mouse move) on the document is monitored in order to determine if the window is visible or not. The page visibility probability is inversely proportional to the time of the last user activity on the page: if the user makes no activity on the document for a long time, the page is most probably not visible. The code below mimics the W3C Page Visibility API: it behaves the same way but has a small false positive rate. It has the advantage to be multibrowser (tested on Firefox 5, Firefox 10, MSIE 9, MSIE 7, Safari 5, Chrome 9).


    <div id="x"></div>

    <script>
    /**
    Registers the handler to the event for the given object.
    @param obj the object which will raise the event
    @param evType the event type: click, keypress, mouseover, ...
    @param fn the event handler function
    @param isCapturing set the event mode (true = capturing event, false = bubbling event)
    @return true if the event handler has been attached correctly
    */
    function addEvent(obj, evType, fn, isCapturing){
      if (isCapturing==null) isCapturing=false; 
      if (obj.addEventListener){
        // Firefox
        obj.addEventListener(evType, fn, isCapturing);
        return true;
      } else if (obj.attachEvent){
        // MSIE
        var r = obj.attachEvent('on'+evType, fn);
        return r;
      } else {
        return false;
      }
    }

    // register to the potential page visibility change
    addEvent(document, "potentialvisilitychange", function(event) {
      document.getElementById("x").innerHTML+="potentialVisilityChange: potentialHidden="+document.potentialHidden+", document.potentiallyHiddenSince="+document.potentiallyHiddenSince+" s<br>";
    });

    // register to the W3C Page Visibility API
    var hidden=null;
    var visibilityChange=null;
    if (typeof document.mozHidden !== "undefined") {
      hidden="mozHidden";
      visibilityChange="mozvisibilitychange";
    } else if (typeof document.msHidden !== "undefined") {
      hidden="msHidden";
      visibilityChange="msvisibilitychange";
    } else if (typeof document.webkitHidden!=="undefined") {
      hidden="webkitHidden";
      visibilityChange="webkitvisibilitychange";
    } else if (typeof document.hidden !=="hidden") {
      hidden="hidden";
      visibilityChange="visibilitychange";
    }
    if (hidden!=null && visibilityChange!=null) {
      addEvent(document, visibilityChange, function(event) {
        document.getElementById("x").innerHTML+=visibilityChange+": "+hidden+"="+document[hidden]+"<br>";
      });
    }


    var potentialPageVisibility = {
      pageVisibilityChangeThreshold:3*3600, // in seconds
      init:function() {
        function setAsNotHidden() {
          var dispatchEventRequired=document.potentialHidden;
          document.potentialHidden=false;
          document.potentiallyHiddenSince=0;
          if (dispatchEventRequired) dispatchPageVisibilityChangeEvent();
        }

        function initPotentiallyHiddenDetection() {
          if (!hasFocusLocal) {
            // the window does not has the focus => check for  user activity in the window
            lastActionDate=new Date();
            if (timeoutHandler!=null) {
              clearTimeout(timeoutHandler);
            }
            timeoutHandler = setTimeout(checkPageVisibility, potentialPageVisibility.pageVisibilityChangeThreshold*1000+100); // +100 ms to avoid rounding issues under Firefox
          }
        }

        function dispatchPageVisibilityChangeEvent() {
          unifiedVisilityChangeEventDispatchAllowed=false;
          var evt = document.createEvent("Event");
          evt.initEvent("potentialvisilitychange", true, true);
          document.dispatchEvent(evt);
        }

        function checkPageVisibility() {
          var potentialHiddenDuration=(hasFocusLocal || lastActionDate==null?0:Math.floor((new Date().getTime()-lastActionDate.getTime())/1000));
                                        document.potentiallyHiddenSince=potentialHiddenDuration;
          if (potentialHiddenDuration>=potentialPageVisibility.pageVisibilityChangeThreshold && !document.potentialHidden) {
            // page visibility change threshold raiched => raise the even
            document.potentialHidden=true;
            dispatchPageVisibilityChangeEvent();
          }
        }

        var lastActionDate=null;
        var hasFocusLocal=true;
        var hasMouseOver=true;
        document.potentialHidden=false;
        document.potentiallyHiddenSince=0;
        var timeoutHandler = null;

        addEvent(document, "pageshow", function(event) {
          document.getElementById("x").innerHTML+="pageshow/doc:<br>";
        });
        addEvent(document, "pagehide", function(event) {
          document.getElementById("x").innerHTML+="pagehide/doc:<br>";
        });
        addEvent(window, "pageshow", function(event) {
          document.getElementById("x").innerHTML+="pageshow/win:<br>"; // raised when the page first shows
        });
        addEvent(window, "pagehide", function(event) {
          document.getElementById("x").innerHTML+="pagehide/win:<br>"; // not raised
        });
        addEvent(document, "mousemove", function(event) {
          lastActionDate=new Date();
        });
        addEvent(document, "mouseover", function(event) {
          hasMouseOver=true;
          setAsNotHidden();
        });
        addEvent(document, "mouseout", function(event) {
          hasMouseOver=false;
          initPotentiallyHiddenDetection();
        });
        addEvent(window, "blur", function(event) {
          hasFocusLocal=false;
          initPotentiallyHiddenDetection();
        });
        addEvent(window, "focus", function(event) {
          hasFocusLocal=true;
          setAsNotHidden();
        });
        setAsNotHidden();
      }
    }

    potentialPageVisibility.pageVisibilityChangeThreshold=4; // 4 seconds for testing
    potentialPageVisibility.init();
    </script>

Since there is currently no working cross-browser solution without false positive, you should better think twice about disabling periodical activity on your web site.

Redirect on select option in select box

to make it as globally reuse function using jquery

HTML

<select class="select_location">
   <option value="http://localhost.com/app/page1.html">Page 1</option>
   <option value="http://localhost.com/app/page2.html">Page 2</option>
   <option value="http://localhost.com/app/page3.html">Page 3</option>
</select>

Javascript using jquery

$('.select_location').on('change', function(){
   window.location = $(this).val();
});

now you will able to reuse this function by adding .select_location class to any Select element class

"Can't find Project or Library" for standard VBA functions

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

Asynchronously wait for Task<T> to complete with timeout

If you use a BlockingCollection to schedule the task, the producer can run the potentially long running task and the consumer can use the TryTake method which has timeout and cancellation token built in.

How do I display Ruby on Rails form validation error messages one at a time?

A better idea,

if you want to put the error message just beneath the text field, you can do like this

.row.spacer20top
  .col-sm-6.form-group
    = f.label :first_name, "*Your First Name:"
    = f.text_field :first_name, :required => true, class: "form-control"
    = f.error_message_for(:first_name)

What is error_message_for?
--> Well, this is a beautiful hack to do some cool stuff

# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
  def error_message_for(field_name)
    if self.object.errors[field_name].present?
      model_name              = self.object.class.name.downcase
      id_of_element           = "error_#{model_name}_#{field_name}"
      target_elem_id          = "#{model_name}_#{field_name}"
      class_name              = 'signup-error alert alert-danger'
      error_declaration_class = 'has-signup-error'

      "<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
      "#{self.object.errors[field_name].join(', ')}"\
      "</div>"\
      "<!-- Later JavaScript to add class to the parent element -->"\
      "<script>"\
          "document.onreadystatechange = function(){"\
            "$('##{id_of_element}').parent()"\
            ".addClass('#{error_declaration_class}');"\
          "}"\
      "</script>".html_safe
    end
  rescue
    nil
  end
end

Result enter image description here

Markup Generated after error

<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>

Corresponding SCSS

  .has-signup-error{
    .signup-error{
      background: transparent;
      color: $brand-danger;
      border: none;
    }

    input, select{
      background-color: $bg-danger;
      border-color: $brand-danger;
      color: $gray-base;
      font-weight: 500;
    }

    &.checkbox{
      label{
        &:before{
          background-color: $bg-danger;
          border-color: $brand-danger;
        }
      }
    }

Note: Bootstrap variables used here

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

For those of you installing ELK on virtual machine in GCP (Google Cloud Platform), make sure that you created firewall rule of Ingress type (i.e. for incoming to VM traffic). You can specify in the rule multiple ports at a time by separating them with comma: 5000,5044,5601,9200,9300,9600.

In that rule you may want to specify a tag (pick tag's name as you like, for example docker-elk that will target your VM (Targets column): enter image description here

On VM's settings page assign that tag to your VM:

enter image description here

After doing that I was able to access Elasticsearch in my browser via port 9200. And I didn't have to edit elasticsearch.yml file whatsoever.

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

Best way to access a control on another form in Windows Forms?

Suppose you have two forms, and you want to hide the property of one form via another:

form1 ob = new form1();
ob.Show(this);
this.Enabled= false;

and when you want to get focus back of form1 via form2 button then:

Form1 ob = new Form1();
ob.Visible = true;
this.Close();

HTML inside Twitter Bootstrap popover

you can use attribute data-html="true":

<a href="#" id="example"  rel="popover" 
    data-content="<div>This <b>is</b> your div content</div>" 
    data-html="true" data-original-title="A Title">popover</a>

How can I include null values in a MIN or MAX?

Use the analytic function :

select case when 
    max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1 
    else 0 end as flag 
from MYTABLE;

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Maybe check Hibernate Validator 4.0, the Reference Implementation of the JSR 303: Bean Validation.

This is an example of an annotated class:

public class Address {

    @NotNull 
    private String line1;
    private String line2;
    private String zip;
    private String state;

    @Length(max = 20)
    @NotNull
    private String country;

    @Range(min = -2, max = 50, message = "Floor out of range")
    public int floor;

        ...
}

For an introduction, see Getting started with JSR 303 (Bean Validation) – part 1 and part 2 or the "Getting started" section of the reference guide which is part of the Hibernate Validator distribution.

How to make a HTML Page in A4 paper size page(s)?

PPI and DPI make absolutely no difference to how a document will print off a browser. the printer takes no information on screen dot pitch or the DPI of the images etc. if you are printing images they would print at a size similar in proportion to how they are displayed on screen. the print processor of the browser would increase the DPI of the images from something rather low like 72dpi to whatever DPI the rest of the document is. say the image displays as half a page wide, then its about 4" wide physically. the pixel width of the image would be approx 300px to display correctly in the browser. by the time it prints at a nominal 300DPI, the processor has added pixels and the image will grow to around 1200px which at 300 DPI is 4".

when it comes to vector or non pixel based elements like text, the printer chooses its own DPI from the driver which doesnt relate to screen dot pitch or browser width etc. if the browser is 3000px wide, the print processor will wrap text as appropriate.

heres what makes it hard about creating print displays: each browser and printer will interpret text sizes (pt, em, px) and spacing in its own way. depending on what printer, browser and maybe even OS you use, you will get a different amount of lines and characters per page. so even if you test on your computer using your browser and printer and figure out that you can display the text in a box at 640x900px and its perfect on print, the next guy who tries to print will possibly get it printing differently. there really is no way to force each printer and browser to get it identical each time.

forget pixels and moreso forget DPI, the only thing you could use pixels for is setting a table width that simulates the width of a printable area on your printer. in that case i found that 640px wide is close.

Create JSON object dynamically via JavaScript (Without concate strings)

Perhaps this information will help you.

_x000D_
_x000D_
var sitePersonel = {};_x000D_
var employees = []_x000D_
sitePersonel.employees = employees;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var firstName = "John";_x000D_
var lastName = "Smith";_x000D_
var employee = {_x000D_
  "firstName": firstName,_x000D_
  "lastName": lastName_x000D_
}_x000D_
sitePersonel.employees.push(employee);_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var manager = "Jane Doe";_x000D_
sitePersonel.employees[0].manager = manager;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
console.log(JSON.stringify(sitePersonel));
_x000D_
_x000D_
_x000D_

jQuery find file extension (from string)

var fileName = 'file.txt';

// Getting Extension

var ext = fileName.split('.')[1];

// OR

var ext = fileName.split('.').pop();

How do I put a clear button inside my HTML text input box like the iPhone does?

HTML5 introduces the 'search' input type that I believe does what you want.

<input type="search" />

Here's a live example.

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

Change the code to

List<string> nameslist = new List<string> {"one", "two", "three"};

or

List<string> nameslist = new List<string>(new[] {"one", "two", "three"});

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

How to include jQuery in ASP.Net project?

There are actually a few ways this can be done:

1: Download

You can download the latest version of jQuery and then include it in your page with a standard HTML script tag. This can be done within the master or an individual page.

HTML5

<script src="/scripts/jquery-2.1.0.min.js"></script>

HTML4

<script src="/scripts/jquery-2.1.0.min.js" type="text/javascript"></script>

2: Content Delivery Network

You can include jQuery to your site using a CDN (Content Delivery Network) such as Google's. This should help reduce page load times if the user has already visited a site using the same version from the same CDN.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

3: NuGet Package Manager

Lastly, (my preferred) use NuGet which is shipped with Visual Studio and Visual Studio Express. This is accessed from right-clicking on your project and clicking Manage NuGet Packages.

NuGet is an open source Library Package Manager that comes as a Visual Studio extension and that makes it very easy to add, remove, and update external libraries in your Visual Studio projects and websites. Beginning ASP.NET 4.5 in C# and VB.NET, WROX, 2013

enter image description here

Once installed, a new Folder group will appear in your Solution Explorer called Scripts. Simply drag and drop the file you wish to include onto your page of choice.

This method is ideal for larger projects because if you choose to remove the files, or change versions later (though the package manager) if will automatically remove/update any reference to that file within your project.

The only downside to this approach is it does not use a CDN to host the file so page load time may be slightly slower the first time the user visits your site.

Chrome Extension - Get DOM content

You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScriptinstead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.

part of manifest.json

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
},
"permissions": [
    "activeTab",
    "<all_urls>"
]

index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="test">TEST!</button>
    <script src="test.js"></script>
  </body>
</html>

test.js

document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        console.log(document.body);
        return document.body.innerHTML;
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')
        console.log(results[0]);
    });
});

Does bootstrap have builtin padding and margin classes?

I think what you're asking about is how to create responsive spacing between rows or col-xx-xx classes.

You can definitely do this with the col-xx-offset-xx class:

<div class="col-xs-4">
</div>

<div class="col-xs-7 col-xs-offset-1">
</div>

As for adding margin or padding directly to elements, there are some simple ways to do this depending on your element. You can use btn-lg or label-lg or well-lg. If you're ever wondering, how can i give this alittle padding. Try adding the primary class name + lg or sm or md depending on your size needs:

<button class="btn btn-success btn-lg btn-block">Big Button w/ Display: Block</button>

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

Nothing easier than that man. Try this one:

<?xml version="1.0" encoding="iso-8859-1"?>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
    <style>
        .loading { background: url(/img/spinner.gif) center no-repeat !important}
    </style>
</head>
<body>
    <a class="ajax" href="http://www.google.com">
      Open as dialog
    </a>

    <script type="text/javascript">
    $(function (){
        $('a.ajax').click(function() {
            var url = this.href;
            // show a spinner or something via css
            var dialog = $('<div style="display:none" class="loading"></div>').appendTo('body');
            // open the dialog
            dialog.dialog({
                // add a close listener to prevent adding multiple divs to the document
                close: function(event, ui) {
                    // remove div with all data and events
                    dialog.remove();
                },
                modal: true
            });
            // load remote content
            dialog.load(
                url, 
                {}, // omit this param object to issue a GET request instead a POST request, otherwise you may provide post parameters within the object
                function (responseText, textStatus, XMLHttpRequest) {
                    // remove the loading class
                    dialog.removeClass('loading');
                }
            );
            //prevent the browser to follow the link
            return false;
        });
    });
    </script>
</body>
</html>

Note that you can't load remote from local, so you'll have to upload this to a server or whatever. Also note that you can't load from foreign domains, so you should replace href of the link to a document hosted on the same domain (and here's the workaround).

Cheers

Calling async method on button click

This is what's killing you:

task.Wait();

That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...

There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:

private async void Button_Click(object sender, RoutedEventArgs 
{
    Task<List<MyObject>> task = GetResponse<MyObject>("my url");
    var items = await task;
    // Presumably use items here
}

Or just:

private async void Button_Click(object sender, RoutedEventArgs 
{
    var items = await GetResponse<MyObject>("my url");
    // Presumably use items here
}

Now instead of blocking until the task has completed, the Button_Click method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)

Note that I would also rename GetResponse to GetResponseAsync for clarity.

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

I made exactly what @grepit made.

But I had to made some changes in my Java code:

In Producer and Receiver project I altered:

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("your-host-ip");
factory.setUsername("username-you-created");
factory.setPassword("username-password");

        

Doing that, you are connecting an specific host as the user you have created. It works for me!

How do I join two lists in Java?

We can join 2 lists using java8 with 2 approaches.

    List<String> list1 = Arrays.asList("S", "T");
    List<String> list2 = Arrays.asList("U", "V");

1) Using concat :

    List<String> collect2 = Stream.concat(list1.stream(), list2.stream()).collect(toList());
    System.out.println("collect2 = " + collect2); // collect2 = [S, T, U, V]

2) Using flatMap :

    List<String> collect3 = Stream.of(list1, list2).flatMap(Collection::stream).collect(toList());
    System.out.println("collect3 = " + collect3); // collect3 = [S, T, U, V]

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

in this link i mentioned before on the comment, read this part :

A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.

this "JOIN FETCH" will have it's effect if you have (fetch = FetchType.LAZY) property for a collection inside entity(example bellow).

And it is only effect the method of "when the query should happen". And you must also know this:

hibernate have two orthogonal notions : when is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class.

when is the association fetched --> your "FETCH" type

how is it fetched --> Join/select/Subselect/Batch

In your case, FETCH will only have it's effect if you have department as a set inside Employee, something like this in the entity:

@OneToMany(fetch = FetchType.LAZY)
private Set<Department> department;

when you use

FROM Employee emp
JOIN FETCH emp.department dep

you will get emp and emp.dep. when you didnt use fetch you can still get emp.dep but hibernate will processing another select to the database to get that set of department.

so its just a matter of performance tuning, about you want to get all result(you need it or not) in a single query(eager fetching), or you want to query it latter when you need it(lazy fetching).

Use eager fetching when you need to get small data with one select(one big query). Or use lazy fetching to query what you need latter(many smaller query).

use fetch when :

  • no large unneeded collection/set inside that entity you about to get

  • communication from application server to database server too far and need long time

  • you may need that collection latter when you don't have the access to it(outside of the transactional method/class)

Clear data in MySQL table with PHP?

TRUNCATE TABLE `table`

unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer

DELETE FROM `table`

though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using

ALTER TABLE `table` AUTO_INCREMENT = value

will happen a lot faster.

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Your code works for me. When does addSalespersonOption get called? There may be a problem with that call.

Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:

<select id="salesperson"> 
    <option value="">(select)</option> 
</select>

instead of this:

<select id="salesperson" /> 
    <option value"">(select)</option> 
</select>

Edit: When does your options list get dynamically populated? Are you sure you are passing 'on' for the defSales value in your call to addSalespersonOption? Try changing that code to this:

if (selected == "on") { 
    alert('setting default selected option to ' + text);
    html = '<option value="'+value+'" selected="selected">'+text+'</option>'; 
} 

and see if the alert happens and what is says if it does happen.

Edit: Working example of my testing (the error:undefined is from jsbin, not my code).

set environment variable in python script

You can add elements to your environment by using

os.environ['LD_LIBRARY_PATH'] = 'my_path'

and run subprocesses in a shell (that uses your os.environ) by using

subprocess.call('sqsub -np ' + var1 + '/homedir/anotherdir/executable', shell=True)

POST request send json data java HttpUrlConnection

private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

Converting java.sql.Date to java.util.Date

In the recent implementation, java.sql.Data is an subclass of java.util.Date, so no converting needed. see here: https://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html

A html space is showing as %2520 instead of %20

For some - possibly valid - reason the url was encoded twice. %25 is the urlencoded % sign. So the original url looked like:

http://server.com/my path/

Then it got urlencoded once:

http://server.com/my%20path/

and twice:

http://server.com/my%2520path/

So you should do no urlencoding - in your case - as other components seems to to that already for you. Use simply a space

Android "elevation" not showing a shadow

In my case, this was caused by a custom parent component setting the rendering layer type to "Software":

setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Removing this line of did the trick. Or course you need to evaluate why this is there in the first place. In my case it was to support Honeycomb, which is well behind the current minimum SDK for my project.

Java 6 Unsupported major.minor version 51.0

i also faced similar issue. I could able to solve this by setting JAVA_HOME in Environment variable in windows. Setting JAVA_HOME in batch file is not working in this case.

What is the difference between smoke testing and sanity testing?

Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.

Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.

In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

Why use double indirection? or Why use pointers to pointers?

I saw a very good example today, from this blog post, as I summarize below.

Imagine you have a structure for nodes in a linked list, which probably is

typedef struct node
{
    struct node * next;
    ....
} node;

Now you want to implement a remove_if function, which accepts a removal criterion rm as one of the arguments and traverses the linked list: if an entry satisfies the criterion (something like rm(entry)==true), its node will be removed from the list. In the end, remove_if returns the head (which may be different from the original head) of the linked list.

You may write

for (node * prev = NULL, * curr = head; curr != NULL; )
{
    node * const next = curr->next;
    if (rm(curr))
    {
        if (prev)  // the node to be removed is not the head
            prev->next = next;
        else       // remove the head
            head = next;
        free(curr);
    }
    else
        prev = curr;
    curr = next;
}

as your for loop. The message is, without double pointers, you have to maintain a prev variable to re-organize the pointers, and handle the two different cases.

But with double pointers, you can actually write

// now head is a double pointer
for (node** curr = head; *curr; )
{
    node * entry = *curr;
    if (rm(entry))
    {
        *curr = entry->next;
        free(entry);
    }
    else
        curr = &entry->next;
}

You don't need a prev now because you can directly modify what prev->next pointed to.

To make things clearer, let's follow the code a little bit. During the removal:

  1. if entry == *head: it will be *head (==*curr) = *head->next -- head now points to the pointer of the new heading node. You do this by directly changing head's content to a new pointer.
  2. if entry != *head: similarly, *curr is what prev->next pointed to, and now points to entry->next.

No matter in which case, you can re-organize the pointers in a unified way with double pointers.

Could not find folder 'tools' inside SDK

This can also happen due to the bad unzipping process of SDK.It Happend to me. Dont use inbuilt windows unzip process. use WINRAR software for unzipping sdk

TensorFlow not found using pip

Check https://pypi.python.org/pypi/tensorflow to see which packages are available.

As of this writing, they don't provide a source package, so if there's no prebuilt one for your platform, this error occurs. If you add -v to the pip command line, you'll see it iterating over the packages that are available at PyPI and discarding them for being incompatible.

You need to either find a prebuilt package somewhere else, or compile tensorflow yourself from its sources by instructions at https://www.tensorflow.org/install/install_sources .

They have a good reason for not building for some platforms though:

How to enable CORS in ASP.NET Core

All the workaround mentioned above may work or may not work, in most cases it will not work. I have given the solution here

Currently I am working on Angular and Web API(.net Core) and came across CORS issue explained below

The solution provided above will always work. With 'OPTIONS' request it is really necessary to enable 'Anonymous Authentication'. With the solution mentioned here you don't have to do all the steps mentioned above, like IIS settings.

Anyways someone marked my above post as duplicate with this post, but I can see that this post is only to enable CORS in ASP.net Core, but my post is related to, Enabling and implementing CORS in ASP.net Core and Angular.

Disabled form fields not submitting data

We can also use the readonly only with below attributes -

readonly onclick='return false;'

This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

Which characters make a URL invalid?

Most of the existing answers here are impractical because they totally ignore the real-world usage of addresses like:

First, a digression into terminology. What are these addresses? Are they valid URLs?

Historically, the answer was "no". According to RFC 3986, from 2005, such addresses are not URIs (and therefore not URLs, since URLs are a type of URIs). Per the terminology of 2005 IETF standards, we should properly call them IRIs (Internationalized Resource Identifiers), as defined in RFC 3987, which are technically not URIs but can be converted to URIs simply by percent-encoding all non-ASCII characters in the IRI.

Per modern spec, the answer is "yes". The WHATWG Living Standard simply classifies everything that would previously be called "URIs" or "IRIs" as "URLs". This aligns the specced terminology with how normal people who haven't read the spec use the word "URL", which was one of the spec's goals.

What characters are allowed under the WHATWG Living Standard?

Per this newer meaning of "URL", what characters are allowed? In many parts of the URL, such as the query string and path, we're allowed to use arbitrary "URL units", which are

URL code points and percent-encoded bytes.

What are "URL code points"?

The URL code points are ASCII alphanumeric, U+0021 (!), U+0024 ($), U+0026 (&), U+0027 ('), U+0028 LEFT PARENTHESIS, U+0029 RIGHT PARENTHESIS, U+002A (*), U+002B (+), U+002C (,), U+002D (-), U+002E (.), U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+003F (?), U+0040 (@), U+005F (_), U+007E (~), and code points in the range U+00A0 to U+10FFFD, inclusive, excluding surrogates and noncharacters.

(Note that the list of "URL code points" doesn't include %, but that %s are allowed in "URL code units" if they're part of a percent-encoding sequence.)

The only place I can spot where the spec permits the use of any character that's not in this set is in the host, where IPv6 addresses are enclosed in [ and ] characters. Everywhere else in the URL, either URL units are allowed or some even more restrictive set of characters.

What characters were allowed under the old RFCs?

For the sake of history, and since it's not explored fully elsewhere in the answers here, let's examine was allowed under the older pair of specs.

First of all, we have two types of RFC 3986 reserved characters:

  • :/?#[]@, which are part of the generic syntax for a URI defined in RFC 3986
  • !$&'()*+,;=, which aren't part of the RFC's generic syntax, but are reserved for use as syntactic components of particular URI schemes. For instance, semicolons and commas are used as part of the syntax of data URIs, and & and = are used as part of the ubiquitous ?foo=bar&qux=baz format in query strings (which isn't specified by RFC 3986).

Any of the reserved characters above can be legally used in a URI without encoding, either to serve their syntactic purpose or just as literal characters in data in some places where such use could not be misinterpreted as the character serving its syntactic purpose. (For example, although / has syntactic meaning in a URL, you can use it unencoded in a query string, because it doesn't have meaning in a query string.)

RFC 3986 also specifies some unreserved characters, which can always be used simply to represent data without any encoding:

  • abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~

Finally, the % character itself is allowed for percent-encodings.

That leaves only the following ASCII characters that are forbidden from appearing in a URL:

  • The control characters (chars 0-1F and 7F), including new line, tab, and carriage return.
  • "<>\^`{|}

Every other character from ASCII can legally feature in a URL.

Then RFC 3987 extends that set of unreserved characters with the following unicode character ranges:

  %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
/ %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
/ %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
/ %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
/ %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
/ %xD0000-DFFFD / %xE1000-EFFFD

These block choices from the old spec seem bizarre and arbitrary given the latest Unicode block definitions; this is probably because the blocks have been added to in the decade since RFC 3987 was written.


Finally, it's perhaps worth noting that simply knowing which characters can legally appear in a URL isn't sufficient to recognise whether some given string is a legal URL or not, since some characters are only legal in particular parts of the URL. For example, the reserved characters [ and ] are legal as part of an IPv6 literal host in a URL like http://[1080::8:800:200C:417A]/foo but aren't legal in any other context, so the OP's example of http://example.com/file[/].html is illegal.

javascript create empty array of a given size

If you want to create anonymous array with some values so you can use this syntax.

_x000D_
_x000D_
var arr = new Array(50).fill().map((d,i)=>++i)
console.log(arr)
_x000D_
_x000D_
_x000D_

Flutter: RenderBox was not laid out

I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.

How to get a .csv file into R?

Since you say you want to access by position once your data is read in, you should know about R's subsetting/ indexing functions.

The easiest is

df[row,column]
#example
df[1:5,] #rows 1:5, all columns
df[,5] #all rows, column 5. 

Other methods are here. I personally use the dplyr package for intuitive data manipulation (not by position).

How to convert datetime format to date format in crystal report using C#?

There are many ways you can do this. You can just use what is described here or you can do myDate.ToString("dd-MMM-yyyy"); There are plenty of help for this topic in the MSDN documentation.

You could also write you own DateExtension class which will allow you to go something like myDate.ToMyDateFormat();

    public static class DateTimeExtensions
    {
        public static DateTime ToMyDateFormat(this DateTime d)
        {
            return d.ToString("dd-MMM-yyyy");
        }
    }

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Background

Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.

Most of my points are related to Invariant's answer, so I would suggest to go through it first.

Current Status of JavaFX on Mobile / Embedded

UPDATE

JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.

Old answer with JavaFXPorts

Some bad news first:

Now, some good news:

  • JavaFX still runs on Android, iOS and most of the Embedded devices
  • JavaFXPorts SDK for android, iOS and embedded devices can be downloaded from here
  • JavaFXPorts project is still thriving and it is easier than ever to run JavaFX on mobile devices, all thanks to the IDE plugins that is built on top of these SDKs and gets you started in a few minutes without the hassle of installing any SDK
  • JavaFX 3D is now supported on mobile devices
  • GluonVM to replace RoboVM enabling Java 9 support for mobile developers. Yes, you heard it right.
  • Mobile Project has been launched by Oracle to support JDK on all major mobile platforms. It should support JavaFX as well ;)

How to get started

If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.

Most of the documentation on how to get started can be found here and some of the samples can be found here.

Loop through JSON in EJS

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296

How to populate/instantiate a C# array with a single value?

this also works...but might be unnecessary

 bool[] abValues = new bool[1000];
 abValues = abValues.Select( n => n = true ).ToArray<bool>();

How do I use Linq to obtain a unique list of properties from a list of objects?

When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this

 IEnumerable<T> ids = list.Select(x => x).Distinct();

XSL substring and indexOf

The following is the complete example containing both XML and XSLT where substring-before and substring-after are used

<?xml version="1.0" encoding="UTF-8"?>
<persons name="Group_SOEM">
    <person>
        <first>Joe Smith</first>
        <last>Joe Smith</last>
        <address>123 Main St, Anycity</address>
    </person>
</persons>    

The following is XSLT which changes value of first/last name by separating the value by space so that after applying this XSL the first name element will have value "Joe" and last "Smith".

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="first">
    <first>
        <xsl:value-of select="substring-before(.,' ')" />
    </first>
</xsl:template> 
<xsl:template match="last">
    <last>
        <xsl:value-of select="substring-after(.,' ')" />
    </last>
</xsl:template> 
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>   

Fatal error: "No Target Architecture" in Visual Studio

Another reason for the error (amongst many others that cropped up when changing the target build of a Win32 project to X64) was not having the C++ 64 bit compilers installed as noted at the top of this page.
Further to philipvr's comment on child headers, (in my case) an explicit include of winnt.h being unnecessary when windows.h was being used.

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

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

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

How do I make a column unique and index it in a Ruby on Rails migration?

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name.

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

I will say It 's just shorthand syntax for get reference of html element during debugging time , normaly these kind of task will perform by these method

document.getElementById , document.getElementsByClassName , document.querySelector

so clicking on an html element and getting a reference variable ($0) in console is a huge time saving during the day

How to change TextBox's Background color?

Setting textbox backgroundcolor with multiple colors on single click.

Note:- using HTML and Javscript.

< input id="ClickMe_btn" onclick="setInterval(function () { ab() }, 3000);" type="button" value="ClickMe" />

var arr, i = 0; arr = ["Red", "Blue", "Green", " Orange ", "Purple", "Yellow", "Brown", "Lime", "Grey"]; // We provide array as input.

    function ab()
     {   document.getElementById("Text").style.backgroundColor = arr[i];
          window.alert(arr[i]);
          i++;
     }

Note: You can change milliseconds, with setInterval 2nd parameter.

How do I copy a folder from remote to local using scp?

What I always use is:

scp -r username@IP:/path/to/server/source/folder/  .

. (dot) : it means current folder. so copy from server and paste here only.

IP : can be an IP address like 125.55.41.311 or it can be host like ns1.mysite.com.

MVC4 HTTP Error 403.14 - Forbidden

You can also get a 403 if when testing with dev server you are using integrated pipeline and then install as classic pipeline mode on your live IIS 7.5 web server, also I was missing my app_data folder which also was required

Case insensitive 'in'

username = 'MICHAEL89'
if username.upper() in (name.upper() for name in USERNAMES):
    ...

Alternatively:

if username.upper() in map(str.upper, USERNAMES):
    ...

Or, yes, you can make a custom method.

Function to return only alpha-numeric characters from string?

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

What is ":-!!" in C code?

Some people seem to be confusing these macros with assert().

These macros implement a compile-time test, while assert() is a runtime test.

What is the difference between dict.items() and dict.iteritems() in Python2?

dict.items() return list of tuples, and dict.iteritems() return iterator object of tuple in dictionary as (key,value). The tuples are the same, but container is different.

dict.items() basically copies all dictionary into list. Try using following code to compare the execution times of the dict.items() and dict.iteritems(). You will see the difference.

import timeit

d = {i:i*2 for i in xrange(10000000)}  
start = timeit.default_timer() #more memory intensive
for key,value in d.items():
    tmp = key + value #do something like print
t1 = timeit.default_timer() - start

start = timeit.default_timer()
for key,value in d.iteritems(): #less memory intensive
    tmp = key + value
t2 = timeit.default_timer() - start

Output in my machine:

Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186

This clearly shows that dictionary.iteritems() is much more efficient.

Unique constraint on multiple columns

If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:

ALTER TABLE dbo.User
  ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)

Questions every good Database/SQL developer should be able to answer

  • Explain possible constraints on tables
  • Explain views (and materialized)
  • Explain sequences
  • Explain triggers

Escaping a forward slash in a regular expression

Use the backslash \ or choose a different delimiter, ie m#.\d# instead of /.\d/ "In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"

Add Marker function with Google Maps API

<div id="map" style="width:100%;height:500px"></div>

<script>
function myMap() {
  var myCenter = new google.maps.LatLng(51.508742,-0.120850);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 5};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>

Maven: best way of linking custom external JAR to my project?

The best solution here is to install a repository: Nexus or Artifactory. If gives you a place to put things like this, and further it speeds things up by caching your stuff from the outside.

If the thing you are dealing with is open source, you might also consider putting in into central.

See the guide.

How to remove element from array in forEach loop?

Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.

You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for (à la C language):

_x000D_
_x000D_
let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];_x000D_
_x000D_
for (let i = arr.length - 1; i >= 0; i--) {_x000D_
  if (arr[i] === 'a') {_x000D_
    arr.splice(i, 1);_x000D_
  }_x000D_
}_x000D_
_x000D_
document.body.append(arr.join());
_x000D_
_x000D_
_x000D_

If you really think about it, a forEach is just syntactic sugar for a for loop... So if it's not helping you, just please stop breaking your head against it.

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

What is __future__ in Python used for and how/when to use it, and how it works

After Python 3.0 onward, print is no longer just a statement, its a function instead. and is included in PEP 3105.

Also I think the Python 3.0 package has still these special functionality. Lets see its usability through a traditional "Pyramid program" in Python:

from __future__ import print_function

class Star(object):
    def __init__(self,count):
        self.count = count

    def start(self):
        for i in range(1,self.count):
            for j in range (i): 
                print('*', end='') # PEP 3105: print As a Function 
            print()

a = Star(5)
a.start()

Output:
*
**
***
****

If we use normal print function, we won't be able to achieve the same output, since print() comes with a extra newline. So every time the inner for loop execute, it will print * onto the next line.

What are XAND and XOR

XOR is Exclusive Or. It means "One of the two items being XOR'd is true, but not both of them."

TRUE XOR TRUE : FALSE
TRUE XOR FALSE : TRUE
FALSE XOR TRUE : TRUE
FALSE XOR FALSE: FALSE

Wikipedia's XOR Article

XAND I have not heard of.

How to detect DataGridView CheckBox event change?

In the event CellContentClick you can use this strategy:

private void myDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{    
    if (e.ColumnIndex == 2)//set your checkbox column index instead of 2
    {   //When you check
        if (Convert.ToBoolean(myDataGrid.Rows[e.RowIndex].Cells[2].EditedFormattedValue) == true)
        {
            //EXAMPLE OF OTHER CODE
            myDataGrid.Rows[e.RowIndex].Cells[5].Value = DateTime.Now.ToShortDateString();

            //SET BY CODE THE CHECK BOX
            myDataGrid.Rows[e.RowIndex].Cells[2].Value = 1;
        }
        else //When you decheck
        {
            myDataGrid.Rows[e.RowIndex].Cells[5].Value = String.Empty;

            //SET BY CODE THE CHECK BOX
            myDataGrid.Rows[e.RowIndex].Cells[2].Value = 0;
        }
    }
}

Which Protocols are used for PING?

Internet Control Message Protocol

http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol

ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.

How can I check if a background image is loaded?

Here is a small plugin I made to allow you to do exactly this, it also works on multiple background images and multiple elements:

Read the article:

http://catmull.uk/code-lab/background-image-loaded/

or go straight to the plugin code:

http://catmull.uk/downloads/bg-loaded/bg-loaded.js

So just include the plugin and then call it on the element:

<script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
<script type="text/javascript">
   $('body').bgLoaded();
</script>

Obviously download the plugin and store it on your own hosting.

By default it adds an additional "bg-loaded" class to each matched element once the background is loaded but you can easily change that by passing it a different function like this:

<script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
<script type="text/javascript">
   $('body').bgLoaded({
      afterLoaded : function() {
         alert('Background image done loading');
      }
   });
</script>

Here is a codepen demonstrating it working.

http://codepen.io/catmull/pen/Lfcpb

What do Push and Pop mean for Stacks?

The rifle clip analogy posted by Oren A is pretty good, but I'll try another one and try to anticipate what the instructor was trying to get across.

A stack, as it's name suggests is an arrangement of "things" that has:

  • A top
  • A bottom
  • An ordering in between the top and bottom (e.g. second from the top, 3rd from the bottom).

(think of it as a literal stack of books on your desk and you can only take something from the top)

Pushing something on the stack means "placing it on top". Popping something from the stack means "taking the top 'thing'" off the stack.

A simple usage is for reversing the order of words. Say I want to reverse the word: "popcorn". I push each letter from left to right (all 7 letters), and then pop 7 letters and they'll end up in reverse order. It looks like this was what he was doing with those expressions.

push(p) push(o) push(p) push(c) push(o) push(r) push(n)

after pushing the entire word, the stack looks like:

   |  n   |  <- top
   |  r   |
   |  o   |
   |  c   |
   |  p   |
   |  o   |
   |  p   |  <- bottom (first "thing" pushed on an empty stack)
    ======

when I pop() seven times, I get the letters in this order:

n,r,o,c,p,o,p

conversion of infix/postfix/prefix is a pathological example in computer science when teaching stacks:

Infix to Postfix conversion.

Post fix conversion to an infix expression is pretty straight forward:

(scan expression from left to right)

  1. For every number (operand) push it on the stack.
  2. Every time you encounter an operator (+,-,/,*) pop twice from the stack and place the operator between them. Push that on the stack:

So if we have 53+2* we can convert that to infix in the following steps:

  1. Push 5.
  2. Push 3.
  3. Encountered +: pop 3, pop 5, push 5+3 on stack (be consistent with ordering of 5 and 3)
  4. Push 2.
  5. Encountered *: pop 2, pop (5+3), push (2 * (5+3)).

*When you reach the end of the expression, if it was formed correctly you stack should only contain one item.

By introducing 'x' and 'o' he may have been using them as temporary holders for the left and right operands of an infix expression: x + o, x - o, etc. (or order of x,o reversed).

There's a nice write up on wikipedia as well. I've left my answer as a wiki incase I've botched up any ordering of expressions.

Read file As String

With files we know the size in advance, so just read it all at once!

String result;
File file = ...;

long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
    result = "";
    Log.w(TAG, "File is empty or huge: " + file);
} else {
    try (FileReader in = new FileReader(file)) {
        char[] content = new char[(int)length];

        int numRead = in.read(content);
        if (numRead != length) {
            Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
        }
        result = new String(content, 0, numRead);
    }
    catch (Exception ex) {
        Log.e(TAG, "Failure reading " + this.file, ex);
        result = "";
    }
}

Need to combine lots of files in a directory

I know this is an old post, but I found it and then found someone who suggested Total Mail Converter. I was able to convert my folder with 2k .msg files into .txt. It also allows you to convert into PDF and other popular formats.

It's a great tool that I am glad someone suggested as it will save me several days.

FYI - My project is combining the .msg files into one text file so that I can run a script to extract certain information from the files (ie: email and links). Instead of 2k files, I can work with one.

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
         /
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
                 /
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I found the solution myself later, so I placed it as an answer:

The error persisted every now and then when adding new function to my JS file. I ultimately stripped down my concatenated JS file and found out that there were two versions of jQuery being loaded, of which one was very, very old.

Check if a Python list item contains a string inside another string

If you only want to check for the presence of abc in any string in the list, you could try

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
    # whatever

If you really want to get all the items containing abc, use

matching = [s for s in some_list if "abc" in s]

jQuery ajax success callback function definition

Just use:

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

The success property requires only a reference to a function, and passes the data as parameter to this function.

You can access your handleData function like this because of the way handleData is declared. JavaScript will parse your code for function declarations before running it, so you'll be able to use the function in code that's before the actual declaration. This is known as hoisting.

This doesn't count for functions declared like this, though:

var myfunction = function(){}

Those are only available when the interpreter passed them.

See this question for more information about the 2 ways of declaring functions

HTTP Error 404 when running Tomcat from Eclipse

  1. Click on Window > Show view > Server OR right click on the server in "Servers" view, select "Properties".
  2. OR Open the Overview screen for the server by double clicking it.
  3. In the Server locations tab , select "Use Tomcat location".
  4. Save the configurations and restart the Server.

This way Eclipse will take full control over Tomcat, this way you'll also be able to access the default Tomcat homepage with the Tomcat Manager when running from inside Eclipse.

Screenshot is attached here

The application has stopped unexpectedly: How to Debug?

If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.

The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.

Automatically open Chrome developer tools when new tab/new window is opened

There is a command line switch for this: --auto-open-devtools-for-tabs

So for the properties on Google Chrome, use something like this:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --auto-open-devtools-for-tabs

Here is a useful link: chromium-command-line-switches

ReactJS - .JS vs .JSX

JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern

// filename: MyComponent.js
function MyComponent() {
  return <div />;
}

as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

After not able to find a good universal solution I made something of my own. I have not tested it for a very large list.

It takes care of nested keys,arrays or just about anything.

Here is the github and demo

app.filter('xf', function() {
    function keyfind(f, obj) {
        if (obj === undefined)
            return -1;
        else {
            var sf = f.split(".");
            if (sf.length <= 1) {
                return obj[sf[0]];
            } else {
                var newobj = obj[sf[0]];
                sf.splice(0, 1);
                return keyfind(sf.join("."), newobj)
            }
        }

    }
    return function(input, clause, fields) {
        var out = [];
        if (clause && clause.query && clause.query.length > 0) {
            clause.query = String(clause.query).toLowerCase();
            angular.forEach(input, function(cp) {
                for (var i = 0; i < fields.length; i++) {
                    var haystack = String(keyfind(fields[i], cp)).toLowerCase();
                    if (haystack.indexOf(clause.query) > -1) {
                        out.push(cp);
                        break;
                    }
                }
            })
        } else {
            angular.forEach(input, function(cp) {
                out.push(cp);
            })
        }
        return out;
    }

})

HTML

<input ng-model="search.query" type="text" placeholder="search by any property">
<div ng-repeat="product in products |  xf:search:['color','name']">
...
</div>

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

How to thoroughly purge and reinstall postgresql on ubuntu?

I was following the replies, When editing /etc/group I also deleted this line:

ssl-cert:x:112:postgres

then, when trying to install postgresql, I got this error

Preconfiguring packages ...
dpkg: unrecoverable fatal error, aborting:
 syntax error: unknown group 'ssl-cert' in statoverride file
E: Sub-process /usr/bin/dpkg returned an error code (2)

Putting the "ssl-cert:x:112:postgres" line back in /etc/group seems to fix it (so I was able to install postgresql)

How to detect orientation change in layout in Android?

If accepted answer doesn't work for you, make sure you didn't define in manifest file:

android:screenOrientation="portrait"

Which is my case.

How to start Spyder IDE on Windows

I had the same problem after setting up my environment on Windows 10. I have Python 3.6.2 x64 installed as my default Python distribution and is in my PATH so I can launch from cmd prompt.

I installed PyQt5 (pip install pyqt5) and Spyder (pip install spyder) which both installed w/out error and included all of the necessary dependencies.

To launch Spyder, I created a simple Python script (Spyder.py):

# Spyder Start Script
from spyder.app import start
start.main()

Then I created a Windows batch file (Spyder.bat):

@echo off
python c:\<path_to_Spyder_py>\Spyder.py

Lastly, I created a shortcut on my desktop which launches Spyder.bat and updated the icon to one I downloaded from the Spyder github project.

Works like a charm for me.

Fragments onResume from back stack

This is the correct answer you can call onResume() providing the fragment is attached to the activity. Alternatively you can use onAttach and onDetach

How to open a Bootstrap modal window using jQuery?

In addition you can use via data attribute

<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>

In this particular case you don't need to write javascript.

You can see more here: http://getbootstrap.com/2.3.2/javascript.html#modals

When should you NOT use a Rules Engine?

In my experience, rules engines work best when the following are true:

  1. Well-defined doctrine for your problem domain
  2. High quality (preferably automated) data to help drive most of your inputs
  3. Access to subject matter experts
  4. Software developers with experience creating expert systems

If any of these four traits are missing, you still might find a rules engine works for you, but every time I've tried it with even 1 missing, I've run into trouble.

Can I convert a boolean to Yes/No in a ASP.NET GridView

Or you can use the ItemDataBound event in the code behind.

What is the difference between association, aggregation and composition?

Association, Aggregation, Composition are about Has a relationship.

Aggregation and Composition are subsets of Association which describe relationship more accurately

Aggregation - independent relationship. An object can be passed and saved inside class via constructor, method, setter...

Composition - dependent relationship. An object is created by owner object

*Association is an alternative for sybtyping

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

How do I get a computer's name and IP address using VB.NET?

Here is Example for this. In this example we can get IP address of our given host name.

   Dim strHostName As String = "jayeshsorathia.blogspot.com"
    'string strHostName = "www.microsoft.com";
    ' Get DNS entry of specified host name
    Dim addresses As IPAddress() = Dns.GetHostEntry(strHostName).AddressList

    ' The DNS entry may contains more than one IP addresses.
    ' Iterate them and display each along with the type of address (AddressFamily).
    For Each address As IPAddress In addresses
        Response.Write(String.Format("{0} = {1} ({2})", strHostName, address, address.AddressFamily))
        Response.Write("<br/><br/>")
    Next

Find out a Git branch creator

As far as I know, you may see if you are the creator of a branch only. This is indicated by the first row in .git/ref/heads/<branch>. If it ends with "Created from HEAD" you are the creator.

How is the java memory pool divided?

With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.

write newline into a file

Solution:

in WINDOWS you should write "\r\n" for a new line.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

It doesn't - at least during the compilation phase.

The translation of a c++ program from source code to machine code is performed in three phases:

  1. Preprocessing - The Preprocessor parses all source code for lines beginning with # and executes the directives. In your case, the contents of your file class.h is inserted in place of the line #include "class.h. Since you might be includein your header file in several places, the #ifndef clauses avoid duplicate declaration-errors, since the preprocessor directive is undefined only the first time the header file is included.
  2. Compilation - The Compiler does now translate all preprocessed source code files to binary object files.
  3. Linking - The Linker links (hence the name) together the object files. A reference to your class or one of its methods (which should be declared in class.h and defined in class.cpp) is resolved to the respective offset in one of the object files. I write 'one of your object files' since your class does not need to be defined in a file named class.cpp, it might be in a library which is linked to your project.

In summary, the declarations can be shared through a header file, while the mapping of declarations to definitions is done by the linker.

Select datatype of the field in postgres

The information schema views and pg_typeof() return incomplete type information. Of these answers, psql gives the most precise type information. (The OP might not need such precise information, but should know the limitations.)

create domain test_domain as varchar(15);

create table test (
  test_id test_domain, 
  test_vc varchar(15), 
  test_n numeric(15, 3), 
  big_n bigint,
  ip_addr inet
);

Using psql and \d public.test correctly shows the use of the data type test_domain, the length of varchar(n) columns, and the precision and scale of numeric(p, s) columns.

sandbox=# \d public.test
             Table "public.test"
 Column  |         Type          | Modifiers
---------+-----------------------+-----------
 test_id | test_domain           |
 test_vc | character varying(15) |
 test_n  | numeric(15,3)         |
 big_n   | bigint                |
 ip_addr | inet                  |

This query against an information_schema view does not show the use of test_domain at all. It also doesn't report the details of varchar(n) and numeric(p, s) columns.

select column_name, data_type 
from information_schema.columns 
where table_catalog = 'sandbox'
  and table_schema = 'public'
  and table_name = 'test';
 column_name |     data_type
-------------+-------------------
 test_id     | character varying
 test_vc     | character varying
 test_n      | numeric
 big_n       | bigint
 ip_addr     | inet

You might be able to get all that information by joining other information_schema views, or by querying the system tables directly. psql -E might help with that.

The function pg_typeof() correctly shows the use of test_domain, but doesn't report the details of varchar(n) and numeric(p, s) columns.

select pg_typeof(test_id) as test_id, 
       pg_typeof(test_vc) as test_vc,
       pg_typeof(test_n) as test_n,
       pg_typeof(big_n) as big_n,
       pg_typeof(ip_addr) as ip_addr
from test;
   test_id   |      test_vc      | test_n  | big_n  | ip_addr
-------------+-------------------+---------+--------+---------
 test_domain | character varying | numeric | bigint | inet

Using ORDER BY and GROUP BY together

Here is the simplest solution

select m_id,v_id,max(timestamp) from table group by m_id;

Group by m_id but get max of timestamp for each m_id.

Simple way to repeat a string

If you only know the length of the output string (and it may be not divisible by the length of the input string), then use this method:

static String repeat(String s, int length) {
    return s.length() >= length ? s.substring(0, length) : repeat(s + s, length);
}

Usage demo:

for (int i = 0; i < 50; i++)
    System.out.println(repeat("_/?\\", i));

Don't use with empty s and length > 0, since it's impossible to get the desired result in this case.

Load arrayList data into JTable

Basic method for beginners like me.

public void loadDataToJtable(ArrayList<String> liste){
        
    rows = table.getRowCount();

    cols = table.getColumnCount();

    for (int i = 0; i < rows ; i++) {

            for ( int k  = 0; k < cols ; k++) {
            
            for (int h = 0; h < list1.size(); h++) {
                
                String b =  list1.get(h);
                b = table.getValueAt(i, k).toString();
                
            }
        }
    }
}

convert a list of objects from one type to another using lambda expression

I believe something like this should work:

origList.Select(a => new TargetType() { SomeValue = a.SomeValue});

Python pandas insert list into a cell

df3.set_value(1, 'B', abc) works for any dataframe. Take care of the data type of column 'B'. Eg. a list can not be inserted into a float column, at that case df['B'] = df['B'].astype(object) can help.

jquery - fastest way to remove all rows from a very large table

$("#your-table-id").empty();

That's as fast as you get.

Relative URLs in WordPress

I think this is the kind of question only a core developer could/should answer. I've researched and found the core ticket #17048: URLs delivered to the browser should be root-relative. Where we can find the reasons explained by Andrew Nacin, lead core developer. He also links to this [wp-hackers] thread. On both those links, these are the key quotes on why WP doesn't use relative URLs:

Core ticket:

  • Root-relative URLs aren't really proper. /path/ might not be WordPress, it might be outside of the install. So really it's not much different than an absolute URL.

  • Any relative URLs also make it significantly more difficult to perform transformations when the install is moved. The find-replace is going to be necessary in most situations, and having an absolute URL is ironically more portable for those reasons.

  • absolute URLs are needed in numerous other places. Needing to add these in conditionally will add to processing, as well as introduce potential bugs (and incompatibilities with plugins).

[wp-hackers] thread

  • Relative to what, I'm not sure, as WordPress is often in a subdirectory, which means we'll always need to process the content to then add in the rest of the path. This introduces overhead.

  • Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible to properly implement.

  • WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to relocate, it is a global find-replace in the database.


And, on a personal note, more than once I've found theme and plugins bad coded that simply break when WP_CONTENT_URL is defined.
They don't know this can be set and assume that this is true: WP.URL/wp-content/WhatEver, and it's not always the case. And something will break along the way.


The plugin Relative URLs (linked in edse's Answer), applies the function wp_make_link_relative in a series of filters in the action hook template_redirect. It's quite a simple code and seems a nice option.

What's the difference between an Angular component and module

Angular Component

A component is one of the basic building blocks of an Angular app. An app can have more than one component. In a normal app, a component contains an HTML view page class file, a class file that controls the behaviour of the HTML page and the CSS/scss file to style your HTML view. A component can be created using @Component decorator that is part of @angular/core module.

import { Component } from '@angular/core';

and to create a component

@Component({selector: 'greet', template: 'Hello {{name}}!'})
class Greet {
  name: string = 'World';
}

To create a component or angular app here is the tutorial

Angular Module

An angular module is set of angular basic building blocks like component, directives, services etc. An app can have more than one module.

A module can be created using @NgModule decorator.

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

What's the correct way to convert bytes to a hex string in Python 3?

Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

import codecs
codecs.getencoder('hex')(b'foo')[0]

Starting with Python 3.4, there is a less awkward option:

codecs.encode(b'foo', 'hex')

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.

Array to Collection: Optimized code

You can use:

list.addAll(Arrays.asList(array));

How to convert array to SimpleXML

With FluidXML you can generate, starting from a PHP Array, an XML for SimpleXML with... just two lines of code.

$fluidxml  = fluidxml($array);
$simplexml = simplexml_import_dom($fluidxml->dom());

An example array could be

$array = [ 'doc' => [
              'fruit' => 'orange',
              'cake'  => [
                   '@id' => '123', 
                   '@'   => 'tiramisu' ],
              [ 'pasta' => 'matriciana' ],
              [ 'pasta' => 'boscaiola'  ]
] ];

https://github.com/servo-php/fluidxml

How can I read Chrome Cache files?

I've made short stupid script which extracts JPG and PNG files:

#!/usr/bin/php
<?php
 $dir="/home/user/.cache/chromium/Default/Cache/";//Chrome or chromium cache folder. 
 $ppl="/home/user/Desktop/temporary/"; // Place for extracted files 

 $list=scandir($dir);
 foreach ($list as $filename)
 {

 if (is_file($dir.$filename))
    {
        $cont=file_get_contents($dir.$filename);
        if  (strstr($cont,'JFIF'))
        {
            echo ($filename."  JPEG \n");
            $start=(strpos($cont,"JFIF",0)-6);
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            $cont=substr($cont,$start,$end-6);
            $wholename=$ppl.$filename.".jpg";
            file_put_contents($wholename,$cont);
            echo("Saving :".$wholename." \n" );


                }
        elseif  (strstr($cont,"\211PNG"))
        {
            echo ($filename."  PNG \n");
            $start=(strpos($cont,"PNG",0)-1);
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            $cont=substr($cont,$start,$end-1);
            $wholename=$ppl.$filename.".png";
            file_put_contents($wholename,$cont);
            echo("Saving :".$wholename." \n" );


                }
        else
        {
            echo ($filename."  UNKNOWN \n");
        }
    }
 }
?>

ValueError: setting an array element with a sequence

for those who are having trouble with similar problems in Numpy, a very simple solution would be:

defining dtype=object when defining an array for assigning values to it. for instance:

out = np.empty_like(lil_img, dtype=object)

Http Post With Body

You can use HttpClient and HttpPost to send a json string as body:

public void post(String completeUrl, String body) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(completeUrl);
    httpPost.setHeader("Content-type", "application/json");
    try {
        StringEntity stringEntity = new StringEntity(body);
        httpPost.getRequestLine();
        httpPost.setEntity(stringEntity);

        httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Json body example:

{
  "param1": "value 1",
  "param2": 123,
  "testStudentArray": [
    {
      "name": "Test Name 1",
      "gpa": 3.5
    },
    {
      "name": "Test Name 2",
      "gpa": 3.8
    }
  ]
}

How to enable CORS in apache tomcat

Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!

How to work with complex numbers in C?

This code will help you, and it's fairly self-explanatory:

#include <stdio.h>      /* Standard Library of Input and Output */
#include <complex.h>    /* Standard Library of Complex Numbers */

int main() {

    double complex z1 = 1.0 + 3.0 * I;
    double complex z2 = 1.0 - 4.0 * I;

    printf("Working with complex numbers:\n\v");

    printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));

    double complex sum = z1 + z2;
    printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));

    double complex difference = z1 - z2;
    printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));

    double complex product = z1 * z2;
    printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));

    double complex quotient = z1 / z2;
    printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));

    double complex conjugate = conj(z1);
    printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));

    return 0;
}

  with:

creal(z1): get the real part (for float crealf(z1), for long double creall(z1))

cimag(z1): get the imaginary part (for float cimagf(z1), for long double cimagl(z1))

Another important point to remember when working with complex numbers is that functions like cos(), exp() and sqrt() must be replaced with their complex forms, e.g. ccos(), cexp(), csqrt().

Java regex email

FWIW, here is the Java code we use to validate email addresses. The Regexp's are very similar:

public static final Pattern VALID_EMAIL_ADDRESS_REGEX = 
    Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);

public static boolean validate(String emailStr) {
        Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
        return matcher.find();
}

Works fairly reliably.