Programs & Examples On #Hessian

Hessian is a simple binary protocol for connecting web services.

Autowiring fails: Not an managed Type

In my case, when using IntelliJ, I had multiple modules in the project. The main module was dependent on another module which had the maven dependencies on Spring.

The main module had Entitys and so did the second module. But when I ran the main module, only the Entitys from the second module got recognized as managed classes.

I then added Spring dependencies on the main module as well, and guess what? It recognized all the Entitys.

How to generate .NET 4.0 classes from xsd?

For a quick and lazy solution, (and not using VS at all) try these online converters:

  • xsd-to-xml-converter here
  • xmltocsharp converter here

XSD => XML => C# classes

Example XSD:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="shiporder">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="orderperson" type="xs:string"/>
      <xs:element name="shipto">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="address" type="xs:string"/>
            <xs:element name="city" type="xs:string"/>
            <xs:element name="country" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="item" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="note" type="xs:string" minOccurs="0"/>
            <xs:element name="quantity" type="xs:positiveInteger"/>
            <xs:element name="price" type="xs:decimal"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="orderid" type="xs:string" use="required"/>
  </xs:complexType>
</xs:element>

</xs:schema>

Converts to XML:

<?xml version="1.0" encoding="utf-8"?>
<!-- Created with Liquid Technologies Online Tools 1.0 (https://www.liquid-technologies.com) -->
<shiporder xsi:noNamespaceSchemaLocation="schema.xsd" orderid="string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <orderperson>string</orderperson>
  <shipto>
    <name>string</name>
    <address>string</address>
    <city>string</city>
    <country>string</country>
  </shipto>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>3229484693</quantity>
    <price>-6894.465094196054907</price>
  </item>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>2181272155</quantity>
    <price>-2645.585094196054907</price>
  </item>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>2485046602</quantity>
    <price>4023.034905803945093</price>
  </item>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>1342091380</quantity>
    <price>-810.825094196054907</price>
  </item>
</shiporder>

Which converts to this class structure:

   /* 
    Licensed under the Apache License, Version 2.0

    http://www.apache.org/licenses/LICENSE-2.0
    */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="shipto")]
    public class Shipto {
        [XmlElement(ElementName="name")]
        public string Name { get; set; }
        [XmlElement(ElementName="address")]
        public string Address { get; set; }
        [XmlElement(ElementName="city")]
        public string City { get; set; }
        [XmlElement(ElementName="country")]
        public string Country { get; set; }
    }

    [XmlRoot(ElementName="item")]
    public class Item {
        [XmlElement(ElementName="title")]
        public string Title { get; set; }
        [XmlElement(ElementName="note")]
        public string Note { get; set; }
        [XmlElement(ElementName="quantity")]
        public string Quantity { get; set; }
        [XmlElement(ElementName="price")]
        public string Price { get; set; }
    }

    [XmlRoot(ElementName="shiporder")]
    public class Shiporder {
        [XmlElement(ElementName="orderperson")]
        public string Orderperson { get; set; }
        [XmlElement(ElementName="shipto")]
        public Shipto Shipto { get; set; }
        [XmlElement(ElementName="item")]
        public List<Item> Item { get; set; }
        [XmlAttribute(AttributeName="noNamespaceSchemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
        public string NoNamespaceSchemaLocation { get; set; }
        [XmlAttribute(AttributeName="orderid")]
        public string Orderid { get; set; }
        [XmlAttribute(AttributeName="xsi", Namespace="http://www.w3.org/2000/xmlns/")]
        public string Xsi { get; set; }
    }

}

Attention! Take in account that this is just to Get-You-Started, the results obviously need refinements!

Datetime current year and month in Python

>>> from datetime import date
>>> date.today().month
2
>>> date.today().year
2020
>>> date.today().day
13

Using WGET to run a cronjob PHP

You could tell wget to not download the contents in a couple of different ways:

wget --spider http://www.example.com/cronit.php

which will just perform a HEAD request but probably do what you want

wget -O /dev/null http://www.example.com/cronit.php

which will save the output to /dev/null (a black hole)

You might want to look at wget's -q switch too which prevents it from creating output

I think that the best option would probably be:

wget -q --spider http://www.example.com/cronit.php

that's unless you have some special logic checking the HTTP method used to request the page

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

In Java, what does NaN mean?

NaN stands for Not a Number. It is used to signify any value that is mathematically undefined. Like dividing 0.0 by 0.0. You can look here for more information: https://web.archive.org/web/20120819091816/http://www.concentric.net/~ttwang/tech/javafloat.htm

Post your program here if you need more help.

Circular gradient in android

Here is the complete xml with gradient, stoke & circular shape.

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

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <!-- You can use gradient with below attributes-->
    <gradient
        android:angle="90"
        android:centerColor="#555994"
        android:endColor="#b5b6d2"
        android:startColor="#555994"
        android:type="linear" />

    <!-- You can omit below tag if you don't need stroke -->
   <stroke android:color="#3b91d7" android:width="5dp"/>

    <!-- Set the same value for both width and height to get a circular shape -->
    <size android:width="200dp" android:height="200dp"/>


    <!--if you need only a single color filled shape-->
    <solid android:color="#e42828"/>


</shape>

How to drop SQL default constraint without knowing its name?

Drop all default contstraints in a database - safe for nvarchar(max) threshold.

/* WARNING: THE SAMPLE BELOW; DROPS ALL THE DEFAULT CONSTRAINTS IN A DATABASE */ 
/* MAY 03, 2013 - BY WISEROOT  */
declare @table_name nvarchar(128)
declare @column_name nvarchar(128)
declare @df_name nvarchar(128)
declare @cmd nvarchar(128) 

declare table_names cursor for 
 SELECT t.name TableName, c.name ColumnName
 FROM sys.columns c INNER JOIN
     sys.tables t ON c.object_id = t.object_id INNER JOIN
     sys.schemas s ON t.schema_id = s.schema_id
     ORDER BY T.name, c.name

     open table_names
fetch next from table_names into @table_name , @column_name
while @@fetch_status = 0
BEGIN

if exists (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = @table_name and c.name = @column_name)
BEGIN
    SET @df_name = (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = @table_name and c.name = @column_name)
    select @cmd = 'ALTER TABLE [' + @table_name +  '] DROP CONSTRAINT [' +  @df_name + ']'
    print @cmd
    EXEC sp_executeSQL @cmd;
END

  fetch next from table_names into @table_name , @column_name
END

close table_names 
deallocate table_names

How can I use Helvetica Neue Condensed Bold in CSS?

I had the same problem and trouble getting it to work on all browsers.

So this is the best font stack for Helvetica Neue Condensed Bold I could find:

font-family: "HelveticaNeue-CondensedBold", "HelveticaNeueBoldCondensed", "HelveticaNeue-Bold-Condensed", "Helvetica Neue Bold Condensed", "HelveticaNeueBold", "HelveticaNeue-Bold", "Helvetica Neue Bold", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosCnBold', "Helvetica", "Tahoma", "Geneva", "Arial Narrow", "Arial", sans-serif; font-weight:600; font-stretch:condensed;

Even more stacks to find at:

http://rachaelmoore.name/posts/design/css/web-safe-helvetica-font-stack/

How to update values in a specific row in a Python Pandas DataFrame?

I needed to update and add suffix to few rows of the dataframe on conditional basis based on the another column's value of the same dataframe -

df with column Feature and Entity and need to update Entity based on specific feature type

df2= df1 df.loc[df.Feature == 'dnb', 'Entity'] = 'duns_' + df.loc[df.Feature == 'dnb','Entity']

Java Reflection Performance

Yes, it is significantly slower. We were running some code that did that, and while I don't have the metrics available at the moment, the end result was that we had to refactor that code to not use reflection. If you know what the class is, just call the constructor directly.

How to dynamically load a Python class

import importlib

module = importlib.import_module('my_package.my_module')
my_class = getattr(module, 'MyClass')
my_instance = my_class()

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

As per the docs:

You can set annotation processor argument (room.schemaLocation) to tell Room to export the schema into a folder. Even though it is not mandatory, it is a good practice to have version history in your codebase and you should commit that file into your version control system (but don't ship it with your app!).

So if you don't need to check the schema and you want to get rid of the warning, just add exportSchema = false to your RoomDatabase, as follows.

@Database(entities = { YourEntity.class }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
   //...
}

If you follow @mikejonesguy answer below, you will follow the good practice mentioned in the docs :). Basically you will get a .json file in your ../app/schemas/ folder. And it looks something like this:

{
  "formatVersion": 1,
  "database": {
    "version": 1,
    "identityHash": "53db508c5248423325bd5393a1c88c03",
    "entities": [
      {
        "tableName": "sms_table",
        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` TEXT, `date` INTEGER, `client_id` INTEGER)",
        "fields": [
          {
            "fieldPath": "id",
            "columnName": "id",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "message",
            "columnName": "message",
            "affinity": "TEXT"
          },
          {
            "fieldPath": "date",
            "columnName": "date",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "clientId",
            "columnName": "client_id",
            "affinity": "INTEGER"
          }
        ],
        "primaryKey": {
          "columnNames": [
            "id"
          ],
          "autoGenerate": true
        },
        "indices": [],
        "foreignKeys": []
      }
    ],
    "setupQueries": [
      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"53db508c5248423325bd5393a1c88c03\")"
    ]
  }
}

If my understanding is correct, you will get such a file with every database version update, so that you can easily follow the history of your db.

Face recognition Library

pam-face-authentication a PAM Module for Face Authentication: but it would require some work to get what you want. A quick test showed, that the recognition rate are not as good as those of VeriLook from NeuroTechnology.

Malic is another open source face recognition software, which uses Gabor Wavelet descriptors. But the last update to the source is 3 years old.

From the website: "Malic is an opensource face recognition software which uses gabor wavelet. It is realtime face recognition system that based on Malib and CSU Face Identification Evaluation System (csuFaceIdEval).Uses Malib library for realtime image processing and some of csuFaceIdEval for face recognition."

Further this could be of interest:

gaborboosting: A scientific program applied on Face Recognition with Gabor Wavelet and AdaBoost Algorithm

Feature Extraction Library - FELib refers to "Face Annotation by Transductive Kernel Fisher Discriminant,"

Print "\n" or newline characters as part of the output on terminal

If you're in control of the string, you could also use a 'Raw' string type:

>>> string = r"abcd\n"
>>> print(string)
abcd\n

Datagridview: How to set a cell in editing mode?

private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  if (DgvRoomInformation.CurrentCell.ColumnIndex == 4)  //example-'Column index=4'
  {
    DgvRoomInformation.BeginEdit(true);   
  }
}

Prevent HTML5 video from being downloaded (right-click saved)?

Short Answer: Encrypt the link like youtube does, don't know how than ask youtube/google of how they do it. (Just in case you want to get straight into the point.)

I would like to point out to anyone that this is possible because youtube does it and if they can so can any other website and it isn't from the browser either because I tested it on a couple browsers such as microsoft edge and internet explorer and so there is a way to disable it and seen that people still say it...I tries looking for an answer because if youtube can than there has to be a way and the only way to see how they do it is if someone looked into the scripts of youtube which I am doing now. I also checked to see if it was a custom context menu as well and it isn't because the context menu is over flowing the inspect element and I mean like it is over it and I looked and it never creates a new class and also it is impossible to actually access inspect element with javascript so it can't be. You can tell when it double right-click a youtube video that it pops up the context menu for chrome. Besides...youtube wouldn't add that function in. I am doing research and looking through the source of youtube so I will be back if I find the answer...if anyone says you can't than, well they didn't do research like I have. The only way to download youtube videos is through a video download.

Okay...I did research and my research stays that you can disable it except there is no javascript to it...you have to be able to encrypt the links to the video for you to be able to disable it because I think any browser won't show it if it can't find it and when I opened a youtube video link it showed as this "blob:https://www.youtube.com/e5c4808e-297e-451f-80da-3e838caa1275" without quotes so it is encrypting it so it cannot be saved...you need to know php for that but like the answer you picked out of making it harder, youtube makes it the hardest of heavy encrypting it, you need to be an advance php programmer but if you don't know that than take the person you picked as best answer of making it hard to download it...but if you know php than heavy encrypt the video link so it only is able to be read on yours...I don't know how to explain how they do it but they did and there is a way. The way youtube Encrypts there videos is quite smart so if you want to know how to than just ask youtube/google of how they do it...hope this helps for you although you already picked a best answer. So encrypting the link is best in short terms.

CSS3 equivalent to jQuery slideUp and slideDown?

Aight fam, after some research and experimenting, I think the best approach is to have the thing's height at 0px, and let it transition to an exact height. You get the exact height with JavaScript. The JavaScript isn't doing the animating, it's just changing the height value. Check it:

function setInfoHeight() {
  $(window).on('load resize', function() {
    $('.info').each(function () {
      var current = $(this);
      var closed = $(this).height() == 0;
      current.show().height('auto').attr('h', current.height() );
      current.height(closed ? '0' : current.height());
    });
  });

Whenever the page loads or is resized, the element with class info will get its h attribute updated. Then you could have a button trigger the style="height: __" to set it to that previously set h value.

function moreInformation() {
  $('.icon-container').click(function() {
    var info = $(this).closest('.dish-header').next('.info'); // Just the one info
    var icon = $(this).children('.info-btn'); // Select the logo

    // Stop any ongoing animation loops. Without this, you could click button 10
    // times real fast, and watch an animation of the info showing and closing
    // for a few seconds after
    icon.stop();
    info.stop();

    // Flip icon and hide/show info
    icon.toggleClass('flip');

    // Metnod 1, animation handled by JS
    // info.slideToggle('slow');

    // Method 2, animation handled by CSS, use with setInfoheight function
    info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');

  });
};

Here's the styling for the info class.

.info {
  display: inline-block;
  height: 0px;
  line-height: 1.5em;
  overflow: hidden;
  padding: 0 1em;
  transition: height 0.6s, padding 0.6s;
  &.active {
    border-bottom: $thin-line;
    padding: 1em;
  }
}

I used this on one of my projects so class names are specific. You can change them up however you like.

The styling might not be supported cross-browser. Works fine in chrome.

Below is the live example for this code. Just click on the ? icon to start the animation

CodePen

string.split - by multiple character delimiter

string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);

Rendering raw html with reactjs

I used this library called Parser. It worked for what I needed.

import React, { Component } from 'react';    
import Parser from 'html-react-parser';

class MyComponent extends Component {
  render() {
    <div>{Parser(this.state.message)}</div>
  }
};

How to move git repository with all branches from bitbucket to github?

There is the Importing a repository with GitHub Importer

If you have a project hosted on another version control system as Mercurial, you can automatically import it to GitHub using the GitHub Importer tool.

  1. In the upper-right corner of any page, click , and then click Import repository.
  2. Under "Your old repository's clone URL", type the URL of the project you want to import.
  3. Choose your user account or an organization to own the repository, then type a name for the repository on GitHub.
  4. Specify whether the new repository should be public or private.
    • Public repositories are visible to any user on GitHub, so you can benefit from GitHub's collaborative community.
    • Public or private repository radio buttonsPrivate repositories are only available to the repository owner, as well as any collaborators you choose to share with.
  5. Review the information you entered, then click Begin import.

You'll receive an email when the repository has been completely imported.

  1. https://help.github.com/categories/importing-your-projects-to-github
  2. https://help.github.com/articles/importing-a-repository-with-github-importer/

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3, dict.values() (along with dict.keys() and dict.items()) returns a view, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values() in a call to list like so:

v = list(d.values())
{names[i]:v[i] for i in range(len(names))}

JQuery / JavaScript - trigger button click from another button click event

By using JavaScript: document.getElementById("myBtn").click();

How to print (using cout) a number in binary form?

#include <iostream> 
#include <cmath>       // in order to use pow() function
using namespace std; 

string show_binary(unsigned int u, int num_of_bits);

int main() 
{ 

  cout << show_binary(128, 8) << endl;   // should print 10000000
  cout << show_binary(128, 5) << endl;   // should print 00000
  cout << show_binary(128, 10) << endl;  // should print 0010000000

  return 0; 
}

string show_binary(unsigned int u, int num_of_bits) 
{ 
  string a = "";

  int t = pow(2, num_of_bits);   // t is the max number that can be represented

  for(t; t>0; t = t/2)           // t iterates through powers of 2
      if(u >= t){                // check if u can be represented by current value of t
          u -= t;
          a += "1";               // if so, add a 1
      }
      else {
          a += "0";               // if not, add a 0
      }

  return a ;                     // returns string
}

Does Typescript support the ?. operator? (And, what's it called?)

Not as nice as a single ?, but it works:

var thing = foo && foo.bar || null;

You can use as many && as you like:

var thing = foo && foo.bar && foo.bar.check && foo.bar.check.x || null;

Create directories using make file

Or, KISS.

DIRS=build build/bins

... 

$(shell mkdir -p $(DIRS))

This will create all the directories after the Makefile is parsed.

nginx upload client_max_body_size issue

Does your upload die at the very end? 99% before crashing? Client body and buffers are key because nginx must buffer incoming data. The body configs (data of the request body) specify how nginx handles the bulk flow of binary data from multi-part-form clients into your app's logic.

The clean setting frees up memory and consumption limits by instructing nginx to store incoming buffer in a file and then clean this file later from disk by deleting it.

Set body_in_file_only to clean and adjust buffers for the client_max_body_size. The original question's config already had sendfile on, increase timeouts too. I use the settings below to fix this, appropriate across your local config, server, & http contexts.

client_body_in_file_only clean;
client_body_buffer_size 32K;

client_max_body_size 300M;

sendfile on;
send_timeout 300s;

How can I convert a Word document to PDF?

This is quite a hard task, ever harder if you want perfect results (impossible without using Word) as such the number of APIs that just do it all for you in pure Java and are open source is zero I believe (Update: I am wrong, see below).

Your basic options are as follows:

  1. Using JNI/a C# web service/etc script MS Office (only option for 100% perfect results)
  2. Using the available APIs script Open Office (90+% perfect)
  3. Use Apache POI & iText (very large job, will never be perfect).

Update - 2016-02-11 Here is a cut down copy of my blog post on this subject which outlines existing products that support Word-to-PDF in Java.

Converting Microsoft Office (Word, Excel) documents to PDFs in Java

Three products that I know of can render Office documents:

yeokm1/docs-to-pdf-converter Irregularly maintained, Pure Java, Open Source Ties together a number of libraries to perform the conversion.

xdocreport Actively developed, Pure Java, Open Source It's Java API to merge XML document created with MS Office (docx) or OpenOffice (odt), LibreOffice (odt) with a Java model to generate report and convert it if you need to another format (PDF, XHTML...).

Snowbound Imaging SDK Closed Source, Pure Java Snowbound appears to be a 100% Java solution and costs over $2,500. It contains samples describing how to convert documents in the evaluation download.

OpenOffice API Open Source, Not Pure Java - Requires Open Office installed OpenOffice is a native Office suite which supports a Java API. This supports reading Office documents and writing PDF documents. The SDK contains an example in document conversion (examples/java/DocumentHandling/DocumentConverter.java). To write PDFs you need to pass the "writer_pdf_Export" writer rather than the "MS Word 97" one. Or you can use the wrapper API JODConverter.

JDocToPdf - Dead as of 2016-02-11 Uses Apache POI to read the Word document and iText to write the PDF. Completely free, 100% Java but has some limitations.

Pass a javascript variable value into input type hidden value

You could give your hidden field an id:

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

and then when you want to assign its value:

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

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

Command to run a .bat file

You can use Cmd command to run Batch file.

Here is my way =>

cmd /c ""Full_Path_Of_Batch_Here.cmd" "

More information => cmd /?

SVN 405 Method Not Allowed

I also met this problem just now and solved it in this way. So I recorded it here, and I wish it be useful for others.

Scenario:

  1. Before I commit the code, revision: 100
  2. (Someone else commits the code... revision increased to 199)
  3. I (forgot to run "svn up", ) commit the code, now my revision: 200
  4. I run "svn up".

The error occurred.

Solution:

  1. $ mv current_copy copy_back # Rename the current code copy
  2. $ svn checkout current_copy # Check it out again
  3. $ cp copy_back/ current_copy # Restore your modifications

How to update a single library with Composer?

Just use

composer require {package/packagename}

like

composer require phpmailer/phpmailer

if the package is not in the vendor folder.. composer installs it and if the package exists, composer update package to the latest version.

How to position three divs in html horizontally?

I know this is a very old question. Just posting this here as I solved this problem using FlexBox. Here is the solution

_x000D_
_x000D_
#container {
  height: 100%;
  width: 100%;
  display: flex;
}
#leftThing {
  width: 25%;
  background-color: blue;
}
#content {
  width: 50%;
  background-color: green;
}
#rightThing {
  width: 25%;
  background-color: yellow;
}
_x000D_
<div id="container">

  <div id="leftThing">
    Left Side Menu
  </div>

  <div id="content">
    Random Content
  </div>

  <div id="rightThing">
    Right Side Menu
  </div>

</div>
_x000D_
_x000D_
_x000D_

Just had to add display:flex to the container! No floats required.

Value Change Listener to JTextField

If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.

usernameTextField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
    }
});

Which websocket library to use with Node.js?

npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.

var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;

var app = express();
    app.use(express.static(__dirname+ "/../"));
    app.get('/someGetRequest', function(req, res, next) {
       console.log('receiving get request');
    });
    app.post('/somePostRequest', function(req, res, next) {
       console.log('receiving post request');
    });
    app.listen(80); //port 80 need to run as root

    console.log("app listening on %d ", 80);

var server = http.createServer(app);
    server.listen(port);

console.log("http server listening on %d", port);

var userId;
var wss = new WebSocketServer({server: server});
    wss.on("connection", function (ws) {

    console.info("websocket connection open");

    var timestamp = new Date().getTime();
    userId = timestamp;

    ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));


    ws.on("message", function (data, flags) {
        console.log("websocket received a message");
        var clientMsg = data;

        ws.send(JSON.stringify({msg:{connectionId:userId}}));


    });

    ws.on("close", function () {
        console.log("websocket connection close");
    });
});
console.log("websocket server created");

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

Here is my answer that I had used in my app. It shows text in center of the screen.

<TextView
    android:id="@+id/txtSubject"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/subject"
    android:layout_margin="10dp"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge" />

What is the default database path for MongoDB?

I have version 2.0.7 installed on Ubuntu and it defaulted to /var/lib/mongodb/ and that is also what was placed into my /etc/mongodb.conf file.

Remove the first character of a string

Depending on the structure of the string, you can use lstrip:

str = str.lstrip(':')

But this would remove all colons at the beginning, i.e. if you have ::foo, the result would be foo. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

QUERY syntax using cell reference

none of the above answers worked for me. This one did:

=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)

Finding the average of an array using JS

The MacGyver way,just for lulz

_x000D_
_x000D_
var a = [80, 77, 88, 95, 68];_x000D_
_x000D_
console.log(eval(a.join('+'))/a.length)
_x000D_
_x000D_
_x000D_

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

How to add Class in <li> using wp_nav_menu() in Wordpress?

<?php
    echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
            wp_nav_menu(
                    array(
                        'menu' => $nav_menu, 
                        'container'  => false,
                        'container_class'   => false,
                        'menu_class'        => false,
                        'items_wrap'        => '%3$s',
                                            'depth'             => 1,
                                            'echo'              => false
                            )
                    )
            );
?>

start MySQL server from command line on Mac OS Lion

As this helpful article states: On OS X to start/stop MySQL from the command line:

sudo /usr/local/mysql/support-files/mysql.server start 
sudo /usr/local/mysql/support-files/mysql.server stop 

On Linux start/stop from the command line:

/etc/init.d/mysqld start 
/etc/init.d/mysqld stop 
/etc/init.d/mysqld restart 

Some Linux flavours offer the service command too

# service mysqld start 
# service mysqld stop 
# service mysqld restart

or

 # service mysql start 
 # service mysql stop 
 # service mysql restart 

webpack is not recognized as a internal or external command,operable program or batch file

Sometimes npm install -g webpack does not save properly. Better to use npm install webpack --save . It worked for me.

oracle - what statements need to be committed?

DML have to be committed or rollbacked. DDL cannot.

http://www.orafaq.com/faq/what_are_the_difference_between_ddl_dml_and_dcl_commands

You can switch auto-commit on and that's again only for DML. DDL are never part of transactions and therefore there is nothing like an explicit commit/rollback.

truncate is DDL and therefore commited implicitly.

Edit
I've to say sorry. Like @DCookie and @APC stated in the comments there exist sth like implicit commits for DDL. See here for a question about that on Ask Tom. This is in contrast to what I've learned and I am still a bit curious about.

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

Creating and playing a sound in swift

Here's a bit of code I've got added to FlappySwift that works:

import SpriteKit
import AVFoundation

class GameScene: SKScene {

    // Grab the path, make sure to add it to your project!
    var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
    var audioPlayer = AVAudioPlayer()

    // Initial setup
    override func didMoveToView(view: SKView) {
        audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
        audioPlayer.prepareToPlay()
    }

    // Trigger the sound effect when the player grabs the coin
    func didBeginContact(contact: SKPhysicsContact!) {
        audioPlayer.play()
    }

}

Git and nasty "error: cannot lock existing info/refs fatal"

In case of bettercodes.org, the solution is more poetic - the only problem may be in rights assigned to the project members. Simple members don't have write rights! Please make sure that you have the Moderator or Administrator rights. This needs to be set at bettercodes.org at the project settings by an Administrator, of course.

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 8.0 navigate to:

Server > Data Import

A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.

Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.

Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.

That's it!

For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard

Node.js Logging

Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.

The fix is to change logger.trace to logger.error in the body of errorLogger.

Should I use != or <> for not equal in T-SQL?

Technically they function the same if you’re using SQL Server AKA T-SQL. If you're using it in stored procedures there is no performance reason to use one over the other. It then comes down to personal preference. I prefer to use <> as it is ANSI compliant.

You can find links to the various ANSI standards at...

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

How to get named excel sheets while exporting from SSRS

You could use -sed- and -grep- to replace or write to the xml header of each file specifying your desired sheet name, e.g., sheetname1, between any occurrence of the tags:

<Sheetnames>?sheetname1?</Sheetnames>

Closing Applications

System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit() method is typically called from within a message loop, and forces Run() to return. To exit a message loop for the current thread only, call ExitThread(). This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run().

System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.

I hope it is best to use Application.Exit

See also these links:

Facebook Oauth Logout

You can do this with the access_token:

$access_array = split("\|", $access_token);

$session_key = $access_array[1];

You can use that $session key in the PHP SDK to generate a functional logout URL.

$logoutUrl = $facebook->getLogoutUrl(array('next' => $logoutUrl, 'session_key' => $session_key));

This ends the browser's facebook session.

"RangeError: Maximum call stack size exceeded" Why?

Here it fails at Array.apply(null, new Array(1000000)) and not the .map call.

All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.

You need to the understand what is call stack.

Stack is a LIFO data structure, which is like an array that only supports push and pop methods.

Let me explain how it works by a simple example:

function a(var1, var2) {
    var3 = 3;
    b(5, 6);
    c(var1, var2);
}
function b(var5, var6) {
    c(7, 8);
}
function c(var7, var8) {
}

When here function a is called, it will call b and c. When b and c are called, the local variables of a are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.

We implement the callStack as array:

var callStack = [];

Everytime a function called we push the local variables into the stack:

callStack.push(currentLocalVaraibles);

Once the function call is finished(like in a, we have called b, b is finished executing and we must return to a), we get back the local variables by poping the stack:

currentLocalVaraibles = callStack.pop();

So when in a we want to call c again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000)), your currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.

Same error happens on infinite recursion(function a() { a() }) as too many times, stuff has been pushed to the call stack.

Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.

Git command to display HEAD commit id?

Old thread, still for future reference...:) even following works

git show-ref --head

by default HEAD is filtered out. Be careful about following though ; plural "heads" with a 's' at the end. The following command shows branches under "refs/heads"

 git show-ref --heads

FormsAuthentication.SignOut() does not log the user out

This started happening to me when I set the authentication > forms > Path property in Web.config. Removing that fixed the problem, and a simple FormsAuthentication.SignOut(); again removed the cookie.

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

What is the size limit of a post request?

One of the best solutions for this, you do not use multiple or more than 1,000 input fields. You can concatenate multiple inputs with any special character, for ex. @.

See this:

<input type='text' name='hs1' id='hs1'>
<input type='text' name='hs2' id='hs2'>
<input type='text' name='hs3' id='hs3'>
<input type='text' name='hs4' id='hs4'>
<input type='text' name='hs5' id='hs5'>

<input type='hidden' name='hd' id='hd'>

Using any script (JavaScript or JScript),

document.getElementById("hd").value = document.getElementById("hs1").value+"@"+document.getElementById("hs2").value+"@"+document.getElementById("hs3").value+"@"+document.getElementById("hs4").value+"@"+document.getElementById("hs5").value

With this, you will bypass the max_input_vars issue. If you increase max_input_vars in the php.ini file, that is harmful to the server because it uses more server cache memory, and this can sometimes crash the server.

python pandas convert index to datetime

It should work as expected. Try to run the following example.

import pandas as pd
import io

data = """value          
"2015-09-25 00:46"    71.925000
"2015-09-25 00:47"    71.625000
"2015-09-25 00:48"    71.333333
"2015-09-25 00:49"    64.571429
"2015-09-25 00:50"    72.285714"""

df = pd.read_table(io.StringIO(data), delim_whitespace=True)

# Converting the index as date
df.index = pd.to_datetime(df.index)

# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df

#                          value  A   B
# 2015-09-25 00:46:00  71.925000  0  46
# 2015-09-25 00:47:00  71.625000  0  47
# 2015-09-25 00:48:00  71.333333  0  48
# 2015-09-25 00:49:00  64.571429  0  49
# 2015-09-25 00:50:00  72.285714  0  50

Git: How to return from 'detached HEAD' state

If you remember which branch was checked out before (e.g. master) you could simply

git checkout master

to get out of detached HEAD state.

Generally speaking: git checkout <branchname> will get you out of that.

If you don't remember the last branch name, try

git checkout -

This also tries to check out your last checked out branch.

Writing binary number system in C code

Use BOOST_BINARY (Yes, you can use it in C).

#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);

This macro is expanded to an octal literal during preprocessing.

How to retrieve Jenkins build parameters using the Groovy API?

I've just got this working, so specifically, using the Groovy Postbuild plugin, you can do the following:

def paramText
def actionList = manager.build.getActions(hudson.model.ParametersAction)
if (actionList.size() != 0)
{
  def pA = actionList.get(0)
  paramText = pA.createVariableResolver(manager.build).resolve("MY_PARAM_NAME")
}

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

If your data file is structured like this

col1, col2, col3
   1,    2,    3
  10,   20,   30
 100,  200,  300

then numpy.genfromtxt can interpret the first line as column headers using the names=True option. With this you can access the data very conveniently by providing the column header:

data = np.genfromtxt('data.txt', delimiter=',', names=True)
print data['col1']    # array([   1.,   10.,  100.])
print data['col2']    # array([   2.,   20.,  200.])
print data['col3']    # array([   3.,   30.,  300.])

Since in your case the data is formed like this

row1,   1,  10, 100
row2,   2,  20, 200
row3,   3,  30, 300

you can achieve something similar using the following code snippet:

labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
data = {label: row for label, row in zip(labels, raw_data)}

The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt creates using the names=True option:

print data['row1']    # array([   1.,   10.,  100.])
print data['row2']    # array([   2.,   20.,  200.])
print data['row3']    # array([   3.,   30.,  300.])

Cannot find or open the PDB file in Visual Studio C++ 2010

I ran into a similar problem where Visual Studio (2017) said it could not find my project's PDB file. I could see the PDB file did exist in the correct path. I had to Clean and Rebuild the project, then Visual Studio recognized the PDB file and debugging worked.

Sending a notification from a service in Android

Both Activity and Service actually extend Context so you can simply use this as your Context within your Service.

NotificationManager notificationManager =
    (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);

How to execute two mysql queries as one in PHP/MYSQL?

Using SQL_CALC_FOUND_ROWS you can't.

The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.

As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.

Perhaps you'd be best off doing this as as subquery:

SELECT 
 (select count(*) from my_table WHERE Name LIKE '%prashant%') 
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;

Convert Decimal to Varchar

Hope this will help .

DECLARE  @emp_cond nvarchar(Max) =' ',@LOCATION_ID  NUMERIC(18,0)   
SET@LOCATION_ID=10110000000
IF CAST(@LOCATION_ID AS VARCHAR(18))<>' ' 
            BEGIN
                SELECT @emp_cond= @emp_cond + N' AND 
CM.STATIC_EMP_INFO.EMP_ID = ' ' '+  CAST(@LOCATION_ID AS VARCHAR(18))  +' ' ' '
           END
print  @emp_cond  
EXEC( @emp_cond) 

How to pass command line arguments to a rake task

To run rake tasks with traditional arguments style:

rake task arg1 arg2

And then use:

task :task do |_, args|
  puts "This is argument 1: #{args.first}"
end

Add following patch of rake gem:

Rake::Application.class_eval do

  alias origin_top_level top_level

  def top_level
    @top_level_tasks = [top_level_tasks.join(' ')]
    origin_top_level
  end

  def parse_task_string(string) # :nodoc:
    parts = string.split ' '
    return parts.shift, parts
  end

end

Rake::Task.class_eval do

  def invoke(*args)
    invoke_with_call_chain(args, Rake::InvocationChain::EMPTY)
  end

end

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I got the same error since Application pool was stopped in IIS. After starting the App Pool, the issue was resolved.

JBoss vs Tomcat again

First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.

Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.

How to decide whether to use Tomcat or a full stack Java EE application server:

When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:

  1. JMS messaging for asynchronous integration
  2. Web Services engine (JAX-WS and/or JAX-RS)
  3. Management capabilities like JMX and a scripted administration interface
  4. Advanced security, e.g. out-of-the-box integration with 3rd party directories
  5. EAR file instead of "only" WAR file support
  6. all the other "great" Java EE features I can't remember :-)

In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.

Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.

my 2 cent

Is it possible to have placeholders in strings.xml for runtime values?

Formatting and Styling

Yes, see the following from String Resources: Formatting and Styling

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

Basic Usage

Note that getString has an overload that uses the string as a format string:

String text = res.getString(R.string.welcome_messages, username, mailCount);

Plurals

If you need to handle plurals, use this:

<plurals name="welcome_messages">
    <item quantity="one">Hello, %1$s! You have a new message.</item>
    <item quantity="other">Hello, %1$s! You have %2$d new messages.</item>
</plurals>

The first mailCount param is used to decide which format to use (single or plural), the other params are your substitutions:

Resources res = getResources();
String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);

See String Resources: Plurals for more details.

How to create XML file with specific structure in Java

There is no need for any External libraries, the JRE System libraries provide all you need.

I am infering that you have a org.w3c.dom.Document object you would like to write to a file

To do that, you use a javax.xml.transform.Transformer:

import org.w3c.dom.Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

public class XMLWriter {
    public static void writeDocumentToFile(Document document, File file) {

        // Make a transformer factory to create the Transformer
        TransformerFactory tFactory = TransformerFactory.newInstance();

        // Make the Transformer
        Transformer transformer = tFactory.newTransformer();

        // Mark the document as a DOM (XML) source
        DOMSource source = new DOMSource(document);

        // Say where we want the XML to go
        StreamResult result = new StreamResult(file);

        // Write the XML to file
        transformer.transform(source, result);
    }
}

Source: http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

How to solve npm error "npm ERR! code ELIFECYCLE"

React Application: For me the issue was that after running npm install had some errors.

I've went with the recommendation npm audit fix. This operation broke my package.json and package-lock.json (changed version of packages and and structure of .json).

THE FIX WAS:

  • Delete node_modules
  • Run npm install
  • npm start

Hope this will be helpfull for someone.

What is the best JavaScript code to create an img element

Just for the sake of completeness, I would suggest using the InnerHTML way as well - even though I would not call it the best way...

document.getElementById("image-holder").innerHTML = "<img src='image.png' alt='The Image' />";

By the way, innerHTML is not that bad

How to return 2 values from a Java method?

You could implement a generic Pair if you are sure that you just need to return two values:

public class Pair<U, V> {

 /**
     * The first element of this <code>Pair</code>
     */
    private U first;

    /**
     * The second element of this <code>Pair</code>
     */
    private V second;

    /**
     * Constructs a new <code>Pair</code> with the given values.
     * 
     * @param first  the first element
     * @param second the second element
     */
    public Pair(U first, V second) {

        this.first = first;
        this.second = second;
    }

//getter for first and second

and then have the method return that Pair:

public Pair<Object, Object> getSomePair();

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

How to pass ArrayList of Objects from one to another activity using Intent in android?

Your intent creation seems correct if your Question implements Parcelable.

In the next activity you can retrieve your list of questions like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}

What is Shelving in TFS?

That's right. If you create a shelf, other people doing a get latest won't see your code.

It puts your code changes onto the server, which is probably better backed up than your work PC.

It enables you to pick up your changes on another machine, should you feel the urge to work from home.

Others can see your shelves (though I think this may be optional) so they can review your code prior to a check-in.

Two Divs next to each other, that then stack with responsive change

With a mediaquery based on a min-width you could achieve something like http://jsbin.com/aruyiq/1/edit

CSS

.wrapper { 
  border : 2px dotted #ccc; padding: 2px; 
}

.wrapper div {
   width: 100%; 
   min-height: 200px;
   padding: 10px;
   -webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
   box-sizing: border-box;
}
#one { background-color: gray; }
#two { background-color: white; }

@media screen and (min-width: 600px) {
   .wrapper {
      height: auto; overflow: hidden; // clearing 
   }
   #one { width: 200px; float: left; }
   #two { margin-left: 200px; }
}

In my example the breakpoint is 600px but you could adapt it to your needs.

Why the switch statement cannot be applied on strings?

You can't use string in switch case.Only int & char are allowed. Instead you can try enum for representing the string and use it in the switch case block like

enum MyString(raj,taj,aaj);

Use it int the swich case statement.

Xcode Objective-C | iOS: delay function / NSTimer help?

[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];

Is the best one to use. Using sleep(15); will cause the user unable to perform any other actions. With the following function, you would replace goToSecondButton with the appropriate selector or command, which can also be from the frameworks.

ScrollIntoView() causing the whole page to move

I've added a way to display the imporper behavior of the ScrollIntoView - http://jsfiddle.net/LEqjm/258/ [it should be a comment but I don't have enough reputation]

$("ul").click(function() {
    var target = document.getElementById("target");
if ($('#scrollTop').attr('checked')) {
    target.parentNode.scrollTop = target.offsetTop;    
} else {
        target.scrollIntoView(!0);
}
});

Select a Column in SQL not in Group By

The columns in the result set of a select query with group by clause must be:

  • an expression used as one of the group by criteria , or ...
  • an aggregate function , or ...
  • a literal value

So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:

I want to find the individual claim row bearing the most recent creation date within each group in my claims table

Given

create table dbo.some_claims_table
(
  claim_id     int      not null ,
  group_id     int      not null ,
  date_created datetime not null ,

  constraint some_table_PK primary key ( claim_id                ) ,
  constraint some_table_AK01 unique    ( group_id , claim_id     ) ,
  constraint some_Table_AK02 unique    ( group_id , date_created ) ,

)

The first thing to do is identify the most recent creation date for each group:

select group_id ,
       date_created = max( date_created )
from dbo.claims_table
group by group_id

That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select query:

select *
from dbo.claims_table t
join ( select group_id ,
       date_created = max( date_created )
       from dbo.claims_table
       group by group_id
      ) x on x.group_id     = t.group_id
         and x.date_created = t.date_created

If the table is not unique by date_created within group_id (AK02), you you can get duplicate rows for a given group.

Python Git Module experiences?

The git interaction library part of StGit is actually pretty good. However, it isn't broken out as a separate package but if there is sufficient interest, I'm sure that can be fixed.

It has very nice abstractions for representing commits, trees etc, and for creating new commits and trees.

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';
        document.head.appendChild(style);
    }

Excel plot time series frequency with continuous xaxis

I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog

Non-uniformly distributed data can be plotted in excel in

  • X Y (Scatter Plots)
  • Linear plots with Date axis
    • These don't take time into account, only days.
    • This method is quite cumbersome as it requires translating your time units to days, months, or years.. then change the axis labels... Not Recommended

Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.

1- Add the center point to your data series

+---------------+-------+------+
|    Time       | Time  | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 |  12  |
| 09:00 - 10:00 | 09:30 |  13  |
| 10:00 - 11:00 | 10:30 |  10  |
| 13:00 - 14:00 | 13:30 |   5  |
| 14:00 - 15:00 | 14:30 |  14  |
+---------------+-------+------+

2- Create a Scatter Plot

3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:

  • Minimum : Fix : 0.33333
  • Maximum : Fix : 0.625
  • Major unit : Fix : 0.041667

Line Scatter Plot


Alternative Display:

Make the points turn into columns:

To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.

1- You're going to need to add several rows where we draw the line and disjoint the data

+-------+------+
| Time  | Freq |
+-------+------+
| 08:30 |   0  |
| 08:30 |  12  |
|       |      |
| 09:30 |   0  |
| 09:30 |  13  |
|       |      |
| 10:30 |   0  |
| 10:30 |  10  |
|       |      |
| 13:30 |   0  |
| 13:30 |   5  |
|       |      |
| 14:30 |   0  |
| 14:30 |  14  |
+-------+------+

2- Plot an X Y (Scatter) Chart with Lines.

3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.

Bar-Line Scatter Plot

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Why Choose Struct Over Class?

One point not getting attention in these answers is that a variable holding a class vs a struct can be a let while still allowing changes on the object's properties, while you cannot do this with a struct.

This is useful if you don't want the variable to ever point to another object, but still need to modify the object, i.e. in the case of having many instance variables that you wish to update one after another. If it is a struct, you must allow the variable to be reset to another object altogether using var in order to do this, since a constant value type in Swift properly allows zero mutation, while reference types (classes) don't behave this way.

Loop structure inside gnuplot?

Take a look also to the do { ... } command since gnuplot 4.6 as it is very powerful:

do for [t=0:50] {
  outfile = sprintf('animation/bessel%03.0f.png',t)
  set output outfile
  splot u*sin(v),u*cos(v),bessel(u,t/50.0) w pm3d ls 1
}

http://www.gnuplotting.org/gnuplot-4-6-do/

Add padding on view programmatically

To answer your second question:

view.setPadding(0,padding,0,0);

like SpK and Jave suggested, will set the padding in pixels. You can set it in dp by calculating the dp value as follows:

int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);

Hope that helps!

Regular Expression to match every new line character (\n) inside a <content> tag

Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:

<!-- <content> blah </content> -->

You can take two approaches here:

  1. Strip all comments out first. Then use the regex approach.
  2. Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.

Be careful.

I am also not so sure you can match all new lines at once. @Quartz suggested this one:

<content>([^\n]*\n+)+</content>

This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:

<content>.*</content>

BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.

I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.

I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...

UPDATE 1:

Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):

To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.

Similarly, to search for content tags, use: .*?

Also, You may be able to try this out, and access each newline character with the match objects groups():

<content>(.*?(\n))+.*?</content>

I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.

UPDATE 2:

So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:

#!/usr/bin/python

import re

def FindContentNewlines(xml_text):
    # May want to compile these regexes elsewhere, but I do it here for brevity
    comments = re.compile(r"<!--.*?-->", re.DOTALL)
    content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
    newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)

    # strip comments: this actually may not be reliable for "nested comments"
    # How does xml handle <!--  <!-- --> -->. I am not sure. But that COULD
    # be trouble.
    xml_text = re.sub(comments, "", xml_text)

    result = []
    all_contents = re.findall(content, xml_text)
    for c in all_contents:
        result.extend(re.findall(newlines, c))

    return result

if __name__ == "__main__":
    example = """

<!-- This stuff
ought to be omitted
<content>
  omitted
</content>
-->

This stuff is good
<content>
<p>
  haha!
</p>
</content>

This is not found
"""
    print FindContentNewlines(example)

This program prints the result:

 ['', '<p>', '  haha!', '</p>', '']

The first and last empty strings come from the newline chars immediately preceeding the first <p> and the one coming right after the </p>. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.

Hope this helps :-).

PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.

Windows command for file size only

In PowerShell you can do:

$imageObj = New-Object System.IO.FileInfo("C:\test.jpg")    
$imageObj.Length

Use <Image> with a local file

To display image from local folder, you need to write down code:

 <Image source={require('../assets/self.png')}/>

Here I have put my image in asset folder.

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

The problem is also identified in your status bar at the bottom:

overwrite label in status bar

You are in overwrite mode instead of insert mode.

The “Insert” key toggles between insert and overwrite modes.

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

How to check size of a file using Bash?

[ -n file.txt ] doesn't check its size, it checks that the string file.txt is non-zero length, so it will always succeed.

If you want to say "size is non-zero", you need [ -s file.txt ].

To get a file's size, you can use wc -c to get the size (file length) in bytes:

file=file.txt
minimumsize=90000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize bytes
else
    echo size is under $minimumsize bytes
fi

In this case, it sounds like that's what you want.

But FYI, if you want to know how much disk space the file is using, you could use du -k to get the size (disk space used) in kilobytes:

file=file.txt
minimumsize=90
actualsize=$(du -k "$file" | cut -f 1)
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize kilobytes
else
    echo size is under $minimumsize kilobytes
fi

If you need more control over the output format, you can also look at stat. On Linux, you'd start with something like stat -c '%s' file.txt, and on BSD/Mac OS X, something like stat -f '%z' file.txt.

How do I run a program from command prompt as a different user and as an admin

All of these answers unfortunately miss the point.

There are 2 security context nuances here, and we need them to overlap. - "Run as administrator" - changing your execution level on your local machine - "Run as different user" - selects what user credentials you run the process under.

When UAC is enabled on a workstation, there are processes which refuse to run unless elevated - simply being a member of the local "Administrators" group isn't enough. If your requirement also dictates that you use alternate credentials to those you are signed in with, we need a method to invoke the process both as the alternate credentials AND elevated.

What I found can be used, though a bit of a hassle, is:

  • run a CMD prompt as administrator
  • use the Sysinternals psexec utility as follows:

    psexec \\localworkstation -h -i -u domain\otheruser exetorun.exe

The first elevation is needed to be able to push the psexec service. The -h runs the new "remote" (local) process elevated, and -i lets it interact with the desktop.

Perhaps there are easier ways than this?

How to get milliseconds from LocalDateTime in Java 8

What I do so I don't specify a time zone is,

System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println("ctm " + System.currentTimeMillis());

gives

ldt 1424812121078 
ctm 1424812121281

As you can see the numbers are the same except for a small execution time.

Just in case you don't like System.currentTimeMillis, use Instant.now().toEpochMilli()

Case statement with multiple values in each 'when' block

Another nice way to put your logic in data is something like this:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Replace all occurrences of a string in a data frame

late to the party. but if you only want to get rid of leading/trailing white space, R base has a function trimws

For example:

data <- apply(X = data, MARGIN = 2, FUN = trimws) %>% as.data.frame()

Returning binary file from controller in ASP.NET Web API

The overload that you're using sets the enumeration of serialization formatters. You need to specify the content type explicitly like:

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

Rounding up to next power of 2

If you need it for OpenGL related stuff:

/* Compute the nearest power of 2 number that is 
 * less than or equal to the value passed in. 
 */
static GLuint 
nearestPower( GLuint value )
{
    int i = 1;

    if (value == 0) return -1;      /* Error! */
    for (;;) {
         if (value == 1) return i;
         else if (value == 3) return i*4;
         value >>= 1; i *= 2;
    }
}

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

Add image in title bar

You'll have to use a favicon for your page. put this in the head-tag: <link rel="shortcut icon" href="/favicon.png" type="image/png">

where favicon.png is preferably a 16x16 png image.

source: Adding a favicon to a static HTML page

Can I add and remove elements of enumeration at runtime in Java

No, enums are supposed to be a complete static enumeration.

At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.

In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface for the interface and an enum that implements that interface for the standard values. Of course, you lose the ability to switch when you only have a reference to the interface.

scikit-learn random state in splitting dataset

when random_state set to an integer, train_test_split will return same results for each execution.

when random_state set to an None, train_test_split will return different results for each execution.

see below example:

from sklearn.model_selection import train_test_split

X_data = range(10)
y_data = range(10)

for i in range(5):
    X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = 0) # zero or any other integer
    print(y_test)

print("*"*30)

for i in range(5): 
    X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = None)
    print(y_test)

Output:

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]

[2, 8, 4]


[4, 7, 6]

[4, 3, 7]

[8, 1, 4]

[9, 5, 8]

[6, 4, 5]

DateTime's representation in milliseconds?

As of .NET 4.6, you can use a DateTimeOffset object to get the unix milliseconds. It has a constructor which takes a DateTime object, so you can just pass in your object as demonstrated below.

DateTime yourDateTime;
long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();

As noted in other answers, make sure yourDateTime has the correct Kind specified, or use .ToUniversalTime() to convert it to UTC time first.

Here you can learn more about DateTimeOffset.

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

HTML: Image won't display?

I confess to not having read the whole thread. However when I faced a similar issue I found that checking carefully the case of the file name and correcting that in the HTML reference fixed a similar issue. So local preview on Windows worked but when I published to my server (hosted Linux) I had to make sure "mugshot.jpg" was changed to "mugshot.JPG". Part of the problem is the defaults in Windows hiding full file names behind file type indications.

How to use OrderBy with findAll in Spring Data

Please have a look at the Spring Data JPA - Reference Documentation, section 5.3. Query Methods, especially at section 5.3.2. Query Creation, in "Table 3. Supported keywords inside method names" (links as of 2019-05-03).

I think it has exactly what you need and same query as you stated should work...

How to check if a variable is an integer or a string?

The isdigit method of the str type returns True iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.

Force an SVN checkout command to overwrite current files

This can be done pretty easily. All I did was move the existing directory, not under version control, to a temporary directory. Then I checked out the SVN version to my correct directory name, copied the files from the temporary directory into the SVN directory, and reverted the files in the SVN directory. If that does not make sense there is an example below:

/usr/local/www

mv www temp_www
svn co http://www.yourrepo.com/therepo www
cp -pR ./temp_www/* ./www
svn revert -R ./www/*
svn update

I hope this helps and am not sure why just a simple SVN update did not change the files back?

Text file in VBA: Open/Find Replace/SaveAs/Close File

I have had the same problem and came acrosse this site.

the solution to just set another "filename" in the

... for output as ... command was very simple and useful.

in addition (beyond the Application.GetSaveAsFilename() Dialog)

it is very simple to set a** new filename** just using

the replace command, so you may change the filename/extension

eg. (as from the first post)

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

now just set:

newFilename = replace(sFilename, ".txt", ".csv") to change the extension

or

newFilename = replace(sFilename, ".", "_edit.") for a differrent filename

and then just as before

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

I surfed over an hour to find out how to rename a txt-file,

with many different solutions, but it could be sooo easy :)

Case-Insensitive List Search

You're checking if the result of IndexOf is larger or equal 0, meaning whether the match starts anywhere in the string. Try checking if it's equal to 0:

if (testList.FindAll(x => x.IndexOf(keyword, 
                   StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
   Console.WriteLine("Found in list");

Now "goat" and "oat" won't match, but "goat" and "goa" will. To avoid this, you can compare the lenghts of the two strings.

To avoid all this complication, you can use a dictionary instead of a list. They key would be the lowercase string, and the value would be the real string. This way, performance isn't hurt because you don't have to use ToLower for each comparison, but you can still use Contains.

What does CultureInfo.InvariantCulture mean?

For things like numbers (decimal points, commas in amounts), they are usually preferred in the specific culture.

A appropriate way to do this would be set it at the culture level (for German) like this:

Thread.CurrentThread.CurrentCulture.NumberFormat = new CultureInfo("de").NumberFormat;

How do you count the lines of code in a Visual Studio solution?

Visual Studio 2010 Ultimate has this built-in:

Analyze ? Calculate Code Metrics

Trigger validation of all fields in Angular Form submit

To validate all fields of my form when I want, I do a validation on each field of $$controls like this :

angular.forEach($scope.myform.$$controls, function (field) {
    field.$validate();
});

Git blame -- prior commits?

I wrote ublame python tool that returns a naive history of a file commits that impacted a given search term, you'll find more information on the þroject page.

How to align texts inside of an input?

If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.

_x000D_
_x000D_
input.rightAligned {_x000D_
  direction:ltr;_x000D_
  overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
  direction:rtl;_x000D_
  text-align: left;_x000D_
  unicode-bidi: plaintext;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
    <input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
_x000D_
_x000D_

The not selector is currently well supported : Browser support

Python IndentationError: unexpected indent

find all tabs and replaced by 4 spaces in notepad ++ .It worked.

DD/MM/YYYY Date format in Moment.js

You can use this

moment().format("DD/MM/YYYY");

However, this returns a date string in the specified format for today, not a moment date object. Doing the following will make it a moment date object in the format you want.

var someDateString = moment().format("DD/MM/YYYY");
var someDate = moment(someDateString, "DD/MM/YYYY");

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

@dimas's answer is not logically consistent with your question; ifAllGranted cannot be directly replaced with hasAnyRole.

From the Spring Security 3—>4 migration guide:

Old:

<sec:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>

New (SPeL):

<sec:authorize access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>

Replacing ifAllGranted directly with hasAnyRole will cause spring to evaluate the statement using an OR instead of an AND. That is, hasAnyRole will return true if the authenticated principal contains at least one of the specified roles, whereas Spring's (now deprecated as of Spring Security 4) ifAllGranted method only returned true if the authenticated principal contained all of the specified roles.

TL;DR: To replicate the behavior of ifAllGranted using Spring Security Taglib's new authentication Expression Language, the hasRole('ROLE_1') and hasRole('ROLE_2') pattern needs to be used.

RegEx match open tags except XHTML self-contained tags

You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n?erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege???x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the transgression of a chi?ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c??o??rrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg?ex parsers for HTML will ins?tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil?l devour your HT?ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi?ght he com?e?s, ?h?i?s un?ho?ly radian?ce? destro?ying all enli??^?ghtenment, HTML tags lea?ki¸n?g fr?o?m ?yo??ur eye?s? ?l?ik?e liq?uid pain, the song of re?gular exp?ression parsing will exti?nguish the voices of mor?tal man from the sp?here I can see it can you see _????i^??t´??_??_? it is beautiful t?he final snuffing of the lie?s of Man ALL IS LOS´???????T ALL I?S LOST the pon?y he comes he c??omes he comes the ich?or permeates all MY FACE MY FACE ?h god no NO NOO?O?O NT stop the an?*?????¯????g????????l??????????e¯?s ?a¸??r?????e n?ot re`???a?l~??????? ZA????LG? IS?^??????_ TO???????? TH?E??? ?P???O??N?Y? H???¯?"????E????`´¸??? ???¸??_???C???????_??O??????M????????_?E?????????S??????????


Have you tried using an XML parser instead?


Moderator's Note

This post is locked to prevent inappropriate edits to its content. The post looks exactly as it is supposed to look - there are no problems with its content. Please do not flag it for our attention.

How to split long commands over multiple lines in PowerShell

Trailing backtick character, i.e.,

&"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
-verb:sync `
-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `
-dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"

White space matters. The required format is Space`Enter.

How to convert Moment.js date to users local timezone?

You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();

From there you can use any of the functions you might expect:

var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...

Note that by passing testDateUtc, which is a moment object, back into the moment() constructor, it creates a clone. Otherwise, when you called .local(), it would also change the testDateUtc value, instead of just the localDate value. Moments are mutable.

Also note that if your original input contains a time zone offset such as +00:00 or Z, then you can just parse it directly with moment. You don't need to use .utc or .local. For example:

var localDate = moment("2015-01-30T10:00:00Z");

Odd behavior when Java converts int to byte?

In Java, an int is 32 bits. A byte is 8 bits .

Most primitive types in Java are signed, and byte, short, int, and long are encoded in two's complement. (The char type is unsigned, and the concept of a sign is not applicable to boolean.)

In this number scheme the most significant bit specifies the sign of the number. If more bits are needed, the most significant bit ("MSB") is simply copied to the new MSB.

So if you have byte 255: 11111111 and you want to represent it as an int (32 bits) you simply copy the 1 to the left 24 times.

Now, one way to read a negative two's complement number is to start with the least significant bit, move left until you find the first 1, then invert every bit afterwards. The resulting number is the positive version of that number

For example: 11111111 goes to 00000001 = -1. This is what Java will display as the value.

What you probably want to do is know the unsigned value of the byte.

You can accomplish this with a bitmask that deletes everything but the least significant 8 bits. (0xff)

So:

byte signedByte = -1;
int unsignedByte = signedByte & (0xff);

System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);

Would print out: "Signed: -1 Unsigned: 255"

What's actually happening here?

We are using bitwise AND to mask all of the extraneous sign bits (the 1's to the left of the least significant 8 bits.) When an int is converted into a byte, Java chops-off the left-most 24 bits

1111111111111111111111111010101
&
0000000000000000000000001111111
=
0000000000000000000000001010101

Since the 32nd bit is now the sign bit instead of the 8th bit (and we set the sign bit to 0 which is positive), the original 8 bits from the byte are read by Java as a positive value.

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

How to store an array into mysql?

Consider normalizing the table structure into a comments, and a separate votes table.

Table "comments":

id
comment
user
...

Table "votes":

user_id  
comment_id
vote (downvote/upvote)

this would allow an unlimited number of votes without having to deal with the limits of a database field.

Also, you may have future needs for operations like "show all votes a user has cast", removing specific votes or limiting the maximum number of votes per day. These operations are dead easy and fast to implement with a normalized structure, and horribly slow and complex in a serialized array.

Can an AJAX response set a cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

Is it possible to forward-declare a function in Python?

Yes, we can check this.

Input

print_lyrics() 
def print_lyrics():

    print("I'm a lumberjack, and I'm okay.")
    print("I sleep all night and I work all day.")

def repeat_lyrics():
    print_lyrics()
    print_lyrics()
repeat_lyrics()

Output

I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.

As BJ Homer mentioned over above comments, A general rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.

Hope that helps.

std::string to char*

No body ever mentioned sprintf?

std::string s;
char * c;
sprintf(c, "%s", s.c_str());

Split comma-separated values

A way to do this without Linq & Lambdas

string source = "a,b, b, c";
string[] items = source.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

Hide Show content-list with only CSS, no javascript used

I've got another simple solution:

HTML:

<a href="#alert" class="span3" tabindex="0">Hide Me</a>
<a href="#" class="span2" tabindex="0">Show Me</a>
<p id="alert" class="alert" >Some alarming information here</p>

CSS:

body { display: block; }
p.alert:target { display: none; }

Source: http://css-tricks.com/off-canvas-menu-with-css-target/

'Incomplete final line' warning when trying to read a .csv file into R

I got this problem once when I had a single quote as part of the header. When I removed it (i.e. renamed the respective column header from Jimmy's data to Jimmys data), the function returned no warnings.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

Linux Process States

Yes, the task gets blocked in the read() system call. Another task which is ready runs, or if no other tasks are ready, the idle task (for that CPU) runs.

A normal, blocking disc read causes the task to enter the "D" state (as others have noted). Such tasks contribute to the load average, even though they're not consuming the CPU.

Some other types of IO, especially ttys and network, do not behave quite the same - the process ends up in "S" state and can be interrupted and doesn't count against the load average.

SQLite UPSERT / UPDATE OR INSERT

You can also just add an ON CONFLICT REPLACE clause to your user_name unique constraint and then just INSERT away, leaving it to SQLite to figure out what to do in case of a conflict. See:https://sqlite.org/lang_conflict.html.

Also note the sentence regarding delete triggers: When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.

jQuery changing style of HTML element

$('#navigation ul li').css({'display' : 'inline-block'});

It seems a typo there ...syntax mistake :))

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Password Strength Meter

Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/

I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:

function scorePassword(pass) {
    var score = 0;
    if (!pass)
        return score;

    // award every unique letter until 5 repetitions
    var letters = new Object();
    for (var i=0; i<pass.length; i++) {
        letters[pass[i]] = (letters[pass[i]] || 0) + 1;
        score += 5.0 / letters[pass[i]];
    }

    // bonus points for mixing it up
    var variations = {
        digits: /\d/.test(pass),
        lower: /[a-z]/.test(pass),
        upper: /[A-Z]/.test(pass),
        nonWords: /\W/.test(pass),
    }

    var variationCount = 0;
    for (var check in variations) {
        variationCount += (variations[check] == true) ? 1 : 0;
    }
    score += (variationCount - 1) * 10;

    return parseInt(score);
}

Good passwords start to score around 60 or so, here's function to translate that in words:

function checkPassStrength(pass) {
    var score = scorePassword(pass);
    if (score > 80)
        return "strong";
    if (score > 60)
        return "good";
    if (score >= 30)
        return "weak";

    return "";
}

you might want to tune this a bit but i found it working for me nicely

How to find length of dictionary values

To find all of the lengths of the values in a dictionary you can do this:

lengths = [len(v) for v in d.values()]

How to stop asynctask thread in android?

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Determine a string's encoding in C#

The SimpleHelpers.FileEncoding Nuget package wraps a C# port of the Mozilla Universal Charset Detector into a dead-simple API:

var encoding = FileEncoding.DetectFileEncoding(txtFile);

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

com.android.build.transform.api.TransformException

Incase 'Instant Run' is enable, then just disable it.

Set min-width in HTML table's <td>

try this one:

_x000D_
_x000D_
<table style="border:1px solid">
<tr>
    <td style="min-width:50px">one</td>
    <td style="min-width:100px">two</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Xerces-based tools will emit the following error

The processing instruction target matching "[xX][mM][lL]" is not allowed.

when an XML declaration is encountered anywhere other than at the top of an XML file.

This is a valid diagnostic message; other XML parsers should issue a similar error message in this situation.

To correct the problem, check the following possibilities:

  1. Some blank space or other visible content exists before the <?xml ?> declaration.

    Resolution: remove blank space or any other visible content before the XML declaration.

  2. Some invisible content exists before the <?xml ?> declaration. Most commonly this is a Byte Order Mark (BOM).

    Resolution: Remove the BOM using techniques such as those suggested by the W3C page on the BOM in HTML.

  3. A stray <?xml ?> declaration exists within the XML content. This can happen when XML files are combined programmatically or via cut-and-paste. There can only be one <?xml ?> declaration in an XML file, and it can only be at the top.

    Resolution: Search for <?xml in a case-insensitive manner, and remove all but the top XML declaration from the file.

How do I embed PHP code in JavaScript?

We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.

However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

How to make a programme continue to run after log out from ssh?

Start in the background:

./long_running_process options &

And disown the job before you log out:

disown

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Parsing json and searching through it

You can use jsonpipe if you just need the output (and more comfortable with command line):

cat bookmarks.json | jsonpipe |grep uri

How to make child element higher z-index than parent?

Nothing is impossible. Use the force.

.parent {
    position: relative;
}

.child {
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
}

Cannot install packages inside docker Ubuntu image

Make sure you don't have any syntax errors in your Dockerfile as this can cause this error as well. A correct example is:

RUN apt-get update \
    && apt-get -y install curl \
    another-package

It was a combination of fixing a syntax error and adding apt-get update that solved the problem for me.

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

Mocking Logger and LoggerFactory with PowerMock and Mockito

EDIT 2020-09-21: Since 3.4.0, Mockito supports mocking static methods, API is still incubating and is likely to change, in particular around stubbing and verification. It requires the mockito-inline artifact. And you don't need to prepare the test or use any specific runner. All you need to do is :

@Test
public void name() {
    try (MockedStatic<LoggerFactory> integerMock = mockStatic(LoggerFactory.class)) {
        final Logger logger = mock(Logger.class);
        integerMock.when(() -> LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
        new Controller().log();
        verify(logger).warn(any());
    }
}

The two inportant aspect in this code, is that you need to scope when the static mock applies, i.e. within this try block. And you need to call the stubbing and verification api from the MockedStatic object.


@Mick, try to prepare the owner of the static field too, eg :

@PrepareForTest({GoodbyeController.class, LoggerFactory.class})

EDIT1 : I just crafted a small example. First the controller :

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Controller {
    Logger logger = LoggerFactory.getLogger(Controller.class);

    public void log() { logger.warn("yup"); }
}

Then the test :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Controller.class, LoggerFactory.class})
public class ControllerTest {

    @Test
    public void name() throws Exception {
        mockStatic(LoggerFactory.class);
        Logger logger = mock(Logger.class);
        when(LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
        
        new Controller().log();
        
        verify(logger).warn(anyString());
    }
}

Note the imports ! Noteworthy libs in the classpath : Mockito, PowerMock, JUnit, logback-core, logback-clasic, slf4j


EDIT2 : As it seems to be a popular question, I'd like to point out that if these log messages are that important and require to be tested, i.e. they are feature / business part of the system then introducing a real dependency that make clear theses logs are features would be a so much better in the whole system design, instead of relying on static code of a standard and technical classes of a logger.

For this matter I would recommend to craft something like= a Reporter class with methods such as reportIncorrectUseOfYAndZForActionX or reportProgressStartedForActionX. This would have the benefit of making the feature visible for anyone reading the code. But it will also help to achieve tests, change the implementations details of this particular feature.

Hence you wouldn't need static mocking tools like PowerMock. In my opinion static code can be fine, but as soon as the test demands to verify or to mock static behavior it is necessary to refactor and introduce clear dependencies.

How to fix Python indentation

If you're using Vim, see :h retab.

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

For example, if you simply type

:ret

all your tabs will be expanded into spaces.

You may want to

:se et  " shorthand for :set expandtab

to make sure that any new lines will not use literal tabs.


If you're not using Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

will replace tabs with spaces, assuming tab stops every 8 characters, in file.py (with the original going to file.py.bak, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.

What does "hashable" mean in Python?

Hashable = capable of being hashed.

Ok, what is hashing? A hashing function is a function which takes an object, say a string such as “Python,” and returns a fixed-size code. For simplicity, assume the return value is an integer.

When I run hash(‘Python’) in Python 3, I get 5952713340227947791 as the result. Different versions of Python are free to change the underlying hash function, so you will likely get a different value. The important thing is that no matter now many times I run hash(‘Python’), I’ll always get the same result with the same version of Python.

But hash(‘Java’) returns 1753925553814008565. So if the object I am hashing changes, so does the result. On the other hand, if the object I am hashing does not change, then the result stays the same.

Why does this matter?

Well, Python dictionaries, for example, require the keys to be immutable. That is, keys must be objects which do not change. Strings are immutable in Python, as are the other basic types (int, float, bool). Tuples and frozensets are also immutable. Lists, on the other hand, are not immutable (i.e., they are mutable) because you can change them. Similarly, dicts are mutable.

So when we say something is hashable, we mean it is immutable. If I try to pass a mutable type to the hash() function, it will fail:

>>> hash('Python')
1687380313081734297
>>> hash('Java')
1753925553814008565
>>>
>>> hash([1, 2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash({1, 2})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> hash({1 : 2})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>>
>>> hash(frozenset({1, 2}))
-1834016341293975159
>>> hash((1, 2))
3713081631934410656

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

I started using the AngiesList.Redis.RedisSessionStateModule, which aside from using the (very fast) Redis server for storage (I'm using the windows port -- though there is also an MSOpenTech port), it does absolutely no locking on the session.

In my opinion, if your application is structured in a reasonable way, this is not a problem. If you actually need locked, consistent data as part of the session, you should specifically implement a lock/concurrency check on your own.

MS deciding that every ASP.NET session should be locked by default just to handle poor application design is a bad decision, in my opinion. Especially because it seems like most developers didn't/don't even realize sessions were locked, let alone that apps apparently need to be structured so you can do read-only session state as much as possible (opt-out, where possible).

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html

How to list the certificates stored in a PKCS12 keystore with keytool?

You can list down the entries (certificates details) with the keytool and even you don't need to mention the store type.

keytool -list -v -keystore cert.p12 -storepass <password>

 Keystore type: PKCS12
 Keystore provider: SunJSSE

 Your keystore contains 1 entry
 Alias name: 1
 Creation date: Jul 11, 2020
 Entry type: PrivateKeyEntry
 Certificate chain length: 2

Trim spaces from start and end of string

Here, this should do all that you need

function doSomething(input) {
    return input
              .replace(/^\s\s*/, '')     // Remove Preceding white space
              .replace(/\s\s*$/, '')     // Remove Trailing white space
              .replace(/([\s]+)/g, '-'); // Replace remaining white space with dashes
}

alert(doSomething("  something with  some       whitespace   "));

Calculating width from percent to pixel then minus by pixel in LESS CSS

Or, you could use the margin attribute like this:

    {
    background:#222;
    width:100%;
    height:100px;
    margin-left: 10px;
    margin-right: 10px;
    display:block;
    }

HTTP 400 (bad request) for logical error, not malformed request syntax

This is difficult.

I think we should;

  1. Return 4xx errors only when the client has the power to make a change to the request, headers or body, that will result in the request succeeding with the same intent.

  2. Return error range codes when the expected mutation has not occured, i.e. a DELETE didn't happen or a PUT didn't change anything. However, a POST is more interesting because the spec says it should be used to either create resources at a new location, or just process a payload.

Using the example in Vish's answer, if the request intends to add employee Priya to a department Marketing but Priya wasn't found or her account is archived, then this is an application error.

The request worked fine, it got to your application rules, the client did everything properly, the ETags matched etc. etc.

Because we're using HTTP we must respond based on the effect of the request on the state of the resource. And that depends on your API design.

Perhaps you designed this.

PUT { updated members list } /marketing/members

Returning a success code would indicate that the "replacement" of the resource worked; a GET on the resource would reflect your changes, but it wouldn't.

So now you have to choose a suitable negative HTTP code, and that's the tricky part, since the codes are strongly intended for the HTTP protocol, not your application.

When I read the official HTTP codes, these two look suitable.

The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict.

And

The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.

Though we've traditionally considered the 500 to be like an unhandled exception :-/

I don't think its unreasonable to invent your own status code so long as its consistently applied and designed.

This design is easier to deal with.

PUT { membership add command } /accounts/groups/memberships/instructions/1739119

Then you could design your API to always succeed in creating the instruction, it returns 201 Created and a Location header and any problems with the instruction are held within that new resource.

A POST is more like that last PUT to a new location. A POST allows for any kind of server processing of a message, which opens up designs that say something like "The action successfully failed."

Probably you already wrote an API that does this, a website. You POST the payment form and it was successfully rejected because the credit card number was wrong.

With a POST, whether you return 200 or 201 along with your rejection message depends on whether a new resource was created and is available to GET at another location, or not.

With that all said, I'd be inclined to design APIs that need fewer PUTs, perhaps just updating data fields, and actions and stuff that invokes rules and processing or just have a higher chance of expected failures, can be designed to POST an instruction form.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Improving on João's and satru's code, I suggest creating a cursor mixin that can be used to build a cursor with an execute that accepts nested iterables and handles them correctly. A better name would be nice, though... For Python3, use str instead of basestring.

from MySQLdb.cursors import Cursor

class BetterExecuteMixin(object):
    """
    This mixin class provides an implementation of the execute method
    that properly handles sequence arguments for use with IN tests.
    Examples:
    execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
    # Notice that when the sequence is the only argument, you still need
    # a surrounding tuple:
    execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
    """

    def execute(self, query, args=None):
        if args is not None:
            try:
                iter(args)
            except TypeError:
                args = (args,)
            else:
                if isinstance(args, basestring):
                    args = (args,)
            real_params = []
            placeholders = []
            for arg in args:
                # sequences that we treat as a single argument
                if isinstance(arg, basestring):
                    real_params.append(arg)
                    placeholders.append('%s')
                    continue
                try:
                    real_params.extend(arg)
                    placeholders.append(','.join(['%s']*len(arg)))
                except TypeError:
                    real_params.append(arg)
                    placeholders.append('%s')
            args = real_params
            query = query % tuple(placeholders)
        return super(BetterExecuteMixin, self).execute(query, args)

class BetterCursor(BetterExecuteMixin, Cursor):
    pass

This can then be used as follows (and it's still backwards compatible!):

import MySQLdb
conn = MySQLdb.connect(user='user', passwd='pass', db='dbname', host='host',
                       cursorclass=BetterCursor)
cursor = conn.cursor()
cursor.execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
cursor.execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
cursor.execute('SELECT * FROM foo WHERE type IN (%s)', (['bar', 'moo'],))
cursor.execute('SELECT * FROM foo WHERE type=%s', 'bar')
cursor.execute('SELECT * FROM foo WHERE type=%s', ('bar',))

How to use the toString method in Java?

From the Object.toString docs:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Example:

String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());

output:- mystr.toString: [Ljava.lang.String;@13aaa14a

How to add Options Menu to Fragment in Android

Menu file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/play"
        android:titleCondensed="Speak"
        android:showAsAction="always"
        android:title="Speak"
        android:icon="@drawable/ic_play">
    </item>
    <item
        android:id="@+id/pause"
        android:titleCondensed="Stop"
        android:title="Stop"
        android:showAsAction="always"
        android:icon="@drawable/ic_pause">
    </item>
</menu>

Activity code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.speak_menu_history, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.play:
            Toast.makeText(getApplicationContext(), "speaking....", Toast.LENGTH_LONG).show();
            return false;

        case R.id.pause:
            Toast.makeText(getApplicationContext(), "stopping....", Toast.LENGTH_LONG).show();
            return false;

        default:
            break;
    }

    return false;
}

Fragment code:

@Override

public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.play:
            text = page.getText().toString();
            speakOut(text);

            // Do Activity menu item stuff here
            return true;

        case R.id.pause:
            speakOf();

            // Not implemented here
            return true;

        default:
            break;
    }
    return false;
}

How to remove element from ArrayList by checking its value?

Just use myList.remove(myObject).

It uses the equals method of the class. See http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)

BTW, if you have more complex things to do, you should check out the guava library that has dozen of utility to do that with predicates and so on.

Apple Mach-O Linker Error when compiling for device

Check to make sure that you don't have a specific framework search path specified. if you go to the info on the target and just remove the framework search path entries it should use the defaults for your specified deployment version.

How to configure encoding in Maven?

It seems people mix a content encoding with a built files/resources encoding. Having only maven properties is not enough. Having -Dfile.encoding=UTF8 not effective. To avoid having issues with encoding you should follow the following simple rules

  1. Set maven encoding, as described above:
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  1. Always set encoding explicitly, when work with files, strings, IO in your code. If you do not follow this rule, your application depend on the environment. The -Dfile.encoding=UTF8 exactly is responsible for run-time environment configuration, but we should not depend on it. If you have thousands of clients, it takes more effort to configure systems and to find issues because of it. You just have an additional dependency on it which you can avoid by setting it explicitly. Most methods in Java that use a default encoding are marked as deprecated because of it.

  2. Make sure the content, you are working with, also is in the same encoding, that you expect. If it is not, the previous steps do not matter! For instance a file will not be processed correctly, if its encoding is not UTF8 but you expect it. To check file encoding on Linux:

$ file --mime F_PRDAUFT.dsv

  1. Force clients/server set encoding explicitly in requests/responses, here are examples:
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")

Hope this will be useful to someone.

Show values from a MySQL database table inside a HTML table on a webpage

Surely a better solution would by dynamic so that it would work for any query without having to know the column names?

If so, try this (obviously the query should match your database):

// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);

// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");

// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);

// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
    echo '<td>';
    echo $key;
    echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
    echo '<tr>';
    foreach($row as $column) {
        echo '<td>';
        echo $column;
        echo '</td>';
    }
    echo '</tr>';
}
echo '</table>';

Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/

Where does Anaconda Python install on Windows?

conda info will display information about the current install, including the active env location which is what you want.

Here's my output:

(base) C:\Users\USERNAME>conda info

     active environment : base
    active env location : C:\ProgramData\Miniconda3
            shell level : 1
       user config file : C:\Users\USERNAME\.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : not installed
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
       base environment : C:\ProgramData\Miniconda3  (read only)
           channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : C:\ProgramData\Miniconda3\pkgs
                          C:\Users\USERNAME\.conda\pkgs
                          C:\Users\USERNAME\AppData\Local\conda\conda\pkgs
       envs directories : C:\Users\USERNAME\.conda\envs
                          C:\ProgramData\Miniconda3\envs
                          C:\Users\USERNAME\AppData\Local\conda\conda\envs
               platform : win-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Windows/10 Windows/10.0.18362
          administrator : False
             netrc file : None
           offline mode : False

If your shell/prompt complains that it cannot find the command, it likely means that you installed Anaconda without adding it to the PATH environment variable.

If that's the case find and open the Anaconda Prompt and do it from there.

Alternatively reinstall Anaconda choosing to add it to the PATH. Or add the variable manually.

Anaconda Prompt should be available in your Start Menu (Win) or Applications Menu (macos)

How do I display image in Alert/confirm box in Javascript?

Snarky yet potentially useful answer: http://picascii.com/ (currently down)

https://www.ascii-art-generator.org/es.html (don't forget to put a \n after each line!)

Text overwrite in visual studio 2010

If you don't have an insert key, and you're using Visual Studio 2019, then double-clicking the OVR text in the bottom right corner does not work. You'll have to use an on-screen keyboard, if you have one of those, or figure out what your insert key is mapped to. For me, on my mac keyboard hooked up to windows 10, it is the 0 key on the keypad.

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

TypeScript static classes

This is one way:

class SomeClass {
    private static myStaticVariable = "whatever";
    private static __static_ctor = (() => { /* do static constructor stuff :) */ })();
}

__static_ctor here is an immediately invoked function expression. Typescript will output code to call it at the end of the generated class.

Update: For generic types in static constructors, which are no longer allowed to be referenced by static members, you will need an extra step now:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private ___static_ctor = (() => { var someClass:SomeClass<T> ; /* do static constructor stuff :) */ })();
    private static __static_ctor = SomeClass.prototype.___static_ctor();
}

In any case, of course, you could just call the generic type static constructor after the class, such as:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private __static_ctor = (() => { var example: SomeClass<T>; /* do static constructor stuff :) */ })();
}
SomeClass.prototype.__static_ctor();

Just remember to NEVER use this in __static_ctor above (obviously).

Change Twitter Bootstrap Tooltip content on click

I couldn't get any of the answers working, here's a workaround:

$('#'+$(element).attr('aria-describedby')+' .tooltip-inner').html(newTitle);

Sql Server trigger insert values from new row into another table

try this for sql server

CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS

INSERT INTO yourDestinationTable
        (col1, col2    , col3, user_id, user_name)
    SELECT
        'a'  , default , null, user_id, user_name
        FROM inserted

go

How to use MapView in android using google map V2?

More complete sample from here and here.

Or you can check out my layout sample. p.s no need to put API key in the map view.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
            android:id="@+id/map_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"
            />

    <ListView android:id="@+id/nearby_lv"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/white"
              android:layout_weight="1"
            />

</LinearLayout>

format a Date column in a Data Frame

try this package, works wonders, and was made for date/time...

library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)

System.Net.WebException HTTP status code

(I do realise the question is old, but it's among the top hits on Google.)

A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:

catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
     doSomething(response.StatusCode)
}

This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.

PHP Change Array Keys

No, there is not, for starters, it is impossible to have an array with elements sharing the same key

$x =array(); 
$x['foo'] = 'bar' ; 
$x['foo'] = 'baz' ; #replaces 'bar'

Secondarily, if you wish to merely prefix the numbers so that

$x[0] --> $x['foo_0']  

That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is "extract" which will prefix numeric keys prior to making them variables.

The very simplest way is this:

function rekey( $input , $prefix ) { 
    $out = array(); 
    foreach( $input as $i => $v ) { 
        if ( is_numeric( $i ) ) { 
            $out[$prefix . $i] = $v; 
            continue; 
        }
        $out[$i] = $v;
    }
    return $out;
}

Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.

<section> 
    <foo_0></foo_0>
   <foo_1></foo_1>
   <bar></bar>
   <foo_2></foo_2>
</section>

Is not good XML.

<section> 
   <foo></foo>
   <foo></foo>
   <bar></bar>
   <foo></foo>
</section>

Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:

section => { 
    0 => [ foo , {} ]
    1 => [ foo , {} ]
    2 => [ bar , {} ]
    3 => [ foo , {} ] 
}

How do I check what version of Python is running my script?

If you are working on linux just give command python output will be like this

Python 2.4.3 (#1, Jun 11 2009, 14:09:37)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

PHP get domain name

To answer your question, these should work as long as:

  • Your HTTP server passes these values along to PHP (I don't know any that don't)
  • You're not accessing the script via command line (CLI)

But, if I remember correctly, these values can be faked to an extent, so it's best not to rely on them.

My personal preference is to set the domain name as an environment variable in the apache2 virtual host:

# Virtual host
setEnv DOMAIN_NAME example.com

And read it in PHP:

// PHP
echo getenv(DOMAIN_NAME);

This, however, isn't applicable in all circumstances.

How to add smooth scrolling to Bootstrap's scroll spy function

If you have a fixed navbar, you'll need something like this.

Taking from the best of the above answers and comments...

$(".bs-js-navbar-scrollspy li a[href^='#']").on('click', function(event) {
  var target = this.hash;

  event.preventDefault();

  var navOffset = $('#navbar').height();

  return $('html, body').animate({
    scrollTop: $(this.hash).offset().top - navOffset
  }, 300, function() {
    return window.history.pushState(null, null, target);
  });
});

First, in order to prevent the "undefined" error, store the hash to a variable, target, before calling preventDefault(), and later reference that stored value instead, as mentioned by pupadupa.

Next. You cannot use window.location.hash = target because it sets the url and the location simultaneously rather than separately. You will end up having the location at the beginning of the element whose id matches the href... but covered by your fixed top navbar.

In order to get around this, you set your scrollTop value to the vertical scroll location value of the target minus the height of your fixed navbar. Directly targeting that value maintains smooth scrolling, instead of adding an adjustment afterwards, and getting unprofessional-looking jitters.

You will notice the url doesn't change. To set this, use return window.history.pushState(null, null, target); instead, to manually add the url to the history stack.

Done!

Other notes:

1) using the .on method is the latest (as of Jan 2015) jquery method that is better than .bind or .live, or even .click for reasons I'll leave to you to find out.

2) the navOffset value can be within the function or outside, but you will probably want it outside, as you may very well reference that vertical space for other functions / DOM manipulations. But I left it inside to make it neatly into one function.

Compiling C++11 with g++

If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:

The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

What does "if (rs.next())" mean?

Since Result Set is an interface, When you obtain a reference to a ResultSet through a JDBC call, you are getting an instance of a class that implements the ResultSet interface. This class provides concrete implementations of all of the ResultSet methods.

Interfaces are used to divorce implementation from, well, interface. This allows the creation of generic algorithms and the abstraction of object creation. For example, JDBC drivers for different databases will return different ResultSet implementations, but you don't have to change your code to make it work with the different drivers

In very short, if your ResultSet contains result, then using rs.next return true if you have recordset else it returns false.

What's the difference between “mod” and “remainder”?

In C and C++ and many languages, % is the remainder NOT the modulus operator.

For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this

_x000D_
_x000D_
console.log(-21 % 4 == -1);
_x000D_
_x000D_
_x000D_

The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.

Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}