Programs & Examples On #Qt4dotnet

qt4dotnet is a set of Bindings for Qt 4 targeting .NET languages.

Uncaught (in promise) TypeError: Failed to fetch and Cors error

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.json();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
    });
}

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.text();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = muutuja;
    });
}

How to add image to canvas

here is the sample code to draw image on canvas-

$("#selectedImage").change(function(e) {

var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;

img.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");        

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 500, 500);
}});

In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:

http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html

How to upload a file using Java HttpClient library working with PHP

Ok, the Java code I used was wrong, here comes the right Java class:

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

note using MultipartEntity.

How to pass a form input value into a JavaScript function

Give your inputs names it will make it easier

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>

UPDATE:

If you give your button an id things can be even easier:

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>

Javascript:

var button = document.getElementById("theButton"),
value =  button.form.valueId.value;
button.onclick = function() {
    foo(value);
}

Combine two or more columns in a dataframe into a new column with a new name

Using dplyr::mutate:

library(dplyr)
df <- mutate(df, x = paste(n, s)) 

df 
> df
  n  s     b    x
1 2 aa  TRUE 2 aa
2 3 bb FALSE 3 bb
3 5 cc  TRUE 5 cc

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

Converting String to "Character" array in Java

You have to write your own method in this case. Use a loop and get each character using charAt(i) and set it to your Character[] array using arrayname[i] = string.charAt[i].

Getting hold of the outer class object from the inner class object

Here's the example:

// Test
public void foo() {
    C c = new C();
    A s;
    s = ((A.B)c).get();
    System.out.println(s.getR());
}

// classes
class C {}

class A {
   public class B extends C{
     A get() {return A.this;}
   }
   public String getR() {
     return "This is string";
   }
}

Determine a string's encoding in C#

My finally working approach is to try potential candidates of expected encodings by detecting invalid characters in the strings created from the byte array by the encodings. If I don't encounter invalid characters, I suppose the tested encoding works fine for the tested data.

For me, having only Latin and German special characters to consider, in order to determine the proper encoding for a byte array, I try to detect invalid characters in a string with this method:

    /// <summary>
    /// detect invalid characters in string, use to detect improper encoding
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool DetectInvalidChars(string s)
    {
        const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
        return s.Any(ch => !(
            specialChars.Contains(ch) ||
            (ch >= '0' && ch <= '9') ||
            (ch >= 'a' && ch <= 'z') ||
            (ch >= 'A' && ch <= 'Z')));
    }

(NB: if you have other Latin-based languages to consider, you might want to adapt the specialChars const string in the code)

Then I use it like this (I only expect UTF-8 or Default encoding):

        // determine encoding by detecting invalid characters in string
        var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
        if (StringFuncs.DetectInvalidChars(invoiceXmlText))
            invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default

npm install doesn't create node_modules directory

For node_modules you have to follow the below steps

1) In Command prompt -> Goto your project directory.

2) Command :npm init

3) It asks you to set up your package.json file

4) Command: npm install or npm update

What's a clean way to stop mongod on Mac OS X?

If you installed mongodb with homebrew, there's an easier way:

List mongo job with launchctl:

launchctl list | grep mongo

Stop mongo job:

launchctl stop <job label>

(For me this is launchctl stop homebrew.mxcl.mongodb)

Start mongo job:

launchctl start <job label>

How to get source code of a Windows executable?

For Any *.Exe file written in any language .You can view the source code with hiew (otherwise Hackers view). You can download it at www.hiew.ru. It will be the demo version but still can view the code.

After this follow these steps:

  1. Press alt+f2 to navigate to the file.

  2. Press enter to see its assembly / c++ code.

How to map an array of objects in React

@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this

[{
    name: 'Sam',
    email: '[email protected]'
 },
 {
    name: 'Ash',
    email: '[email protected]'
 }
].map( ( {name, email} ) => {
    return <p key={email}>{name} - {email}</p>
})

Cheers!

What is a reasonable code coverage % for unit tests (and why)?

It depends greatly on your application. For example, some applications consist mostly of GUI code that cannot be unit tested.

Disable double-tap "zoom" option in browser on touch devices

* {
    -ms-touch-action: manipulation;
    touch-action: manipulation;
}

Disable double tap to zoom on touch screens. Internet explorer included.

SQL Server - How to lock a table until a stored procedure finishes

Needed this answer myself and from the link provided by David Moye, decided on this and thought it might be of use to others with the same question:

CREATE PROCEDURE ...
AS
BEGIN
  BEGIN TRANSACTION

  -- lock table "a" till end of transaction
  SELECT ...
  FROM a
  WITH (TABLOCK, HOLDLOCK)
  WHERE ...

  -- do some other stuff (including inserting/updating table "a")



  -- release lock
  COMMIT TRANSACTION
END

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Without external variables:

       $('.element').bind('mousewheel', function(e, d) {
            if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
                || (this.scrollTop === 0 && d > 0)) {
                e.preventDefault();
            }
        });

How to get JSON from URL in JavaScript?

//Resolved
const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => {
      console.log(response);
    });


//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);

Loop through all the rows of a temp table and call a stored procedure for each row

Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.

You may want to experiment with BulkCopy in your C# or VB.Net code.

assign value using linq

using Linq would be:

 listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";

UPDATE

This can be simplified to be...

 listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";

UPDATE

For multiple items (condition is met by multiple items):

 listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");

Simple conversion between java.util.Date and XMLGregorianCalendar

I had to make some changes to make it work, as some things seem to have changed in the meantime:

  • xjc would complain that my adapter does not extend XmlAdapter
  • some bizarre and unneeded imports were drawn in (org.w3._2001.xmlschema)
  • the parsing methods must not be static when extending the XmlAdapter, obviously

Here's a working example, hope this helps (I'm using JodaTime but in this case SimpleDate would be sufficient):

import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;

public class DateAdapter extends XmlAdapter<Object, Object> {
    @Override
    public Object marshal(Object dt) throws Exception {
        return new DateTime((Date) dt).toString("YYYY-MM-dd");
    }

    @Override
        public Object unmarshal(Object s) throws Exception {
        return DatatypeConverter.parseDate((String) s).getTime();
    }
}

In the xsd, I have followed the excellent references given above, so I have included this xml annotation:

<xsd:appinfo>
    <jaxb:schemaBindings>
        <jaxb:package name="at.mycomp.xml" />
    </jaxb:schemaBindings>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:date"
              parseMethod="at.mycomp.xml.DateAdapter.unmarshal"
          printMethod="at.mycomp.xml.DateAdapter.marshal" />
    </jaxb:globalBindings>
</xsd:appinfo>

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Apache VirtualHost 403 Forbidden

I was having the same problem with a virtual host on Ubuntu 14.04

For me the following solution worked:

http://ubuntuforums.org/showthread.php?t=2185282

It's just adding a <Directory > tag to /etc/apache2/apache2.conf

libpthread.so.0: error adding symbols: DSO missing from command line

The same thing happened to me as I was installing the HPCC benchmark (includes HPL and a few other benchmarks). I added -lm to the compiler flags in my build script and then it successfully compiled.

Can we execute a java program without a main() method?

Since you tagged Java-ee as well - then YES it is possible.

and in core java as well it is possible using static blocks

and check this How can you run a Java program without main method?

Edit:
as already pointed out in other answers - it does not support from Java 7

Don't reload application when orientation changes

http://animeshrivastava.blogspot.in/2017/08/activity-lifecycle-oncreate-beating_3.html

@Override
protected void onSaveInstanceState(Bundle b)
{
        super.onSaveInstanceState(b);
    String str="Screen Change="+String.valueOf(screenChange)+"....";
        Toast.makeText(ctx,str+"You are changing orientation...",Toast.LENGTH_SHORT).show();
    screenChange=true;

}

Build and Install unsigned apk on device without the development server?

After you follow the first response, you can run your app using

react-native run-android --variant=debug

And your app will run without need for the packager

Open a new tab in the background?

As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.

For example in firefox preferences:

Firefox setup example

Notice the last option.

How to do a deep comparison between 2 objects with lodash?

For anyone stumbling upon this thread, here's a more complete solution. It will compare two objects and give you the key of all properties that are either only in object1, only in object2, or are both in object1 and object2 but have different values:

/*
 * Compare two objects by reducing an array of keys in obj1, having the
 * keys in obj2 as the intial value of the result. Key points:
 *
 * - All keys of obj2 are initially in the result.
 *
 * - If the loop finds a key (from obj1, remember) not in obj2, it adds
 *   it to the result.
 *
 * - If the loop finds a key that are both in obj1 and obj2, it compares
 *   the value. If it's the same value, the key is removed from the result.
 */
function getObjectDiff(obj1, obj2) {
    const diff = Object.keys(obj1).reduce((result, key) => {
        if (!obj2.hasOwnProperty(key)) {
            result.push(key);
        } else if (_.isEqual(obj1[key], obj2[key])) {
            const resultKeyIndex = result.indexOf(key);
            result.splice(resultKeyIndex, 1);
        }
        return result;
    }, Object.keys(obj2));

    return diff;
}

Here's an example output:

// Test
let obj1 = {
    a: 1,
    b: 2,
    c: { foo: 1, bar: 2},
    d: { baz: 1, bat: 2 }
}

let obj2 = {
    b: 2, 
    c: { foo: 1, bar: 'monkey'}, 
    d: { baz: 1, bat: 2 }
    e: 1
}
getObjectDiff(obj1, obj2)
// ["c", "e", "a"]

If you don't care about nested objects and want to skip lodash, you can substitute the _.isEqual for a normal value comparison, e.g. obj1[key] === obj2[key].

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %>

Executes the ruby code within the brackets.

<%= %>

Prints something into erb file.

<%== %>

Equivalent to <%= raw %>. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)

<% -%>

Avoids line break after expression.

<%# %>

Comments out code within brackets; not sent to client (as opposed to HTML comments).

Visit Ruby Doc for more infos about ERB.

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

How to declare 2D array in bash

If each row of the matrix is the same size, then you can simply use a linear array and multiplication.

That is,

a=()
for (( i=0; i<4; ++i )); do
  for (( j=0; j<5; ++j )); do
     a[i*5+j]=0
  done
done

Then your a[2][3] = 3 becomes

a[2*5+3] = 3

This approach might be worth turning into a set of functions, but since you can't pass arrays to or return arrays from functions, you would have to use pass-by-name and sometimes eval. So I tend to file multidimensional arrays under "things bash is simply Not Meant To Do".

How to update core-js to core-js@3 dependency?

For ng9 upgraders:

npm i -g core-js@^3

..then:

npm cache clean -f

..followed by:

npm i

clearInterval() not working

i think you should do:

var myInterval
on.onclick = function() {
    myInterval=setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(myInterval);
}; 

Rendering raw html with reactjs

I have tried this pure component:

const RawHTML = ({children, className = ""}) => 
<div className={className}
  dangerouslySetInnerHTML={{ __html: children.replace(/\n/g, '<br />')}} />

Features

  • Takes classNameprop (easier to style it)
  • Replaces \n to <br /> (you often want to do that)
  • Place content as children when using the component like:
  • <RawHTML>{myHTML}</RawHTML>

I have placed the component in a Gist at Github: RawHTML: ReactJS pure component to render HTML

Validate date in dd/mm/yyyy format using JQuery Validate

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

Can I have multiple background images using CSS?

CSS3 allows this sort of thing and it looks like this:

body {
    background-image: url(images/bgtop.png), url(images/bg.png);
    background-repeat: repeat-x, repeat;
}

The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:

<body>
    <div id="bgTopDiv">
        content here
    </div>
</body>
body{
    background-image: url(images/bg.png);
}
#bgTopDiv{
    background-image: url(images/bgTop.png);
    background-repeat: repeat-x;
}

How can I do a case insensitive string comparison?

This is not the best practice in .NET framework (4 & +) to check equality

String.Compare(x.Username, (string)drUser["Username"], 
                  StringComparison.OrdinalIgnoreCase) == 0

Use the following instead

String.Equals(x.Username, (string)drUser["Username"], 
                   StringComparison.OrdinalIgnoreCase) 

MSDN recommends:

  • Use an overload of the String.Equals method to test whether two strings are equal.
  • Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.

Django: Model Form "object has no attribute 'cleaned_data'"

For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

Just get rid of the second form = SearchForm(request.POST) and all should be well.

Converting Integer to String with comma for thousands

Integers:

int value = 100000; 
String.format("%,d", value); // outputs 100,000

Doubles:

double value = 21403.3144d;
String.format("%,.2f", value); // outputs 21,403.31

String.format is pretty powerful.

- Edited per psuzzi feedback.

Android Studio Rendering Problems : The following classes could not be found

I faced this error when I created second activity in my project in the newly updated Android Studio,I solved it simply by copy pasting the whole xml code from first layout to the second and then I just removed the code that's unnecessary.

How do I get HTTP Request body content in Laravel?

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Date formatting in WPF datagrid

If your bound property is DateTime, then all you need is

Binding={Property, StringFormat=d}

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

var myModule = angular.module('myModule', []);

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

CSS Font Border?

There seems to be a 'text-stroke' property, but (at least for me) it only works in Safari.

http://webkit.org/blog/85/introducing-text-stroke/

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

I run this

var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);

$.ajax({
    type: 'GET',
    url: 'linkserverApi',
    success: function(success) {
        console.log('Success!');
        console.log(success);
    },
    error: function() {
        console.log('Uh Oh!');
    },
    jsonp: 'jsonp'

});

And edit header in the response

'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'

'Access-Control-Max-Age' , '3628800'

'Access-Control-Allow-Origin', 'websiteresponseUrl'

'Content-Type', 'text/javascript; charset=utf8'

Using regular expression in css?

An ID is meant to identify the element uniquely. Any styles applied to it should also be unique to that element. If you have styles you want to apply to many elements, you should add a class to them all, rather than relying on ID selectors...

<div id="sections">
   <div id="s1" class="sec">...</div>
   <div id="s2" class="sec">...</div>
   ...
</div>

and

.sec {
    ...
}

Or in your specific case you could select all divisions inside your parent container, if nothing else is inside it, like so:

#sections > div {
    ...
}

What is the difference between decodeURIComponent and decodeURI?

encodeURIComponent()

Converts the input into a URL-encoded string

encodeURI()

URL-encodes the input, but assumes a full URL is given, so returns a valid URL by not encoding the protocol (e.g. http://) and host name (e.g. www.stackoverflow.com).

decodeURIComponent() and decodeURI() are the opposite of the above

Average of multiple columns

You don't mention if the columns are nullable. If they are and you want the same semantics that the AVG aggregate provides you can do (2008)

SELECT *,
       (SELECT AVG(c)
        FROM   (VALUES(R1),
                      (R2),
                      (R3),
                      (R4),
                      (R5)) T (c)) AS [Average]
FROM   Request  

The 2005 version is a bit more tedious

SELECT *,
       (SELECT AVG(c)
        FROM   (SELECT R1
                UNION ALL
                SELECT R2
                UNION ALL
                SELECT R3
                UNION ALL
                SELECT R4
                UNION ALL
                SELECT R5) T (c)) AS [Average]
FROM   Request

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

How to update Ruby to 1.9.x on Mac?

I'll make a strong suggestion for rvm.

It's a great way to manage multiple Rubies and gems sets without colliding with the system version.


I'll add that now (4/2/2013), I use rbenv a lot, because my needs are simple. RVM is great, but it's got a lot of capability I never need, so I have it on some machines and rbenv on my desktop and laptop. It's worth checking out both and seeing which works best for your needs.

Preventing iframe caching in browser

I found this problem in the latest Chrome as well as the latest Safari on the Mac OS X as of Mar 17, 2016. None of the fixes above worked for me, including assigning src to empty and then back to some site, or adding in some randomly-named "name" parameter, or adding in a random number on the end of the URL after the hash, or assigning the content window href to the src after assigning the src.

In my case, it was because I was using Javascript to update the IFRAME, and only switching the hash in the URL.

The workaround in my case was that I created an interim URL that had a 0 second meta redirect to that other page. It happens so fast that I hardly notice the screen flash. Plus, I made the background color of the interim page the same as the other page, and so you notice it even less.

JavaScript checking for null vs. undefined and difference between == and ===

The difference is subtle.

In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.

But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).

Example:

var a;
typeof a;     # => "undefined"

a = null;
typeof null;  # => "object"

This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:

function doSomething(first, second, optional) {
    if (typeof optional === "undefined") {
        optional = "three";
    }
    // do something
}

If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.

As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.

You may use those operators to check between undefined an null. For example:

null === null            # => true
undefined === undefined  # => true
undefined === null       # => false
undefined == null        # => true

The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:

function test(val) {
    return val == null;
}
test(null);       # => true
test(undefined);  # => true

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

Update React component every second

class ShowDateTime extends React.Component {
   constructor() {
      super();
      this.state = {
        curTime : null
      }
    }
    componentDidMount() {
      setInterval( () => {
        this.setState({
          curTime : new Date().toLocaleString()
        })
      },1000)
    }
   render() {
        return(
          <div>
            <h2>{this.state.curTime}</h2>
          </div>
        );
      }
    }

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had a similar issue while working with Jupyter. I was trying to copy files from one directory to another using copy function of shutil. The problem was that I had forgotten to import the package.(Silly) But instead of python giving import error, it gave this error.

Solved by adding:

from shutil import copy

Convert string to hex-string in C#

First you'll need to get it into a byte[], so do this:

byte[] ba = Encoding.Default.GetBytes("sample");

and then you can get the string:

var hexString = BitConverter.ToString(ba);

now, that's going to return a string with dashes (-) in it so you can then simply use this:

hexString = hexString.Replace("-", "");

to get rid of those if you want.

NOTE: you could use a different Encoding if you needed to.

What is the best way to generate a unique and short file name in Java

This works for me:

String generateUniqueFileName() {
    String filename = "";
    long millis = System.currentTimeMillis();
    String datetime = new Date().toGMTString();
    datetime = datetime.replace(" ", "");
    datetime = datetime.replace(":", "");
    String rndchars = RandomStringUtils.randomAlphanumeric(16);
    filename = rndchars + "_" + datetime + "_" + millis;
    return filename;
}

// USE:

String newFile;
do{
newFile=generateUniqueFileName() + "." + FileExt;
}
while(new File(basePath+newFile).exists());

Output filenames should look like :

2OoBwH8OwYGKW2QE_4Sep2013061732GMT_1378275452253.Ext

How to use not contains() in xpath?

You can use not(expression) function

not() is a function in xpath (as opposed to an operator)

Example:

//a[not(contains(@id, 'xx'))]

OR

expression != true()

Twitter Bootstrap alert message close and open again

I just used a model variable to show/hide the dialog and removed the data-dismiss="alert"

Example:

<div data-ng-show="vm.result == 'error'" class="alert alert-danger alert-dismissable">
    <button type="button" class="close" data-ng-click="vm.result = null" aria-hidden="true">&times;</button>
    <strong>Error  !  </strong>{{vm.exception}}
</div>

works for me and stops the need to go out to jquery

The page cannot be displayed because an internal server error has occurred on server

I think the best first approach is to make sure to turn on detailed error messages via your web.config file, like this:

<configuration>
    <system.webServer>
        <httpErrors errorMode="Detailed"></httpErrors>
    </system.webServer>
</configuration>

After doing this, you should get a more detailed error message from the server.

In my particular case, the more detailed error pointed out that my <defaultDocument> section of the web.config file was not allowed at the folder level where I'd placed my web.config. It said

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". "

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

Difference between & and && in Java?

& is bitwise AND operator comparing bits of each operand.
For example,

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100


&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I encountered a similar problem with glassfish application server and Oracle JDK/JRE but not in Open JDK/JRE.

When connecting to a SSL domain I always ran into:

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
...
Caused by: java.io.EOFException: SSL peer shut down incorrectly

The solution for me was to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files because the server only understood certificates that are not included in Oracle JDK by default, only OpenJDK includes them. After installing everything worked like charme.


JCE 7: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

JCE 8: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

How to reduce the space between <p> tags?

use css :

p { margin:0 }

Try this wonderful plugin http://www.getfirebug.com :)

EDIT: Firebug is now closed as a project, it was migrated to https://www.mozilla.org/en-US/firefox/developer

How to select different app.config for several build configurations

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

Hope this helps.

Regex replace (in Python) - a simpler way?

The short version is that you cannot use variable-width patterns in lookbehinds using Python's re module. There is no way to change this:

>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    re.sub("(?<=fo+)bar(?=baz)", "quux", string)
  File "C:\Development\Python25\lib\re.py", line 150, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "C:\Development\Python25\lib\re.py", line 241, in _compile
    raise error, v # invalid expression
error: look-behind requires fixed-width pattern

This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:

>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
        return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)

This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.

Jackson: how to prevent field serialization

Starting with Jackson 2.6, a property can be marked as read- or write-only. It's simpler than hacking the annotations on both accessors and keeps all the information in one place:

public class User {
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;
}

Using Gradle to build a jar with dependencies

Excluding unwanted Manifest entries fixed the MainClass file not found error in a Gradle build jar file.

jar{
    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
    from {
      -----
    }
}

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

The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:

<VirtualHost 111.22.33.55>
    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld
</VirtualHost>

However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.

List directory in Go

From your description, what you probably want is os.Readdirnames.

func (f *File) Readdirnames(n int) (names []string, err error)

Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.

...

If n <= 0, Readdirnames returns all the names from the directory in a single slice.

Snippet:

file, err := os.Open(path)
if err != nil {
    return err
}
defer file.Close()
names, err := file.Readdirnames(0)
if err != nil {
    return err
}
fmt.Println(names)

Credit to SquattingSlavInTracksuit's comment; I'd have suggested promoting their comment to an answer if I could.

Java 8 Streams FlatMap method example

A very simple example: Split a list of full names to get a list of names, regardless of first or last

 List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");

 fullNames.stream()
            .flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
            .forEach(System.out::println);

This prints out:

Barry
Allen
Bruce
Wayne
Clark
Kent

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

How can I generate random alphanumeric strings?

Horrible, I know, but I just couldn't help myself:


namespace ConsoleApplication2
{
    using System;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            Random adomRng = new Random();
            string rndString = string.Empty;
            char c;

            for (int i = 0; i < 8; i++)
            {
                while (!Regex.IsMatch((c=Convert.ToChar(adomRng.Next(48,128))).ToString(), "[A-Za-z0-9]"));
                rndString += c;
            }

            Console.WriteLine(rndString + Environment.NewLine);
        }
    }
}

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

Shortest way to check for null and assign another value if not

My guess is the best you can come up with is

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
                                                      : planRec.approved_by.ToString();

Of course since you're hinting at the fact that approved_by is an object (which cannot equal ""), this would be rewritten as

this.approved_by = (planRec.approved_by ?? string.Empty).ToString();

Android-java- How to sort a list of objects by a certain value within the object

You should use Comparable instead of a Comparator if a default sort is what your looking for.

See here, this may be of some help - When should a class be Comparable and/or Comparator?

Try this -

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestSort {

    public static void main(String args[]){

        ToSort toSort1 = new ToSort(new Float(3), "3");
        ToSort toSort2 = new ToSort(new Float(6), "6");
        ToSort toSort3 = new ToSort(new Float(9), "9");
        ToSort toSort4 = new ToSort(new Float(1), "1");
        ToSort toSort5 = new ToSort(new Float(5), "5");
        ToSort toSort6 = new ToSort(new Float(0), "0");
        ToSort toSort7 = new ToSort(new Float(3), "3");
        ToSort toSort8 = new ToSort(new Float(-3), "-3");

        List<ToSort> sortList = new ArrayList<ToSort>();
        sortList.add(toSort1);
        sortList.add(toSort2);
        sortList.add(toSort3);
        sortList.add(toSort4);
        sortList.add(toSort5);
        sortList.add(toSort6);
        sortList.add(toSort7);
        sortList.add(toSort8);

        Collections.sort(sortList);

        for(ToSort toSort : sortList){
            System.out.println(toSort.toString());
        }
    }

}

public class ToSort implements Comparable<ToSort> {

    private Float val;
    private String id;

    public ToSort(Float val, String id){
        this.val = val;
        this.id = id;
    }

    @Override
    public int compareTo(ToSort f) {

        if (val.floatValue() > f.val.floatValue()) {
            return 1;
        }
        else if (val.floatValue() <  f.val.floatValue()) {
            return -1;
        }
        else {
            return 0;
        }

    }

    @Override
    public String toString(){
        return this.id;
    }
}

Replace non ASCII character from string

FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:

String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");

=> will produce "oau"

That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.

UL has margin on the left

The <ul> element has browser inherent padding & margin by default. In your case, Use

#footer ul {
    margin: 0; /* To remove default bottom margin */ 
    padding: 0; /* To remove default left padding */
}

or a CSS browser reset ( https://cssreset.com/ ) to deal with this.

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

You might want to add name for the unique key as many times the default unique_key name by rails can be too long for which the DB can throw the error.

To add name for your index just use the name: option. The migration query might look something like this -

add_index :table_name, [:column_name_a, :column_name_b, ... :column_name_n], unique: true, name: 'my_custom_index_name'

More info - http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

Is there a "previous sibling" selector?

Another flexbox solution

You can use inverse the order of elements in HTML. Then besides using order as in Michael_B's answer you can use flex-direction: row-reverse; or flex-direction: column-reverse; depending on your layout.

Working sample:

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row-reverse;_x000D_
   /* Align content at the "reversed" end i.e. beginning */_x000D_
  justify-content: flex-end;_x000D_
}_x000D_
_x000D_
/* On hover target its "previous" elements */_x000D_
.flex-item:hover ~ .flex-item {_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
/* styles just for demo */_x000D_
.flex-item {_x000D_
  background-color: orange;_x000D_
  color: white;_x000D_
  padding: 20px;_x000D_
  font-size: 3rem;_x000D_
  border-radius: 50%;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div class="flex-item">5</div>_x000D_
  <div class="flex-item">4</div>_x000D_
  <div class="flex-item">3</div>_x000D_
  <div class="flex-item">2</div>_x000D_
  <div class="flex-item">1</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to modify the nodejs request default timeout time?

I'm assuming you're using express, given the logs you have in your question. The key is to set the timeout property on server (the following sets the timeout to one second, use whatever value you want):

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;

If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:

var http = require('http');
var server = http.createServer(function (req, res) {
  setTimeout(function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
  }, 200);
}).listen(1337, '127.0.0.1');

server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');

trigger body click with jQuery

As mentioned by Seeker, the problem could have been that you setup the click() function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.

An important point is to run such scripts after the document is ready. This is done by placing the click() initialization within that other function as in:

jQuery(document).ready(function()
  {
    jQuery("body").click(function()
      {
        // ... your click code here ...
      });
  });

This is usually the best method, especially if you include your JavaScript code in your <head> tag. If you include it at the very bottom of the page, then the ready() function is less important, but it may still be useful.

ImportError: No module named google.protobuf

To find where the name google clashes .... try this:

python3

then >>> help('google')

... I got info about google-auth:

NAME
    google

PACKAGE CONTENTS
    auth (package)
    oauth2 (package)

Also then try

pip show google-auth

Then

sudo pip3 uninstall google-auth

... and re-try >>> help('google')

I then see protobuf:

NAME
    google

PACKAGE CONTENTS
    protobuf (package)

Why shouldn't I use "Hungarian Notation"?

Joel Spolsky wrote a good blog post about this. http://www.joelonsoftware.com/articles/Wrong.html Basically it comes down to not making your code harder to read when a decent IDE will tell you want type the variable is if you can't remember. Also, if you make your code compartmentalized enough, you don't have to remember what a variable was declared as three pages up.

.htaccess not working apache

Just follow 3 steps

  1. Enable mode_rewrite using following command

    sudo a2enmod rewrite

Password will be asked. So enter your password

  1. Update your 000-default.conf or default.conf file located at /etc/apache2/sites-available/ directory. you can not edit it directly. so use following command to open

    sudo gedit /etc/apache2/sites-available/000-default.conf

Or sudo gedit /etc/apache2/sites-available/default.conf

you will get

DocumentRoot /var/www/html

OR

DocumentRoot /var/www

line. Add following code after it.

<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

Make user the directory tag path is same as shown in your file.

  1. Restart your apache server using following command

    sudo service apache2 restart

What is JSON and why would I use it?

We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.

For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON). That is one problem where you could use JSON perhaps.

Here is something practical: Yahoo JSON

Swap x and y axis without manually swapping values

Using Excel 2010 x64. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:

Swap the data columns, to end with X_data in column A and Y_data in column B.

My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me: an Excel XY plot literally wants {x,y} pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away. For me an XY plot means Y=f(X) plotted.

Need to find element in selenium by css

By.cssSelector(".ban") or By.cssSelector(".hot") or By.cssSelector(".ban.hot") should all select it unless there is another element that has those classes.

In CSS, .name means find an element that has a class with name. .foo.bar.baz means to find an element that has all of those classes (in the same element).

However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.

Data binding for TextBox

You can't databind to a property and then explictly assign a value to the databound property.

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

In place of 1.+ use the latest version of crashlytics -

 dependencies {
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
    }

you should use this way -

dependencies {
            classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
        }

your problem will be resolved for sure. Happy coding !!

Display a view from another controller in ASP.NET MVC

You can use:

return View("../Category/NotFound", model);

It was tested in ASP.NET MVC 3, but should also work in ASP.NET MVC 2.

Using the passwd command from within a shell script

from "man 1 passwd":

   --stdin
          This option is used to indicate that passwd should read the new
          password from standard input, which can be a pipe.

So in your case

adduser "$1"
echo "$2" | passwd "$1" --stdin

[Update] a few issues were brought up in the comments:

Your passwd command may not have a --stdin option: use the chpasswd utility instead, as suggested by ashawley.

If you use a shell other than bash, "echo" might not be a builtin command, and the shell will call /bin/echo. This is insecure because the password will show up in the process table and can be seen with tools like ps.

In this case, you should use another scripting language. Here is an example in Perl:

#!/usr/bin/perl -w
open my $pipe, '|chpasswd' or die "can't open pipe: $!";
print {$pipe} "$username:$password";
close $pipe

Display HTML form values in same page after submit using Ajax

display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.

Negative regex for Perl string pattern match

Sample text:

Clinton said
Bush used crayons
Reagan forgot

Just omitting a Bush match:

$ perl -ne 'print if /^(Clinton|Reagan)/' textfile
Clinton said
Reagan forgot

Or if you really want to specify:

$ perl -ne 'print if /^(?!Bush)(Clinton|Reagan)/' textfile
Clinton said
Reagan forgot

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

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

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

How to repeat a string a variable number of times in C++?

As Commodore Jaeger alluded to, I don't think any of the other answers actually answer this question; the question asks how to repeat a string, not a character.

While the answer given by Commodore is correct, it is quite inefficient. Here is a faster implementation, the idea is to minimise copying operations and memory allocations by first exponentially growing the string:

#include <string>
#include <cstddef>

std::string repeat(std::string str, const std::size_t n)
{
    if (n == 0) {
        str.clear();
        str.shrink_to_fit();
        return str;
    } else if (n == 1 || str.empty()) {
        return str;
    }
    const auto period = str.size();
    if (period == 1) {
        str.append(n - 1, str.front());
        return str;
    }
    str.reserve(period * n);
    std::size_t m {2};
    for (; m < n; m *= 2) str += str;
    str.append(str.c_str(), (n - (m / 2)) * period);
    return str;
}

We can also define an operator* to get something closer to the Python version:

#include <utility>

std::string operator*(std::string str, std::size_t n)
{
    return repeat(std::move(str), n);
}

On my machine this is around 10x faster than the implementation given by Commodore, and about 2x faster than a naive 'append n - 1 times' solution.

json_decode to array

in PHP json_decode convert json data into PHP associated array
For Ex: $php-array= json_decode($json-data, true); print_r($php-array);

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

IntelliJ IDEA generating serialVersionUID

Easiest modern method: Alt+Enter on

private static final long serialVersionUID = ;

IntelliJ will underline the space after the =. put your cursor on it and hit alt+Enter (Option+Enter on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.

Why use $_SERVER['PHP_SELF'] instead of ""

Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF'].

When using $_SERVER['PHP_SELF'] it is very easy to inject malicious data by simply appending /<script>... after the whatever.php part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.

Jump into interface implementation in Eclipse IDE

The best solution would be Ctrl+Alt+I.

Why does Git treat this text file as a binary file?

This is also caused (on Windows at least) by text files that have UTF-8 with BOM encoding. Changing the encoding to regular UTF-8 immediately made Git see the file as type=text

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

In my case clean project and rebuild works, no need to disable instant run and restart.

How to set background color of a View

try to add:

setBackgroundColor(Color.parseColor("#FF0000"));

How to show "Done" button on iPhone number pad

The solution in UIKeyboardTypeNumberPad and missing return key works great but only if there are no other non-number pad text fields on the screen.

I took that code and turned it into an UIViewController that you can simply subclass to make number pads work. You will need to get the icons from the above link.

NumberPadViewController.h:

#import <UIKit/UIKit.h>

@interface NumberPadViewController : UIViewController {
    UIImage *numberPadDoneImageNormal;
    UIImage *numberPadDoneImageHighlighted;
    UIButton *numberPadDoneButton;
}

@property (nonatomic, retain) UIImage *numberPadDoneImageNormal;
@property (nonatomic, retain) UIImage *numberPadDoneImageHighlighted;
@property (nonatomic, retain) UIButton *numberPadDoneButton;

- (IBAction)numberPadDoneButton:(id)sender;

@end

and NumberPadViewController.m:

#import "NumberPadViewController.h"

@implementation NumberPadViewController

@synthesize numberPadDoneImageNormal;
@synthesize numberPadDoneImageHighlighted;
@synthesize numberPadDoneButton;

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
    if ([super initWithNibName:nibName bundle:nibBundle] == nil)
        return nil;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
        self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp3.png"];
        self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown3.png"];
    } else {        
        self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp.png"];
        self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown.png"];
    }        
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Add listener for keyboard display events
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                    selector:@selector(keyboardDidShow:) 
                                                     name:UIKeyboardDidShowNotification 
                                                   object:nil];     
    } else {
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(keyboardWillShow:) 
                                                     name:UIKeyboardWillShowNotification 
                                                   object:nil];
    }

    // Add listener for all text fields starting to be edited
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(textFieldDidBeginEditing:)
                                                 name:UITextFieldTextDidBeginEditingNotification 
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:UIKeyboardDidShowNotification 
                                                      object:nil];      
    } else {
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:UIKeyboardWillShowNotification 
                                                      object:nil];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UITextFieldTextDidBeginEditingNotification 
                                                  object:nil];
    [super viewWillDisappear:animated];
}

- (UIView *)findFirstResponderUnder:(UIView *)root {
    if (root.isFirstResponder)
        return root;    
    for (UIView *subView in root.subviews) {
        UIView *firstResponder = [self findFirstResponderUnder:subView];        
        if (firstResponder != nil)
            return firstResponder;
    }
    return nil;
}

- (UITextField *)findFirstResponderTextField {
    UIResponder *firstResponder = [self findFirstResponderUnder:[self.view window]];
    if (![firstResponder isKindOfClass:[UITextField class]])
        return nil;
    return (UITextField *)firstResponder;
}

- (void)updateKeyboardButtonFor:(UITextField *)textField {

    // Remove any previous button
    [self.numberPadDoneButton removeFromSuperview];
    self.numberPadDoneButton = nil;

    // Does the text field use a number pad?
    if (textField.keyboardType != UIKeyboardTypeNumberPad)
        return;

    // If there's no keyboard yet, don't do anything
    if ([[[UIApplication sharedApplication] windows] count] < 2)
        return;
    UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];

    // Create new custom button
    self.numberPadDoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.numberPadDoneButton.frame = CGRectMake(0, 163, 106, 53);
    self.numberPadDoneButton.adjustsImageWhenHighlighted = FALSE;
    [self.numberPadDoneButton setImage:self.numberPadDoneImageNormal forState:UIControlStateNormal];
    [self.numberPadDoneButton setImage:self.numberPadDoneImageHighlighted forState:UIControlStateHighlighted];
    [self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];

    // Locate keyboard view and add button
    NSString *keyboardPrefix = [[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2 ? @"<UIPeripheralHost" : @"<UIKeyboard";
    for (UIView *subView in keyboardWindow.subviews) {
        if ([[subView description] hasPrefix:keyboardPrefix]) {
            [subView addSubview:self.numberPadDoneButton];
            [self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
    }
}

- (void)textFieldDidBeginEditing:(NSNotification *)note {
    [self updateKeyboardButtonFor:[note object]];
}

- (void)keyboardWillShow:(NSNotification *)note {
    [self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}

- (void)keyboardDidShow:(NSNotification *)note {
    [self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}

- (IBAction)numberPadDoneButton:(id)sender {
    UITextField *textField = [self findFirstResponderTextField];
    [textField resignFirstResponder];
}

- (void)dealloc {
    [numberPadDoneImageNormal release];
    [numberPadDoneImageHighlighted release];
    [numberPadDoneButton release];
    [super dealloc];
}

@end

Enjoy.

git clone through ssh

This is possibly unrelated directly to the question; but one mistake I just made myself, and I see in the OP, is the URL specification ssh://user@server:/GitRepos/myproject.git - namely, you have both a colon :, and a forward slash / after it signifying an absolute path.

I then found Git clone, ssh: Could not resolve hostname – git , development – Nicolas Kuttler (as that was the error I was getting, on git version 1.7.9.5), noting:

The problem with the command I used initially was that I tried to use an scp-like syntax.

... which was also my problem! So basically in git with ssh, you either use

  • ssh://[email protected]/absolute/path/to/repo.git/ - just a forward slash for absolute path on server
  • [email protected]:relative/path/to/repo.git/ - just a colon (it mustn't have the ssh:// for relative path on server (relative to home dir of username on server machine)

Hope this helps someone,
Cheers!

Adjusting HttpWebRequest Connection Timeout in C#

Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.

From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:

I Set:

.Timeout=5000
.ReadWriteTimeout=32000

The connect and post time for the HttpWebRequest took 26ms

but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.

I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.

For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

Execute bash script from URL

Use:

curl -s -L URL_TO_SCRIPT_HERE | bash

For example:

curl -s -L http://bitly/10hA8iC | bash

Finding the length of a Character Array in C

Provided the char array is null terminated,

char chararray[10] = { 0 };
size_t len = strlen(chararray);

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

Verify External Script Is Loaded

Merging several answers from above into an easy to use function

function GetScriptIfNotLoaded(scriptLocationAndName)
{
  var len = $('script[src*="' + scriptLocationAndName +'"]').length;

  //script already loaded!
  if (len > 0)
      return;

  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = scriptLocationAndName;
  head.appendChild(script);
}

How do I specify unique constraint for multiple columns in MySQL?

For adding unique index following are required:

1) table_name
2) index_name
3) columns on which you want to add index

ALTER TABLE  `tablename` 
ADD UNIQUE index-name
(`column1` ,`column2`,`column3`,...,`columnN`);

In your case we can create unique index as follows:

ALTER TABLE `votes`ADD 
UNIQUE <votesuniqueindex>;(`user` ,`email`,`address`);

Batch file to delete files older than N days

My script to delete files older than a specific year :

@REM _______ GENERATE A CMD TO DELETE FILES OLDER THAN A GIVEN YEAR
@REM _______ (given in _olderthanyear variable)
@REM _______ (you must LOCALIZE the script depending on the dir cmd console output)
@REM _______ (we assume here the following line's format "11/06/2017  15:04            58 389 SpeechToText.zip")

@set _targetdir=c:\temp
@set _olderthanyear=2017

@set _outfile1="%temp%\deleteoldfiles.1.tmp.txt"
@set _outfile2="%temp%\deleteoldfiles.2.tmp.txt"

  @if not exist "%_targetdir%" (call :process_error 1 DIR_NOT_FOUND "%_targetdir%") & (goto :end)

:main
  @dir /a-d-h-s /s /b %_targetdir%\*>%_outfile1%
  @for /F "tokens=*" %%F in ('type %_outfile1%') do @call :process_file_path "%%F" %_outfile2%
  @goto :end

:end
  @rem ___ cleanup and exit
  @if exist %_outfile1% del %_outfile1%
  @if exist %_outfile2% del %_outfile2%
  @goto :eof

:process_file_path %1 %2
  @rem ___ get date info of the %1 file path
  @dir %1 | find "/" | find ":" > %2
  @for /F "tokens=*" %%L in ('type %2') do @call :process_line "%%L" %1
  @goto :eof

:process_line %1 %2
  @rem ___ generate a del command for each file older than %_olderthanyear%
  @set _var=%1
  @rem  LOCALIZE HERE (char-offset,string-length)
  @set _fileyear=%_var:~0,4%
  @set _fileyear=%_var:~7,4%
  @set _filepath=%2
  @if %_fileyear% LSS %_olderthanyear% echo @REM %_fileyear%
  @if %_fileyear% LSS %_olderthanyear% echo @del %_filepath%
  @goto :eof

:process_error %1 %2
  @echo RC=%1 MSG=%2 %3
  @goto :eof

Return content with IHttpActionResult for non-OK response

I would recommend reading this post. There are tons of ways to use existing HttpResponse as suggested, but if you want to take advantage of Web Api 2, then look at using some of the built-in IHttpActionResult options such as

return Ok() 

or

return NotFound()

Choose the right return type for Web Api Controllers

What is the purpose of flush() in Java streams?

If the buffer is full, all strings that is buffered on it, they will be saved onto the disk. Buffers is used for avoiding from Big Deals! and overhead.

In BufferedWriter class that is placed in java libs, there is a one line like:

private static int defaultCharBufferSize = 8192;

If you do want to send data before the buffer is full, you do have control. Just Flush It. Calls to writer.flush() say, "send whatever's in the buffer, now!

reference book: https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208

pages:453

How to make a pure css based dropdown menu?

There is different ways to make dropdown menu using css. Here is simple code.

HTML Code

    <label class="dropdown">

  <div class="dd-button">
    Dropdown
  </div>

  <input type="checkbox" class="dd-input" id="test">

  <ul class="dd-menu">
    <li>Dropdown 1</li>
    <li>Dropdown 2</li>
  </ul>

</label>

CSS Code

body {
  color: #000000;
  font-family: Sans-Serif;
  padding: 30px;
  background-color: #f6f6f6;
}

a {
  text-decoration: none;
  color: #000000;
}

a:hover {
  color: #222222
}

/* Dropdown */

.dropdown {
  display: inline-block;
  position: relative;
}

.dd-button {
  display: inline-block;
  border: 1px solid gray;
  border-radius: 4px;
  padding: 10px 30px 10px 20px;
  background-color: #ffffff;
  cursor: pointer;
  white-space: nowrap;
}

.dd-button:after {
  content: '';
  position: absolute;
  top: 50%;
  right: 15px;
  transform: translateY(-50%);
  width: 0; 
  height: 0; 
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid black;
}

.dd-button:hover {
  background-color: #eeeeee;
}


.dd-input {
  display: none;
}

.dd-menu {
  position: absolute;
  top: 100%;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 0;
  margin: 2px 0 0 0;
  box-shadow: 0 0 6px 0 rgba(0,0,0,0.1);
  background-color: #ffffff;
  list-style-type: none;
}

.dd-input + .dd-menu {
  display: none;
} 

.dd-input:checked + .dd-menu {
  display: block;
} 

.dd-menu li {
  padding: 10px 20px;
  cursor: pointer;
  white-space: nowrap;
}

.dd-menu li:hover {
  background-color: #f6f6f6;
}

.dd-menu li a {
  display: block;
  margin: -10px -20px;
  padding: 10px 20px;
}

.dd-menu li.divider{
  padding: 0;
  border-bottom: 1px solid #cccccc;
}

More css code example

Empty an array in Java / processing

There's

Arrays.fill(myArray, null);

Not that it does anything different than you'd do on your own (it just loops through every element and sets it to null). It's not native in that it's pure Java code that performs this, but it is a library function if maybe that's what you meant.

This of course doesn't allow you to resize the array (to zero), if that's what you meant by "empty". Array sizes are fixed, so if you want the "new" array to have different dimensions you're best to just reassign the reference to a new array as the other answers demonstrate. Better yet, use a List type like an ArrayList which can have variable size.

Why use a READ UNCOMMITTED isolation level?

I always use READ UNCOMMITTED now. It's fast with the least issues. When using other isolations you will almost always come across some Blocking issues.

As long as you use Auto Increment fields and pay a little more attention to inserts then your fine, and you can say goodbye to blocking issues.

You can make errors with READ UNCOMMITED but to be honest, it is very easy make sure your inserts are full proof. Inserts/Updates which use the results from a select are only thing you need to watch out for. (Use READ COMMITTED here, or ensure that dirty reads aren't going to cause a problem)

So go the Dirty Reads (Specially for big reports), your software will run smoother...

How to set full calendar to a specific start date when it's initialized for the 1st time?

In version 2.1.1 this works :

$('#calendar').fullCalendar({
// your calendar settings...
});

$('#calendar').fullCalendar('gotoDate', '2014-05-01');

Documentation about moment time/date format : http://fullcalendar.io/docs/utilities/Moment/ Documentation about the upgrades in version 2 : https://github.com/arshaw/fullcalendar/wiki/Upgrading-to-v2

Force file download with php using header()

Based on Farhan Sahibole's answer:

        header('Content-Disposition: attachment; filename=Image.png');
        header('Content-Type: application/octet-stream'); // Downloading on Android might fail without this
        ob_clean();

        readfile($file);

This is all I needed for this to work. I stripped off anything that isn't required for this to work.

Key is to use ob_clean();

In Python, how do I iterate over a dictionary in sorted key order?

You can now use OrderedDict in Python 2.7 as well:

>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
...                  ('second', 2),
...                  ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]

Here you have the what's new page for 2.7 version and the OrderedDict API.

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

Drawing rotated text on a HTML5 canvas

While this is sort of a follow up to the previous answer, it adds a little (hopefully).

Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3.

So if we think about that like this: move origin to 10, 3, then draw rectangle at 0, 0. Then all we have to do is add a rotate in between.

Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.

We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).

I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.

enter image description here

var font, lineHeight, x, y;

x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';


// Right Aligned
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);


// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;

this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);


// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;

this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);

The line this.context.fillText('right', 0, lineHeight / 2); is basically 0, 0, except we move slightly for the text to be centered near the point

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

How do I import a pre-existing Java project into Eclipse and get up and running?

I think you'll have to import the project via the file->import wizard:

http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse

It's not the last step, but it will start you on your way.

I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

How to save and extract session data in codeigniter

In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';

and create a ci_session table in the database

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

For more details and reference, click here

Java says FileNotFoundException but file exists

Use single forward slash and always type the path manually. For example:

FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");

How to use ADB to send touch events to device using sendevent command?

2.3.5 did not have input tap, just input keyevent and input text You can use the monkeyrunner for it: (this is a copy of the answer at https://stackoverflow.com/a/18959385/1587329):

You might want to use monkeyrunner like this:

$ monkeyrunner
>>> from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
>>> device = MonkeyRunner.waitForConnection()
>>> device.touch(200, 400, MonkeyDevice.DOWN_AND_UP)

You can also do a drag, start activies etc. Have a look at the api for MonkeyDevice.

The remote server returned an error: (403) Forbidden

Add the following line:

request.UseDefaultCredentials = true;

This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.

It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:

request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

Hope this helps.

Add a list item through javascript

I was recently presented with this same challenge and stumbled on this thread but found a simpler solution using append...

var firstname = $('#firstname').val();

$('ol').append( '<li>' + firstname + '</li>' );

Store the firstname value and then use append to add that value as an li to the ol. I hope this helps :)

How to completely remove a dialog on close

$(dialogElement).empty();

$(dialogElement).remove();

this fixes it for real

“tag already exists in the remote" error after recreating the git tag

If you want to UPDATE a tag, let's say it 1.0.0

  1. git checkout 1.0.0
  2. make your changes
  3. git ci -am 'modify some content'
  4. git tag -f 1.0.0
  5. delete remote tag on github: git push origin --delete 1.0.0
  6. git push origin 1.0.0

DONE

android asynctask sending callbacks to ui

I will repeat what the others said, but will just try to make it simpler...

First, just create the Interface class

public interface PostTaskListener<K> {
    // K is the type of the result object of the async task 
    void onPostTask(K result);
}

Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.

public static class LoadData extends AsyncTask<Void, Void, String> {

    private PostTaskListener<String> postTaskListener;

    protected LoadData(PostTaskListener<String> postTaskListener){
        this.postTaskListener = postTaskListener;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null && postTaskListener != null)
            postTaskListener.onPostTask(result);
    }
}

Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:

...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
    @Override
    public void onPostTask(String result) {
        //Your post execution task code
    }
}

// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);

Done!

Check if a string is a valid date using DateTime.TryParse

[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
    string[] formats = { "MM/dd/yyyy" };
    DateTime parsedDateTime;
    return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
                                   DateTimeStyles.None, out parsedDateTime);
}

Simply specify the date time formats that you wish to accept in the array named formats.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

changing the Binding Type from wsHttpbinding to basichttp binding in the endpoint tag and from wsHttpbinding to mexhttpbinginding in metadata endpoint tag helped to overcome the error. Thank you...

A warning - comparison between signed and unsigned integer expressions

It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).

Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:

unsigned u = GetSomeUnsignedValue();
int i = GetSomeSignedValue();

if (i >= 0)
{
    // i is nonnegative, so it is safe to cast to unsigned value
    if ((unsigned)i >= u)
        iIsGreaterThanOrEqualToU();
    else
        iIsLessThanU();
}
else
{
    iIsNegative();
}

Loop through JSON in EJS

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

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

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

wget can't download - 404 error

I had the same problem with a Google Docs URL. Enclosing the URL in quotes did the trick for me:

wget "https://docs.google.com/spreadsheets/export?format=tsv&id=1sSi9f6m-zKteoXA4r4Yq-zfdmL4rjlZRt38mejpdhC23" -O sheet.tsv

No module named Image

You can this query:

pip install image 

I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.

Alter user defined type in SQL Server

As devio says there is no way to simply edit a UDT if it's in use.

A work-round through SMS that worked for me was to generate a create script and make the appropriate changes; rename the existing UDT; run the create script; recompile the related sprocs and drop the renamed version.

How to delete/remove nodes on Firebase

Firebase.remove() like probably most Firebase methods is asynchronous, thus you have to listen to events to know when something happened:

parent = ref.parent()
parent.on('child_removed', function (snapshot) {
    // removed!
})
ref.remove()

According to Firebase docs it should work even if you lose network connection. If you want to know when the change has been actually synchronized with Firebase servers, you can pass a callback function to Firebase.remove method:

ref.remove(function (error) {
    if (!error) {
        // removed!
    }
}

How do I fix PyDev "Undefined variable from import" errors?

I had the same problem. I am using Python and Eclipse on Windows. The code was running just fine, but eclipse show errors everywhere. After I changed the name of the folder 'Lib' to 'lib' (C:\Python27\lib), the problem was solved. It seems that if the capitalization of the letters doesn't match the one in the configuration file, this will sometimes cause problems (but it seems like not always, because the error checking was fine for long time before the problems suddenly appeared for no obvious reason).

GIT commit as different user without email / or only email

Run these two commands from the terminal to set User email and Name

 git config --global user.email "[email protected]" 

 git config --global user.name "your name" 

How to search in an array with preg_match?

You can use array_walk to apply your preg_match function to each element of the array.

http://us3.php.net/array_walk

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In may case, I nedded to copy the gacutil.exe, gacutil.exe.config AND ALSO the gacutlrc.dll (from the 1033 directory)

Socket.IO - how do I get a list of connected sockets/clients?

Here is a quick way to convert the hash of connected sockets from a namespace into an array using ES6 generators (applies to socket.io >= v1.0.0):

io.on('connection', function(socket) {
  var hash = io.of('/').connected
  var list = null

  hash[Symbol.iterator] = function*() {
    // for..of loop to invoke Object.keys() default iterator
    // to get the array values instead of the keys
    for(var id of Object.keys(hash)) yield hash[id]
  }

  list = [...hash]
  console.log(Array.isArray(list)) // true
})

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

If you get a

sudo: add-apt-repository: command not found

then you need to run the following command

sudo apt-get install software-properties-common python-software-properties

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

Add a border outside of a UIView (instead of inside)

Increase the width and height of view's frame with border width before adding the border:

float borderWidth = 2.0f
CGRect frame = self.frame;
frame.width += borderWidth;
frame.height += borderWidth;
 self.layer.borderColor = [UIColor yellowColor].CGColor;
 self.layer.borderWidth = 2.0f;

How do I schedule jobs in Jenkins?

Try this.

20 4 * * *

Check the below Screenshot

enter image description here

Referred URL - https://www.lenar.io/jenkins-schedule-build-periodically/

How to give a pattern for new line in grep?

try pcregrep instead of regular grep:

pcregrep -M "pattern1.*\n.*pattern2" filename

the -M option allows it to match across multiple lines, so you can search for newlines as \n.

try/catch with InputMismatchException creates infinite loop

YOu can also try the following

   do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.next());

            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.next());

            nQuotient = n1/n2;

            bError = false;
        } 
        catch (Exception e) {
            System.out.println("Error!");
            input.reset();
        }
    } while (bError);

Change remote repository credentials (authentication) on Intellij IDEA 14

Go to VCS>Git>Remotes then remove your remote url from the list and add again. Git will ask for a password after next git operation (push, pull, etc). NOTE: Don't forget to specify username in url or you will get auth error.

Open terminal here in Mac OS finder

This:

https://github.com/jbtule/cdto#cd-to

It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.

React.js: onChange event for contentEditable

Edit: See Sebastien Lorber's answer which fixes a bug in my implementation.


Use the onInput event, and optionally onBlur as a fallback. You might want to save the previous contents to prevent sending extra events.

I'd personally have this as my render function.

var handleChange = function(event){
    this.setState({html: event.target.value});
}.bind(this);

return (<ContentEditable html={this.state.html} onChange={handleChange} />);

jsbin

Which uses this simple wrapper around contentEditable.

var ContentEditable = React.createClass({
    render: function(){
        return <div 
            onInput={this.emitChange} 
            onBlur={this.emitChange}
            contentEditable
            dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
    },
    shouldComponentUpdate: function(nextProps){
        return nextProps.html !== this.getDOMNode().innerHTML;
    },
    emitChange: function(){
        var html = this.getDOMNode().innerHTML;
        if (this.props.onChange && html !== this.lastHtml) {

            this.props.onChange({
                target: {
                    value: html
                }
            });
        }
        this.lastHtml = html;
    }
});

How can I define fieldset border color?

It works for me when I define the complete border property. (JSFiddle here)

.field_set{
 border: 1px #F00 solid;
}?

the reason is the border-style that is set to none by default for fieldsets. You need to override that as well.

Where can I find Android's default icons?

You can find the default Android menu icons here - link is broken now.

Update: You can find Material Design icons here.

Compare two Lists for differences

I think you're looking for a method like this:

public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
    IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
    var enum1 = seq1.GetEnumerator();
    var enum2 = seq2.GetEnumerator();

    while (enum1.MoveNext() && enum2.MoveNext())
    {
        yield return comparer(enum1.Current, enum2.Current);
    }
}

It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.

This solution of course assumes that you want to compare the nth item of seq1 with the nth item in seq2. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.

Edit: Here's an example of how you might use the CompareSequences method with the comparer function you originally posted.

// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;    

foreach(var element in results)
{
    Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}

How do I find an array item with TypeScript? (a modern, easier way)

Playing with the tsconfig.json You can also targeting es5 like this :

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "module": "commonjs", 
        "target": "es5"
    }
    ...

What's a good IDE for Python on Mac OS X?

I like Spyder, it has many tools, such as profiling, intelligent indentation helper and a good autocompletion support

https://code.google.com/p/spyderlib/

Calling Java from Python

Pyjnius.

Docs: http://pyjnius.readthedocs.org/en/latest/

Github: https://github.com/kivy/pyjnius

From the github page:

A Python module to access Java classes as Python classes using JNI.

PyJNIus is a "Work In Progress".

Quick overview

>>> from jnius import autoclass
>>> autoclass('java.lang.System').out.println('Hello world') Hello world

>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> print stack.pop() world
>>> print stack.pop() hello

Index of element in NumPy array

You can use the function numpy.nonzero(), or the nonzero() method of an array

import numpy as np

A = np.array([[2,4],
          [6,2]])
index= np.nonzero(A>1)
       OR
(A>1).nonzero()

Output:

(array([0, 1]), array([1, 0]))

First array in output depicts the row index and second array depicts the corresponding column index.

Url.Action parameters?

Here is another simple way to do it

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>

Where is @Model.ID is a parameter

And here there is a second example.

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2&param3=ViewBag.P3'>Print</a>

You don't have permission to access / on this server

If you set SELinux in permissive mode (command setenforce 0) and it works (worked for me) then you can run restorecon (sudo restorecon -Rv /var/www/html/) which set the correct context to the files in Apache directory permanently because setenforce is temporal. The context for Apache is httpd_sys_content_t and you can verify it running the command ls -Z /var/www/html/ that outputs something like:

-rwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 index.html

In case the file does not have the right context, appear something like this:

drwxr-xr-x. root root unconfined_u:object_r:user_home_t:s0 tests

Hope it can help you.

PD: excuse me my English

How to open up a form from another form in VB.NET?

You could use:

Dim MyForm As New Form1
MyForm.Show()

or rather:

MyForm.ShowDialog()

to open the form as a dialog box to ensure that user interacts with the new form or closes it.

Watching variables in SSIS during debug

I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)

CSS background image to fit width, height should auto-scale in proportion

Background image is not Set Perfect then his css is problem create so his css file change to below code

_x000D_
_x000D_
html {  _x000D_
  background-image: url("example.png");  _x000D_
  background-repeat: no-repeat;  _x000D_
  background-position: 0% 0%;_x000D_
  background-size: 100% 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

%; background-size: 100% 100%;"

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

How to get PID of process I've just started within java program?

Using JNA, supporting old and new JVM to get process id

public static long getProcessId(Process p){
    long pid = -1;
    try {
      pid = p.pid();
    } catch (NoSuchMethodError e) {
        try
        {
            //for windows
            if (p.getClass().getName().equals("java.lang.Win32Process") || p.getClass().getName().equals("java.lang.ProcessImpl")) {
                Field f = p.getClass().getDeclaredField("handle");
                f.setAccessible(true);              
                long handl = f.getLong(p);
                Kernel32 kernel = Kernel32.INSTANCE;
                WinNT.HANDLE hand = new WinNT.HANDLE();
                hand.setPointer(Pointer.createConstant(handl));
                pid = kernel.GetProcessId(hand);
                f.setAccessible(false);
            }
            //for unix based operating systems
            else if (p.getClass().getName().equals("java.lang.UNIXProcess")) 
            {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                pid = f.getLong(p);
                f.setAccessible(false);
            }
        }
        catch(Exception ex)
        {
            pid = -1;
        }
    }        
    return pid;
}

H2 in-memory database. Table not found

I had the same problem and changed my configuration in application-test.properties to this:

#Test Properties
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop

And my dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.198</version>
        <scope>test</scope>
    </dependency>

And the annotations used on test class:

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
public class CommentServicesIntegrationTests {
...
}

What is the difference between background and background-color

One thing I've noticed that I don't see in the documentation is using background: url("image.png")

short hand like above if the image is not found it sends a 302 code instead of being ignored like it is if you use

background-image: url("image.png") 

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

just remove s from the permission you are using sss you have to use ss

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

open failed: EACCES (Permission denied)

First give or check permissions like

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

If these two permissions are OK, then check your output streams are in correct format.

Example:

FileOutputStream fos=new FileOutputStream(Environment.getExternalStorageDirectory()+"/rahul1.jpg");

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

An optional parameter is just tagged with an attribute. This attribute tells the compiler to insert the default value for that parameter at the call-site.

The call obj2.TestMethod(); is replaced by obj2.TestMethod(false); when the C# code gets compiled to IL, and not at JIT-time.

So in a way it's always the caller providing the default value with optional parameters. This also has consequences on binary versioning: If you change the default value but don't recompile the calling code it will continue to use the old default value.

On the other hand, this disconnect means you can't always use the concrete class and the interface interchangeably.

You already can't do that if the interface method was implemented explicitly.

What is the !! (not not) operator in JavaScript?

_x000D_
_x000D_
const foo = 'bar';
console.log(!!foo); // Boolean: true
_x000D_
_x000D_
_x000D_

! negates (inverts) a value AND always returns/ produces a boolean. So !'bar' would yield false (because 'bar' is truthy => negated + boolean = false). With the additional ! operator, the value is negated again, so false becomes true.

How can I add to a List's first position?

Of course, Insert or AddFirst will do the trick, but you could always do:

myList.Reverse();
myList.Add(item);
myList.Reverse();

Express-js wildcard routing to cover everything under and including a path

For those who are learning node/express (just like me): do not use wildcard routing if possible!

I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.

More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

Convert XML to JSON (and back) using Javascript

Here' a good tool from a documented and very famous npm library that does the xml <-> js conversions very well: differently from some (maybe all) of the above proposed solutions, it converts xml comments also.

var obj = {name: "Super", Surname: "Man", age: 23};

var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

How to test REST API using Chrome's extension "Advanced Rest Client"

Add authorization header and click pencil button to enter username and passwords

enter image description here

How do I use Spring Boot to serve static content located in Dropbox folder?

You can place your folder in the root of the ServletContext.

Then specify a relative or absolute path to this directory in application.yml:

spring:
  resources:
    static-locations: file:some_temp_files/

The resources in this folder will be available (for downloading, for example) at:

http://<host>:<port>/<context>/your_file.csv

How does String substring work in Swift

I'm quite mechanical thinking. Here are the basics...

Swift 4 Swift 5

  let t = "abracadabra"

  let start1 = t.index(t.startIndex, offsetBy:0)
  let   end1 = t.index(t.endIndex, offsetBy:-5)
  let start2 = t.index(t.endIndex, offsetBy:-5)
  let   end2 = t.index(t.endIndex, offsetBy:0)

  let t2 = t[start1 ..< end1]
  let t3 = t[start2 ..< end2]                

  //or a shorter form 

  let t4 = t[..<end1]
  let t5 = t[start2...]

  print("\(t2) \(t3) \(t)")
  print("\(t4) \(t5) \(t)")

  // result:
  // abraca dabra abracadabra

The result is a substring, meaning that it is a part of the original string. To get a full blown separate string just use e.g.

    String(t3)
    String(t4)

This is what I use:

    let mid = t.index(t.endIndex, offsetBy:-5)
    let firstHalf = t[..<mid]
    let secondHalf = t[mid...]

How to insert a timestamp in Oracle?

Inserting date in sql

insert
into tablename (timestamp_value)
values ('dd-mm-yyyy hh-mm-ss AM');

If suppose we wanted to insert system date

insert
into tablename (timestamp_value)
values (sysdate);

Move to next item using Java 8 foreach loop in stream

You can use a simple if statement instead of continue. So instead of the way you have your code, you can try:

try(Stream<String> lines = Files.lines(path, StandardCharsets.ISO_8859_1)){
            filteredLines = lines.filter(...).foreach(line -> {
           ...
           if(!...) {
              // Code you want to run
           }
           // Once the code runs, it will continue anyway
    });
}

The predicate in the if statement will just be the opposite of the predicate in your if(pred) continue; statement, so just use ! (logical not).

How to return PDF to browser in MVC?

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

if the filename is generating dynamically then how to define filename here, it is generating through guid here.

Python speed testing - Time Difference - milliseconds

start = datetime.now() 

#code for which response time need to be measured.

end = datetime.now()
dif = end - start
dif_micro = dif.microseconds # time in microseconds
dif_millis = dif.microseconds / 1000 # time in millisseconds

Accessing bash command line args $@ vs $*

This example let may highlight the differ between "at" and "asterix" while we using them. I declared two arrays "fruits" and "vegetables"

fruits=(apple pear plumm peach melon)            
vegetables=(carrot tomato cucumber potatoe onion)

printf "Fruits:\t%s\n" "${fruits[*]}"            
printf "Fruits:\t%s\n" "${fruits[@]}"            
echo + --------------------------------------------- +      
printf "Vegetables:\t%s\n" "${vegetables[*]}"    
printf "Vegetables:\t%s\n" "${vegetables[@]}"    

See the following result the code above:

Fruits: apple pear plumm peach melon
Fruits: apple
Fruits: pear
Fruits: plumm
Fruits: peach
Fruits: melon
+ --------------------------------------------- +
Vegetables: carrot tomato cucumber potatoe onion
Vegetables: carrot
Vegetables: tomato
Vegetables: cucumber
Vegetables: potatoe
Vegetables: onion

How to create cron job using PHP?

Added to Alister, you can edit the crontab usually (not always the case) by entering crontab -e in a ssh session on the server.

The stars represent (* means every of this unit):

[Minute] [Hour] [Day] [Month] [Day of week (0 =sunday to 6 =saturday)] [Command]

You could read some more about this here.