Programs & Examples On #Mcml

Random word generator- Python

Solution for Python 3

For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

import urllib.request

word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

Output:

>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
 'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
 'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]

And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

import random
upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])

And some random names:

>>> for n in range(10):
        ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])

    'Semiramis Sicilian'
    'Julius Genevieve'
    'Rwanda Cohn'
    'Quito Sutherland'
    'Eocene Wheller'
    'Olav Jove'
    'Weldon Pappas'
    'Vienna Leyden'
    'Io Dave'
    'Schwartz Stromberg'

How to use jQuery in AngularJS

The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.

angular.module('app')
.directive('my-slider', 
    ['$timeout', function($timeout) {
        return {
            restrict:'E',
            scope: true,
            template: '<div id="{{ id }}"></div>',
            link: function($scope) {
                $scope.id = String(Math.random()).substr(2, 8);

                $timeout(function() {
                    angular.element('#'+$scope.id).slider();                    
                });
            }
        };
    }]
);

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Encode URL in JavaScript?

The best answer is to use encodeURIComponent on values in the query string (and nowhere else).

However, I find that many APIs want to replace " " with "+" so I've had to use the following:

const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value

escape is implemented differently in different browsers and encodeURI doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.

And as @Jochem points out below, you may want to use encodeURIComponent() on a (each) folder name, but for whatever reason these APIs don't seem to want + in folder names so plain old encodeURIComponent works great.

Example:

const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;

How can I select item with class within a DIV?

Try:

$('#mydiv').find('.myclass');

JS Fiddle demo.

Or:

$('.myclass','#mydiv');

JS Fiddle demo.

Or:

$('#mydiv .myclass');

JS Fiddle demo.

References:


Good to learn from the find() documentation:

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

Equivalent of .bat in mac os

I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:

  • Make a bash (shell) script version of your .bat file (like other
    answers, with \ changed to / in file paths). For example:

    # File "example.command":
    #!/bin/bash
    java -cp  ".;./supportlibraries/Framework_Core.jar; ...etc.
    
  • Then rename it to have the Mac OS file extension .command.
    That should make the script run using the Terminal app.

  • If the app user is going to use a bash script version of the file on Linux
    or run it from the command line, they need to add executable rights
    (change mode bits) using this command, in the folder that has the file:

    chmod +rx [filename].sh
    #or:# chmod +rx [filename].command
    

The forum page question:

Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.

Info from some answers after the question:

Write a shell script, and give it the extension ".command". For example:

#!/bin/bash 
printf "Hello World\n" 

- Mar 23, 2010, Tony T1.

The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.

However, OS X adds the feature that if you give the file the suffix .command, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).

Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]

#!/bin/sh
echo Hello World

- Mar 23, 2010, J D McIninch.

Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:

On mac, there is a specific extension for executing shell
scripts by double clicking them: this is .command.

Getting all types that implement an interface

Even better when choosing the Assembly location. Filter most of the assemblies if you know all your implemented interfaces are within the same Assembly.DefinedTypes.

// We get the assembly through the base class
var baseAssembly = typeof(baseClass).GetTypeInfo().Assembly;

// we filter the defined classes according to the interfaces they implement
var typeList = baseAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IMyInterface))).ToList();

By Can Bilgin

jQuery click event not working in mobile browsers

With this solution, you probably can resolve all mobile clicks problems. Use only "click" function, but add z-index:99 to the element in css:

_x000D_
_x000D_
  $("#test").on('click', function(){_x000D_
    alert("CLICKED!")_x000D_
  });
_x000D_
#test{   _x000D_
  z-index:99;_x000D_
  cursor:pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
_x000D_
<div id="test">CLICK ME</div>
_x000D_
_x000D_
_x000D_

Credit:https://foundation.zurb.com/forum/posts/3258-buttons-not-clickable-on-iphone

How to handle login pop up window using Selenium WebDriver?

The easiest way to handle the Authentication Pop up is to enter the Credentials in Url Itself. For Example, I have Credentials like Username: admin and Password: admin:

WebDriver driver = new ChromeDriver();
driver.get("https://admin:admin@your website url");

Change location of log4j.properties

In Eclipse you can set a VM argument to:

-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}

Is there a way to check for both `null` and `undefined`?

For Typescript 2.x.x you should do it in a following way(using type guard):

tl;dr

function isDefined<T>(value: T | undefined | null): value is T {
  return <T>value !== undefined && <T>value !== null;
}

Why?

In this way isDefined() will respect variable's type and the following code would know take this check in account.

Example 1 - basic check:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: string| undefined) {   
  getFoo(bar); //ERROR: "bar" can be undefined
  if (isDefined(bar)) {
    getFoo(bar); // Ok now, typescript knows that "bar' is defined
  }
}

Example 2 - types respect:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: number | undefined) {
  getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
  if (isDefined(bar)) {
    getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
  }
}

How to get the process ID to kill a nohup process?

If you are unaware of the PID, then first find it using TOP command

top -U userid

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND

You will get the PID using top, then perform the kill operation.

$ kill -9 <PID>

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

java.security.AccessControlException: Access denied (java.io.FilePermission

Within your <jre location>\lib\security\java.policy try adding:

grant { permission java.security.AllPermission; };

And see if it allows you. If so, you will have to add more granular permissions.

See:

Java 8 Documentation for java.policy files

and

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

Reset identity seed after deleting records in SQL Server

DBCC CHECKIDENT ('TestTable', RESEED, 0)
GO

Where 0 is identity Start value

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Using CSS to insert text

It is, but requires a CSS2 capable browser (all major browsers, IE8+).

.OwnerJoe:before {
  content: "Joe's Task:";
}

But I would rather recommend using Javascript for this. With jQuery:

$('.OwnerJoe').each(function() {
  $(this).before($('<span>').text("Joe's Task: "));
});

CSS - Expand float child DIV height to parent's height

I found a lot of answers, but probably the best solution for me is

.parent { 
  overflow: hidden; 
}
.parent .floatLeft {
  # your other styles
  float: left;
  margin-bottom: -99999px;
  padding-bottom: 99999px;
}

You can check other solutions here http://css-tricks.com/fluid-width-equal-height-columns/

Convert string to int array using LINQ

You can shorten JSprangs solution a bit by using a method group instead:

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ints = s1.Split(';').Select(int.Parse).ToArray();

Using If else in SQL Select statement

Here is some example using CASE WHEN

SELECT 
    CASE WHEN A > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            A
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 and B > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE
            'less than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE CASE WHEN A >= 0 THEN
                      'greater than or equal 0'
                   ELSE
                      'less than 0'
              END        
    END  
FROM TRIANGLES;

Hope this helps

How to create Password Field in Model Django

See my code which may help you. models.py

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=100)
    instrument_purchase = models.CharField(max_length=100)
    house_no = models.CharField(max_length=100)
    address_line1 = models.CharField(max_length=100)
    address_line2 = models.CharField(max_length=100)
    telephone = models.CharField(max_length=100)
    zip_code = models.CharField(max_length=20)
    state = models.CharField(max_length=100)
    country = models.CharField(max_length=100)

    def __str__(self):
        return self.name

forms.py

from django import forms
from models import *

class CustomerForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = Customer
        fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')

Ansible: How to delete files and folders inside a directory?

There is an issue open with respect to this.

For now, the solution works for me: create a empty folder locally and synchronize it with the remote one.

Here is a sample playbook:

- name: "Empty directory"
  hosts: *
  tasks:
    - name: "Create an empty directory (locally)"
      local_action:
        module: file
        state: directory
        path: "/tmp/empty"

    - name: Empty remote directory
      synchronize:
        src: /tmp/empty/
        dest: /home/mydata/web/
        delete: yes
        recursive: yes

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

Launching a website via windows commandline

Using a CLI, the easiest way (cross-platform) I've found is to use the NPM package https://github.com/sindresorhus/open-cli

npm install --global open-cli

Installing it globally allows running something like open-cli https://unlyed.github.io/next-right-now/.

You can also install it locally (e.g: in a project) and run npx open-cli https://unlyed.github.io/next-right-now/

Or, using a NPM script (which is how I actually use it): "doc:online": "open-cli https://unlyed.github.io/next-right-now/",

Running yarn doc:online will open the webpage, and this works on any platform (windows, mac, linux).

How to parse an RSS feed using JavaScript?

For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.

Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:

Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.

My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.

POST Content-Length exceeds the limit

I suggest that you should change to post_max_size from 8M to 32M in the php.ini file.

java Arrays.sort 2d array

for decreasing order for integer array of 2 dimension you can use

Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order

Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]);//decreasing order

Retrieving a Foreign Key value with django-rest-framework serializers

Simple solution source='category.name' where category is foreign key and .name it's attribute.

from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item

class ItemSerializer(ModelSerializer):
    category_name = ReadOnlyField(source='category.name')

    class Meta:
        model = Item
        fields = "__all__"

if (boolean == false) vs. if (!boolean)

This is a style choice. It does not impact the performance of the code in the least, it just makes it more verbose for the reader.

onclick="javascript:history.go(-1)" not working in Chrome

Try this:

<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

@try - catch block in Objective-C

Now I've found the problem.

Removing the obj_exception_throw from my breakpoints solved this. Now it's caught by the @try block and also, NSSetUncaughtExceptionHandler will handle this if a @try block is missing.

How to dynamically create CSS class in JavaScript and apply?

Although I'm not sure why you want to create CSS classes with JavaScript, here is an option:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

Remove Item from ArrayList

As mentioned before

iterator.remove()

is maybe the only safe way to remove list items during the loop.

For deeper understanding of items removal using the iterator, try to look at this thread

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Lightweight Javascript DB for use in Node.js

Lokijs: A fast, in-memory document-oriented datastore for node.js, browser and cordova.

  • In-memory Javascript Datastore wih Persistence
  • In-Browser NoSQL db with syncing and persisting
  • a Redis-style store an npm install away
  • Persistable NoSQL db for Cordova
  • Embeddable NoSQL db with Persistence for node-webkit

LokiJS to be the ideal solution:

  • Mobile applications - especially HTML5 based (Cordova, Phonegap, etc.)
  • Node.js embedded datastore for small-to-medium apps
  • Embedded in desktop application with Node Webkit

https://github.com/techfort/LokiJS

Add new item in existing array in c#.net

I agree with Ed. C# does not make this easy the way VB does with ReDim Preserve. Without a collection, you'll have to copy the array into a larger one.

Importing Excel files into R, xlsx or xls

You may be able to keep multiple tabs and more formatting information if you export to an OpenDocument Spreadsheet file (ods) or an older Excel format and import it with the ODS reader or the Excel reader you mentioned above.

Effects of the extern keyword on C functions

The reason it has no effect is because at the link-time the linker tries to resolve the extern definition (in your case extern int f()). It doesn't matter if it finds it in the same file or a different file, as long as it is found.

Hope this answers your question.

Function return value in PowerShell

With PowerShell 5 we now have the ability to create classes. Change your function into a class, and return will only return the object immediately preceding it. Here is a real simple example.

class test_class {
    [int]return_what() {
        Write-Output "Hello, World!"
        return 808979
    }
}
$tc = New-Object -TypeName test_class
$tc.return_what()

If this was a function the expected output would be

Hello World
808979

but as a class the only thing returned is the integer 808979. A class is sort of like a guarantee that it will only return the type declared or void.

What are these ^M's that keep showing up in my files in emacs?

instead of query-replace you may also use M-x delete-trailing-whitespace

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

How to update and delete a cookie?

http://www.quirksmode.org/js/cookies.html

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

Best practices for styling HTML emails

I find that image mapping works pretty well. If you have any headers or footers that are images make sure that you apply a bgcolor="fill in the blank" because outlook in most cases wont load the image and you will be left with a transparent header. If you at least designate a color that works with the over all feel of the email it will be less of a shock for the user. Never try and use any styling sheets. Or CSS at all! Just avoid it.

Depending if you're copying content from a word or shared google Doc be sure to (command+F) Find all the (') and (") and replace them within your editing software (especially dreemweaver) because they will show up as code and it's just not good.

ALT is your best friend. use the ALT tag to add in text to all your images. Because odds are they are not going to load right. And that ALT text is what gets people to click the (see images) button. Also define your images Width, Height and make the boarder 0 so you dont get weird lines around your image.

Consider editing all images within Photoshop with a 15px boarder on each side (make background transparent and save as a PNG 24) of image. Sometimes the email clients do not read any padding styles that you apply to the images so it avoids any weird formatting!

Also i found the line under links particularly annoying so if you apply < style="text-decoration:none; color:#whatever color you want here!" > it will remove the line and give you the desired look.

There is alot that can really mess with the over all look and feel.

How to enable assembly bind failure logging (Fusion) in .NET

Just a tiny bit of info that might help others; if you do something along the lines of searching all assemblies in some directory for classes that inherit/implement classes/interfaces, then make sure you clean out stale assemblies if you get this error pertaining to one of your own assemblies.

The scenario would be something like:

  1. Assembly A loads all assemblies in some folder
  2. Assembly B in this folder is stale, but references assembly C
  3. Assembly C exists, but namespaces, class names or some other detail might have changed in the time that has passed since assembly B became stale (in my case a namespace was changed through a refactoring process)

In short: A ---loads--> B (stale) ---references---> C

If this happens, the only telltale sign is the namespace and classname in the error message. Examine it closely. If you can't find it anywhere in your solution, you are likely trying to load a stale assembly.

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

Set drawable size programmatically

You can try button.requestLayout(). When the background size is changed, it needs to remeasure and layout, but it won't do it

How to send HTML-formatted email?

This works for me

msg.BodyFormat = MailFormat.Html;

and then you can use html in your body

msg.Body = "<em>It's great to use HTML in mail!!</em>"

Best way to convert string to bytes in Python 3?

The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode defaults to 'utf-8' ever since Python 3.0. Thus the best way is

b = mystring.encode()

This will also be faster, because the default argument results not in the string "utf-8" in the C code, but NULL, which is much faster to check!

Here be some timings:

In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop

In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop

Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.


Using encode() without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.

>>> 'äöä'.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Javascript communication between browser tabs/windows

You can communicate between windows (tabbed or not) if they have a child-parent relationship.

Create and update a child window:

<html>
<head>
<title>Cross window test script</title>
<script>
var i = 0;
function open_and_run() {
    var w2 = window.open("", "winCounter"); 
    var myVar=setInterval(function(){myTimer(w2)},1000);
}

function myTimer(w2) {
    i++;
    w2.document.body.innerHTML="<center><h1>" + i + "</h1><p></center>";
}
</script>
</head>
<body>
Click to open a new window 
<button onclick="open_and_run();">Test This!</button>    
</body>
</html>

Child windows can use the parent object to communicate with the parent that spawned it, so you could control the music player from either window.

See it in action here: https://jsbin.com/cokipotajo/edit?html,js,output

Does SVG support embedding of bitmap images?

Yes, you can reference any image from the image element. And you can use data URIs to make the SVG self-contained. An example:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

    ...
    <image
        width="100" height="100"
        xlink:href="data:image/png;base64,IMAGE_DATA"
        />
    ...
</svg>

The svg element attribute xmlns:xlink declares xlink as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href means.

The IMAGE_DATA is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.

Here's a full example from the SVG testsuite.

How to write palindrome in JavaScript

Taking a stab at this. Kind of hard to measure performance, though.

function palin(word) {
    var i = 0,
        len = word.length - 1,
        max = word.length / 2 | 0;

    while (i < max) {
        if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
            return false;
        }
        i += 1;
    }
    return true;
}

My thinking is to use charCodeAt() instead charAt() with the hope that allocating a Number instead of a String will have better perf because Strings are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'), the middle character is always ok.

How does Python return multiple values from a function?

Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name evaluates to a tuple and that tuple is the actual value the function is returning.

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

This happened to me when:

  • Even with my servlet having only the method "doPost"
  • And the form method="POST"

  • I tried to access the action using the URL directly, without using the form submitt. Since the default method for the URL is the doGet method, when you don't use the form submit, you'll see @ your console the http 405 error.

Solution: Use only the form button you mapped to your servlet action.

'any' vs 'Object'

Adding to Alex's answer and simplifying it:

Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.

How to use an environment variable inside a quoted string in Bash

Note that COLUMNS is:

  1. NOT an environment variable. It is an ordinary bash parameter that is set by bash itself.
  2. Set automatically upon receipt of a SIGWINCH signal.

That second point usually means that your COLUMNS variable will only be set in your interactive shell, not in a bash script.

If your script's stdin is connected to your terminal you can manually look up the width of your terminal by asking your terminal:

tput cols

And to use this in your SVN command:

svn diff "$@" --diff-cmd /usr/bin/diff -x "-y -w -p -W $(tput cols)"

(Note: you should quote "$@" and stay away from eval ;-))

Update records in table from CTE

Try the following query:

;WITH CTE_DocTotal
 AS
 (
   SELECT SUM(Sale + VAT) AS DocTotal_1
   FROM PEDI_InvoiceDetail
   GROUP BY InvoiceNumber
 )

UPDATE CTE_DocTotal
SET DocTotal = CTE_DocTotal.DocTotal_1

how to configuring a xampp web server for different root directory

You can change the port while you open your XAMP control panel, follow the steps:

  1. click on config net to the start button, and
  2. select httpd.conf, a text file will open
  3. check the file and file listen:80,
  4. once got listen:80 replace with listen:8080 and
  5. save in the same folder.

Once done that, you will be able to start your local server.

php static function

In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.

DateTime.TryParseExact() rejecting valid formats

string DemoLimit = "02/28/2018";
 string pattern = "MM/dd/yyyy";
 CultureInfo enUS = new CultureInfo("en-US"); 
 DateTime.TryParseExact(DemoLimit, pattern, enUS, 
                     DateTimeStyles.AdjustToUniversal, out datelimit);

For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

With block equivalent in C#?

For me I was trying to auto generate code, and needed to reuse a simple variable like "x" for multiple different classes so that I didn't have to keep generating new variable names. I found that I could limit the scope of a variable and reuse it multiple times if I just put the code in a curly brace section {}.

See the example:

public class Main
{
    public void Execute()
    {
        // Execute new Foos and new Bars many times with same variable.
        double a = 0;
        double b = 0;
        double c = 0;
        double d = 0;
        double e = 0;
        double f = 0;

        double length = 0;
        double area = 0;
        double size = 0;

        {
            Foo x = new Foo(5, 6).Execute();
            a = x.A;
            b = x.B;
            c = x.C;
            d = x.D;
            e = x.E;
            f = x.F;
        }
        {
            Bar x = new Bar("red", "circle").Execute();
            length = x.Length;
            area = x.Area;
            size = x.Size;
        }
        {
            Foo x = new Foo(3, 10).Execute();
            a = x.A;
            b = x.B;
            c = x.C;
            d = x.D;
            e = x.E;
            f = x.F;
        }
        {
            Bar x = new Bar("blue", "square").Execute();
            length = x.Length;
            area = x.Area;
            size = x.Size;
        }
    }
}

public class Foo
{
    public int X { get; set; }
    public int Y { get; set; }
    public double A { get; private set; }
    public double B { get; private set; }
    public double C { get; private set; }
    public double D { get; private set; }
    public double E { get; private set; }
    public double F { get; private set; }

    public Foo(int x, int y)
    {
        X = x;
        Y = y;
    }

    public Foo Execute()
    {
        A = X * Y;
        B = X + Y;
        C = X / (X + Y + 1);
        D = Y / (X + Y + 1);
        E = (X + Y) / (X + Y + 1);
        F = (Y - X) / (X + Y + 1);
        return this;
    }
}

public class Bar
{
    public string Color { get; set; }
    public string Shape { get; set; }
    public double Size { get; private set; }
    public double Area { get; private set; }
    public double Length { get; private set; }
    
    public Bar(string color, string shape)
    {
        Color = color;
        Shape = shape;
    }

    public Bar Execute()
    {
        Length = Color.Length + Shape.Length;
        Area = Color.Length * Shape.Length;
        Size = Area * Length;
        return this;
    }
}

In VB I would have used the With and not needed variable "x" at all. Excluding the vb class definitions of Foo and Bar, the vb code is:

Public Class Main
    Public Sub Execute()
        Dim a As Double = 0
        Dim b As Double = 0
        Dim c As Double = 0
        Dim d As Double = 0
        Dim e As Double = 0
        Dim f As Double = 0
        Dim length As Double = 0
        Dim area As Double = 0
        Dim size As Double = 0

        With New Foo(5, 6).Execute()
            a = .A
            b = .B
            c = .C
            d = .D
            e = .E
            f = .F
        End With

        With New Bar("red", "circle").Execute()
            length = .Length
            area = .Area
            size = .Size
        End With

        With New Foo(3, 10).Execute()
            a = .A
            b = .B
            c = .C
            d = .D
            e = .E
            f = .F
        End With

        With New Bar("blue", "square").Execute()
            length = .Length
            area = .Area
            size = .Size
        End With
    End Sub
End Class

When is null or undefined used in JavaScript?

Regarding this topic the specification (ecma-262) is quite clear

I found it really useful and straightforward, so that I share it: - Here you will find Equality algorithm - Here you will find Strict equality algorithm

I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.

I hope you find it useful.

How to change the icon of .bat file programmatically?

One of the way you can achieve this is:

  1. Create an executable Jar file
  2. Create a batch file to run the above jar and launch the desktop java application.
  3. Use Batch2Exe converter and covert to batch file to Exe.
  4. During above conversion, you can change the icon to that of your choice.(must of valid .ico file)
  5. Place the short cut for the above exe on desktop.

Now your java program can be opened in a fancy way just like any other MSWindows apps.! :)

Why do I have to "git push --set-upstream origin <branch>"?

My understanding is that "-u" or "--set-upstream" allows you to specify the upstream (remote) repository for the branch you're on, so that next time you run "git push", you don't even have to specify the remote repository.

Push and set upstream (remote) repository as origin:

$ git push -u origin

Next time you push, you don't have to specify the remote repository:

$ git push

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

Hide/Show components in react native

The only way to show or hide a component in react native is checking a value of a parameter of app state like state or props. I provided a complete example as below:

import React, {Component} from 'react';
import {View,Text,TextInput,TouchableHighlight} from 'react-native'

class App extends Component {

    constructor(props){
        super(props);
        this.state={
            show:false
        }
}

    showCancel=()=>{
        this.setState({show:true})
    };

    hideCancel=()=>{
        this.setState({show:false})
    };

    renderTouchableHighlight(){
        if(this.state.show){
           return(
               <TouchableHighlight
                   style={{borderColor:'black',borderWidth:1,marginTop:20}}
                   onPress={this.hideCancel}>
                   <View>
                       <Text>Cancel</Text>
                   </View>
               </TouchableHighlight>
           )
        }
        return null;
    }

    render() {


        return (
            <View style={{justifyContent:'center',alignItems:'center',flex:1}}>
                <TextInput
                    style={{borderColor:'black',borderBottomWidth:1}}
                    onFocus={this.showCancel}
                />
                {this.renderTouchableHighlight()}

            </View>
        );
    }
}

export default App;

Here is the result

raw vs. html_safe vs. h to unescape html

In Simple Rails terms:

h remove html tags into number characters so that rendering won't break your html

html_safe sets a boolean in string so that the string is considered as html save

raw It converts to html_safe to string

How to determine the first and last iteration in a foreach loop?

Simply this works!

// Set the array pointer to the last key
end($array);
// Store the last key
$lastkey = key($array);  
foreach($array as $key => $element) {
    ....do array stuff
    if ($lastkey === key($array))
        echo 'THE LAST ELEMENT! '.$array[$lastkey];
}

Thank you @billynoah for your sorting out the end issue.

How to secure phpMyAdmin

One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.

I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29

AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')

Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.

grant select on db_name.some_table to 'pma-user'@'app-server'

How to check if a variable is null or empty string or all whitespace in JavaScript?

You can try this:

do {
   var op = prompt("please input operatot \n you most select one of * - / *  ")
} while (typeof op == "object" || op == ""); 
// execute block of code when click on cancle or ok whthout input

Difference between @Mock and @InjectMocks

One advantage you get with the approach mentioned by @Tom is that you don't have to create any constructors in the SomeManager, and hence limiting the clients to instantiate it.

@RunWith(MockitoJUnitRunner.class)
public class SomeManagerTest {

    @InjectMocks
    private SomeManager someManager;

    @Mock
    private SomeDependency someDependency; // this will be injected into someManager

    //You don't need to instantiate the SomeManager with default contructor at all
   //SomeManager someManager = new SomeManager();    
   //Or SomeManager someManager = new SomeManager(someDependency);

     //tests...

}

Whether its a good practice or not depends on your application design.

How to set tint for an image view programmatically in android?

In case you want to set selector to your tint:

ImageViewCompat.setImageTintList(iv, getResources().getColorStateList(R.color.app_icon_click_color));

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

HTTP Status 504

CheckUpDown has a nice explanation of the 504 error:

A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.

This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.

This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.

How do I call a dynamically-named method in Javascript?

Try with this:

var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);

Rounding Bigdecimal values with 2 Decimal Places

I think that the RoundingMode you are looking for is ROUND_HALF_EVEN. From the javadoc:

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.

Here is a quick test case:

BigDecimal a = new BigDecimal("10.12345");
BigDecimal b = new BigDecimal("10.12556");

a = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
b = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);

System.out.println(a);
System.out.println(b);

Correctly prints:

10.12
10.13

UPDATE:

setScale(int, int) has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use setScale(int, RoundingMode) e.g:

setScale(2, RoundingMode.HALF_EVEN)

What is the difference between call and apply?

Fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

How to test android apps in a real device with Android Studio?

If USB Debugging Mode is enabled and does not work, you should install your device driver.

For Nexus Devices;

  • Install Google USB Drivers on SDK Tools.
  • Go to Control Panel > Device Manager and check drivers status. (Probably you can see warning icon on ADB Interface Driver.) Select ADB Interface driver and click update. Choose "Browse my computer for driver software" and set folder path like "D:\Users\userName\AppData\Local\Android\sdk".

For Another Devices;

  • If you install the model's driver, it may work. For ex: Samsung Kies, LG PC Suite.

Hope it helps!

Apache Proxy: No protocol handler was valid

In my case, I needed proxy_ajp module.

a2enmod proxy proxy_http proxy_ajp 

How do I correctly use "Not Equal" in MS Access?

Like this

SELECT DISTINCT Table1.Column1
FROM Table1
WHERE NOT EXISTS( SELECT * FROM Table2
    WHERE Table1.Column1 = Table2.Column1  )

You want NOT EXISTS, not "Not Equal"


By the way, you rarely want to write a FROM clause like this:

FROM Table1, Table2

as this means "FROM all combinations of every row in Table1 with every row in Table2..." Usually that's a lot more result rows than you ever want to see. And in the rare case that you really do want to do that, the more accepted syntax is:

FROM Table1 CROSS JOIN Table2

Exporting functions from a DLL with dllexport

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

#ifdef LIBRARY_EXPORTS
#    define LIBRARY_API __declspec(dllexport)
#else
#    define LIBRARY_API __declspec(dllimport)
#endif

Then on a function that you want to be exported you use LIBRARY_API:

LIBRARY_API int GetCoolInteger();

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

#ifdef _WIN32
#    ifdef LIBRARY_EXPORTS
#        define LIBRARY_API __declspec(dllexport)
#    else
#        define LIBRARY_API __declspec(dllimport)
#    endif
#elif
#    define LIBRARY_API
#endif

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C" inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:

The Code:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int getEngineVersion() {
  return 1;
}

EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
  K.getGraphicsServer().addGraphicsDriver(
    auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
  );
}

And here's what the exports look like with Dumpbin /exports:

  Dump of file opengl_plugin.dll

  File Type: DLL

  Section contains the following exports for opengl_plugin.dll

    00000000 characteristics
    49866068 time date stamp Sun Feb 01 19:54:32 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
          2    1 00011028 registerPlugin = @ILT+35(_registerPlugin)

So this code works fine:

m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");

m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
  ::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
  ::GetProcAddress(m_hDLL, "registerPlugin")
);

Disable Logback in SpringBoot

The reason is, spring boot comes with logback as its default log configuration whereas camel uses log4j. Thats the reason of conflict. You have two options, either remove logback from spring boot as mentioned in above answers or remove log4j from camel.

<dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring-boot-starter</artifactId>
            <version>${camel.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

What's the difference between :: (double colon) and -> (arrow) in PHP?

Yes, I just hit my first 'PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM'. My bad, I had a $instance::method() that should have been $instance->method(). Silly me.

The odd thing is that this still works just fine on my local machine (running PHP 5.3.8) - nothing, not even a warning with error_reporting = E_ALL - but not at all on the test server, there it just explodes with a syntax error and a white screen in the browser. Since PHP logging was turned off at the test machine, and the hosting company was too busy to turn it on, it was not too obvious.

So, word of warning: apparently, some PHP installations will let you use a $instance::method(), while others don't.

If anybody can expand on why that is, please do.

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

C++ where to initialize static const

Only integral values (e.g., static const int ARRAYSIZE) are initialized in header file because they are usually used in class header to define something such as the size of an array. Non-integral values are initialized in implementation file.

Combating AngularJS executing controller twice

Would like to add for reference:

Double controller code execution can also be caused by referencing the controller in a directive that also runs on the page.

e.g.

return {

            restrict: 'A',
            controller: 'myController',
            link: function ($scope) { ....

When you also have ng-controller="myController" in your HTML

Casting objects in Java

Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()

The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.

So:

Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ? This is called casting

Convert integer to hexadecimal and back again

NET FRAMEWORK

Very well explained and few programming lines GOOD JOB

// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

PASCAL >> C#

http://files.hddguru.com/download/Software/Seagate/St_mem.pas

Something from the old school very old procedure of pascal converted to C #

    /// <summary>
    /// Conver number from Decadic to Hexadecimal
    /// </summary>
    /// <param name="w"></param>
    /// <returns></returns>
    public string MakeHex(int w)
    {
        try
        {
           char[] b =  {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
           char[] S = new char[7];

              S[0] = b[(w >> 24) & 15];
              S[1] = b[(w >> 20) & 15];
              S[2] = b[(w >> 16) & 15];
              S[3] = b[(w >> 12) & 15];
              S[4] = b[(w >> 8) & 15];
              S[5] = b[(w >> 4) & 15];
              S[6] = b[w & 15];

              string _MakeHex = new string(S, 0, S.Count());

              return _MakeHex;
        }
        catch (Exception ex)
        {

            throw;
        }
    }

What is the http-header "X-XSS-Protection"?

This response header can be used to configure a user-agent's built in reflective XSS protection. Currently, only Microsoft's Internet Explorer, Google Chrome and Safari (WebKit) support this header.

Internet Explorer 8 included a new feature to help prevent reflected cross-site scripting attacks, known as the XSS Filter. This filter runs by default in the Internet, Trusted, and Restricted security zones. Local Intranet zone pages may opt-in to the protection using the same header.

About the header that you posted in your question,

The header X-XSS-Protection: 1; mode=block enables the XSS Filter. Rather than sanitize the page, when a XSS attack is detected, the browser will prevent rendering of the page.

In March of 2010, we added to IE8 support for a new token in the X-XSS-Protection header, mode=block.

X-XSS-Protection: 1; mode=block

When this token is present, if a potential XSS Reflection attack is detected, Internet Explorer will prevent rendering of the page. Instead of attempting to sanitize the page to surgically remove the XSS attack, IE will render only “#”.

Internet Explorer recognizes a possible cross-site scripting attack. It logs the event and displays an appropriate message to the user. The MSDN article describes how this header works.

How this filter works in IE,

More on this article, https://blogs.msdn.microsoft.com/ie/2008/07/02/ie8-security-part-iv-the-xss-filter/

The XSS Filter operates as an IE8 component with visibility into all requests / responses flowing through the browser. When the filter discovers likely XSS in a cross-site request, it identifies and neuters the attack if it is replayed in the server’s response. Users are not presented with questions they are unable to answer – IE simply blocks the malicious script from executing.

With the new XSS Filter, IE8 Beta 2 users encountering a Type-1 XSS attack will see a notification like the following:

IE8 XSS Attack Notification

The page has been modified and the XSS attack is blocked.

In this case, the XSS Filter has identified a cross-site scripting attack in the URL. It has neutered this attack as the identified script was replayed back into the response page. In this way, the filter is effective without modifying an initial request to the server or blocking an entire response.

The Cross-Site Scripting Filter event is logged when Windows Internet Explorer 8 detects and mitigates a cross-site scripting (XSS) attack. Cross-site scripting attacks occur when one website, generally malicious, injects (adds) JavaScript code into otherwise legitimate requests to another website. The original request is generally innocent, such as a link to another page or a Common Gateway Interface (CGI) script providing a common service (such as a guestbook). The injected script generally attempts to access privileged information or services that the second website does not intend to allow. The response or the request generally reflects results back to the malicious website. The XSS Filter, a feature new to Internet Explorer 8, detects JavaScript in URL and HTTP POST requests. If JavaScript is detected, the XSS Filter searches evidence of reflection, information that would be returned to the attacking website if the attacking request were submitted unchanged. If reflection is detected, the XSS Filter sanitizes the original request so that the additional JavaScript cannot be executed. The XSS Filter then logs that action as a Cross-Site Script Filter event. The following image shows an example of a site that is modified to prevent a cross-site scripting attack.

Source: https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx

Web developers may wish to disable the filter for their content. They can do so by setting an HTTP header:

X-XSS-Protection: 0

More on security headers in,

How to display an IFRAME inside a jQuery UI dialog

The problems were:

  1. iframe content comes from another domain
  2. iframe dimensions need to be adjusted for each video

The solution based on omerkirk's answer involves:

  • Creating an iframe element
  • Creating a dialog with autoOpen: false, width: "auto", height: "auto"
  • Specifying iframe source, width and height before opening the dialog

Here is a rough outline of code:

HTML

<div class="thumb">
    <a href="http://jsfiddle.net/yBNVr/show/"   data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
    <a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>

jQuery

$(function () {
    var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
    var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        width: "auto",
        height: "auto",
        close: function () {
            iframe.attr("src", "");
        }
    });
    $(".thumb a").on("click", function (e) {
        e.preventDefault();
        var src = $(this).attr("href");
        var title = $(this).attr("data-title");
        var width = $(this).attr("data-width");
        var height = $(this).attr("data-height");
        iframe.attr({
            width: +width,
            height: +height,
            src: src
        });
        dialog.dialog("option", "title", title).dialog("open");
    });
});

Demo here and code here. And another example along similar lines

Disable button after click in JQuery

You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true);

I have made a simple example http://jsfiddle.net/4gnXL/2/

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

React-Native: Application has not been registered error

This solved it for me

AppRegistry.registerComponent('main', () => App);

So my index.js file

import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('main', () => App);

And my package.json file:

"dependencies": {
    "react": "^16.13.1",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.5"
},

Select first and last row from grouped data

using which.min and which.max :

library(dplyr, warn.conflicts = F)
df %>% 
  group_by(id) %>% 
  slice(c(which.min(stopSequence), which.max(stopSequence)))

#> # A tibble: 6 x 3
#> # Groups:   id [3]
#>      id stopId stopSequence
#>   <dbl> <fct>         <dbl>
#> 1     1 a                 1
#> 2     1 c                 3
#> 3     2 b                 1
#> 4     2 c                 4
#> 5     3 b                 1
#> 6     3 a                 3

benchmark

It is also much faster than the current accepted answer because we find the min and max value by group, instead of sorting the whole stopSequence column.

# create a 100k times longer data frame
df2 <- bind_rows(replicate(1e5, df, F)) 
bench::mark(
  mm =df2 %>% 
    group_by(id) %>% 
    slice(c(which.min(stopSequence), which.max(stopSequence))),
  jeremy = df2 %>%
    group_by(id) %>%
    arrange(stopSequence) %>%
    filter(row_number()==1 | row_number()==n()))
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 mm           22.6ms     27ms     34.9     14.2MB     21.3
#> 2 jeremy      254.3ms    273ms      3.66    58.4MB     11.0

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Packing and byte alignment, as described in the C FAQ here:

It's for alignment. Many processors can't access 2- and 4-byte quantities (e.g. ints and long ints) if they're crammed in every-which-way.

Suppose you have this structure:

struct {
    char a[3];
    short int b;
    long int c;
    char d[3];
};

Now, you might think that it ought to be possible to pack this structure into memory like this:

+-------+-------+-------+-------+
|           a           |   b   |
+-------+-------+-------+-------+
|   b   |           c           |
+-------+-------+-------+-------+
|   c   |           d           |
+-------+-------+-------+-------+

But it's much, much easier on the processor if the compiler arranges it like this:

+-------+-------+-------+
|           a           |
+-------+-------+-------+
|       b       |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           |
+-------+-------+-------+

In the packed version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will pad the structure (as if with extra, invisible fields) like this:

+-------+-------+-------+-------+
|           a           | pad1  |
+-------+-------+-------+-------+
|       b       |     pad2      |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           | pad3  |
+-------+-------+-------+-------+

Converting Date and Time To Unix Timestamp

Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...

let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);

to prove it:

let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);

enjoy!

MVC Razor Radio Button

This works for me.

@{ var dic = new Dictionary<string, string>() { { "checked", "" } }; }
@Html.RadioButtonFor(_ => _.BoolProperty, true, (@Model.BoolProperty)? dic: null) Yes
@Html.RadioButtonFor(_ => _.BoolProperty, false, ([email protected])? dic: null) No

How to deal with the URISyntaxException

You need to encode the URI to replace illegal characters with legal encoded characters. If you first make a URL (so you don't have to do the parsing yourself) and then make a URI using the five-argument constructor, then the constructor will do the encoding for you.

import java.net.*;

public class Test {
  public static void main(String[] args) {
    String myURL = "http://finance.yahoo.com/q/h?s=^IXIC";
    try {
      URL url = new URL(myURL);
      String nullFragment = null;
      URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
      System.out.println("URI " + uri.toString() + " is OK");
    } catch (MalformedURLException e) {
      System.out.println("URL " + myURL + " is a malformed URL");
    } catch (URISyntaxException e) {
      System.out.println("URI " + myURL + " is a malformed URL");
    }
  }
}

How do I get hour and minutes from NSDate?

If you were to use the C library then this could be done:

time_t t;
struct tm * timeinfo;

time (&t);
timeinfo = localtime (&t);

NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);

And using Swift:

var t = time_t()
time(&t)
let x = localtime(&t)

println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")

For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/

What is the difference between an annotated and unannotated tag?

TL;DR

The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.

More About Lightweight Tags

According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:

  • When you use git tag <tagname>, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).
  • When you use git tag -a <tagname>, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.
  • When you use git tag -a -m <msg> <tagname>, Git will tag the commit and annotate it with the provided message.
  • When you use git tag -m <msg> <tagname>, Git will behave as if you passed the -a flag for annotation and use the provided message.

Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.

How to align a <div> to the middle (horizontally/width) of the page

Simple http://jsfiddle.net/8pd4qx5r/

html {
  display: table;
  height: 100%;
  width: 100%;
}

body {
  display: table-cell;
  vertical-align: middle;
}

.content {
  margin: 0 auto;
  width: 260px;
  text-align: center;
  background: pink;
}

Does Index of Array Exist

You can rather use a List, so you can check the existence.

List<int> l = new List<int>();
l.Add(45);
...
...

if (l.Count == 25) {
  doStuff();
}
int num = 45;
if (l.Contains(num)) {
  doMoreStuff();
}

SharePoint : How can I programmatically add items to a custom list instance

I think these both blog post should help you solving your problem.

http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/

Short walk through:

  1. Get a instance of the list you want to add the item to.
  2. Add a new item to the list:

    SPListItem newItem = list.AddItem();
    
  3. To bind you new item to a content type you have to set the content type id for the new item:

    newItem["ContentTypeId"] = <Id of the content type>;
    
  4. Set the fields specified within your content type.

  5. Commit your changes:

    newItem.Update();
    

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Mockito. Verify method arguments

argThat plus lambda

that is how you can fail your argument verification:

    verify(mock).mymethod(argThat(
      (x)->false
    ));

where

import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;

argThat plus asserts

the above test will "say" Expected: lambda$... Was: YourClass.toSting.... You can get a more specific cause of the failure if to use asserts in the the lambda:

    verify(mock).mymethod(argThat( x -> {
      assertThat(x).isNotNull();
      assertThat(x.description).contains("KEY");
      return true;
    }));

??BUT??: THIS ONLY WORKS WHEN

  • THE CALL IS EXPECTED 1 TIME, or
  • the call is expected 2+ times, but all the times the verifier matches (returns true).

If the verified method called 2+ times, mockito passes all the called combinations to each verifier. So mockito expects your verifier silently returns true for one of the argument set, and false (no assert exceptions) for other valid calls. That expectation is not a problem for 1 method call - it should just return true 1 time.

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;

Now the failed test will say: Expected: Obj.description to contain 'KEY'. Was: 'Actual description'. NOTE: I used assertJ asserts, but it's up to you which assertion framework to use.


argThat with multiple arguments.

If you use argThat, all arguments must be provided with matches. E.g.:

    verify(mock).mymethod(eq("VALUE_1"), argThat((x)->false));
    // above is correct as eq() is also an argument matcher.

verify(mock).mymethod("VALUE_1", argThat((x)->false));

// above is incorrect; an exceptoin will be thrown, as the fist arg. is given without an argument matcher.

where:

import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;

eq matcher

the easiest way to check if the argument is equal:

verify(mock).mymethod(eq(expectedValue));
// NOTE:   ^ where the parentheses must be closed.

direct argument

if comparison by ref is acceptable, then go on with:

verify(mock).mymethod(expectedArg);
// NOTE:   ^ where the parentheses must be closed.

THE ROOT CAUSE of original question failure was the wrong place of the paranthes: verify(mock.mymethod.... That was wrong. The right would be: verify(mock).*

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

Mailx send html message

Well, the "-a" mail and mailx in Centos7 is "attach file" not "append header." My shortest path to a solution on Centos7 from here: stackexchange.com

Basically:

yum install mutt
mutt -e 'set content_type=text/html' -s 'My subject' [email protected] < msg.html

Find stored procedure by name

For SQL Server version 9.0 (2005), you can use the code below:

select * 
from 
syscomments c
inner join sys.procedures p on p.object_id = c.id
where 
p.name like '%usp_ConnectionsCount%';

Where are my postgres *.conf files?

I like this thread because it documents the default locations for various postgresql.conf files on various architectures...

However, I've also gotten in trouble by relying on those defaults on installations where they have specified alternate locations. One way to find out where a particular config file is by querying the database directly:

select * from pg_settings where name='config_file'

Drop the where clause to see all the settings, which can also be illuminating because it shows where data directories, pg_hba.conf, etc. are.

How to specify font attributes for all elements on an html web page?

I can't stress this advice enough: use a reset stylesheet, then set everything explicitly. It'll cut your cross-browser CSS development time in half.

Try Eric Meyer's reset.css.

How to present a simple alert message in java?

Assuming you already have a JFrame to call this from:

JOptionPane.showMessageDialog(frame, "thank you for using java");

See The Java Tutorials: How to Make Dialogs
See the JavaDoc

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

Sort objects in ArrayList by date?

Here's the answer of how I achieve it:

Mylist.sort(Comparator.comparing(myClass::getStarttime));

How to decrypt a password from SQL server?

You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.

Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?

How to check if element has any children in Javascript?

You could also do the following:

if (element.innerHTML.trim() !== '') {
    // It has at least one
} 

This uses the trim() method to treat empty elements which have only whitespaces (in which case hasChildNodes returns true) as being empty.

NB: The above method doesn't filter out comments. (so a comment would classify a a child)

To filter out comments as well, we could make use of the read-only Node.nodeType property where Node.COMMENT_NODE (A Comment node, such as <!-- … -->) has the constant value - 8

if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '' {
   // It has at least one
}

_x000D_
_x000D_
let divs = document.querySelectorAll('div');
for(element of divs) {
  if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '') {
   console.log('has children')
  } else { console.log('no children') }
}
_x000D_
<div><span>An element</span>
<div>some text</div>
<div>     </div> <!-- whitespace -->
<div><!-- A comment --></div>
<div></div>
_x000D_
_x000D_
_x000D_

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

MySQL: How to allow remote connection to mysql

I had to this challenge when working on a Java Project with MySQL server as the database.

Here's how I did it:

First, confirm that your MySQL server configuration to allow for remote connections. Use your preferred text editor to open the MySQL server configuration file:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0 (to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.

Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:

sudo systemctl restart mysql

Next, log into the MySQL server console on the server it was installed:

mysql -u root -p

Enter your mysql user password

Check the hosts that the user you want has access to already. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| localhost |
+-----------+

Next, I ran the command below to grant the root user remote access to the database named my_database:

USE my_database;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';

Note: % grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';

Afterwhich I checked the hosts that the user now has access to. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| %         |
| localhost |
+-----------+

Finally, you can try connecting to the MySQL server from another server using the command:

mysql -u username -h mysql-server-ip-address -p

Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:

mysql -u root -h 34.69.261.158 -p

Enter your mysql user password

You should get this output depending on your MySQL server version:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Resources: How to Allow Remote Connections to MySQL

That's all.

I hope this helps

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

document.body.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
  event.preventDefault();
  console.log('clicked ;)');
}
});

DEMO

https://jsfiddle.net/muratkezli/51rnc9ug/6/

MySQL - Cannot add or update a child row: a foreign key constraint fails

My fix for this was my child table needed to be populated before the parent table.

I had two tables: UserDetails and Login linked by an email address. I therefore had to insert into the UserDetails first before inserting into the Login table:

insert into UserDetails (Email, Name, Telephone, Department) values ('Email', 'Name', 'number', 'IT');

Then:

insert into Login (UserID, UserType, Email, Username, Password) VALUES (001, 'SYS-USR-ADMIN', 'Email', 'Name', 'Password')

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

Tkinter module not found on Ubuntu

I had the same problem. I tried to use:

sudo apt-get install python3-tk

It gave an error stating blt(>=2.4z-7) is not present and is not installable.

I went here and manually installed it. (For Ubuntu 14.04)

Then I used apt again and it worked.

I concluded that python3.4 in Ubuntu didn't come with the .so file required to carry on installation. And blt was required to download it.

Reducing the gap between a bullet and text in a list item

Here's how to do it.

Multi-line works perfectly if you do it this way. Bullet will automatically size with text. Indent is straight-forward: it's just the padding-left on the li. Minimal CSS required.

_x000D_
_x000D_
ul {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
ul > li {_x000D_
  position: relative;_x000D_
  padding-left: 12px;_x000D_
}_x000D_
ul > li:before {_x000D_
  content: "•";_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
}_x000D_
div {_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<div>_x000D_
  <ul>_x000D_
    <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, explicabo iste numquam dolorem harum natus! Voluptate magni expedita, eaque voluptates, aliquam maiores vel quia repellat a ipsum possimus eveniet, blanditiis.</li>_x000D_
    <li>Repudiandae repellendus laboriosam, odio vero debitis non quisquam provident deserunt, ratione facilis suscipit delectus sunt aliquid, in maxime autem optio, exercitationem iusto fugiat itaque omnis assumenda est a praesentium? Natus?</li>_x000D_
    <li>Voluptatem, distinctio, eius, soluta, atque laboriosam tempora magnam sequi saepe architecto accusamus hic facilis! Tenetur, necessitatibus. Ut ipsam, officia omnis obcaecati vero consectetur vel similique nam consequatur quidem at doloremque.</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unable to import a module that is definitely installed

It's the python path problem.

In my case, I have python installed in:

/Library/Frameworks/Python.framework/Versions/2.6/bin/python,

and there is no site-packages directory within the python2.6.

The package(SOAPpy) I installed by pip is located

/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/

And site-package is not in the python path, all I did is add site-packages to PYTHONPATH permanently.

  1. Open up Terminal
  2. Type open .bash_profile
  3. In the text file that pops up, add this line at the end:

    export PYTHONPATH=$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/

  4. Save the file, restart the Terminal, and you're done

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

I ran into this in a Web App on Azure when attempting to connect to Blob Storage. The problem turned out to be that I had missed deploying a connection string for the blob storage so it was still pointing at the storage emulator. There must be some retry logic built into the client because I saw about 3 attempts. The /devstorageaccount1 here is a dead giveaway.

enter image description here

Fixed by properly setting the connection string in Azure.

Dynamically Add Variable Name Value Pairs to JSON Object

From what the other answers have proposed, I believe this might help:

var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;

However, this is not tested, just an assumption based on the constant repetition of:

object["string"] = value;
//object = {string: value}

Google Maps API Multiple Markers with Infowindows

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  

Is there a way to use use text as the background with CSS?

You could make the element containing the bg text have a lower stacking order ( z-index, position ) and possibly even set opacity. So the element you need on top would need a higher stacking order ( z-index:5; position:relative; for ex ) and the element behind would need something lower ( default or just a lower z-index like 3 and position:relative; ).

How to drop all tables from a database with one SQL query?

Not quite 1 query, still quite short and sweet:

-- Disable all referential integrity constraints
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Drop all PKs and FKs
declare @sql nvarchar(max)
SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name  +'  drop constraint ' + Constraint_Name  from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@sql)
GO

-- Drop all tables
EXEC sp_msforeachtable 'DROP TABLE ?'
GO

CSS to keep element at "fixed" position on screen

The tweak:

position:fixed; 

works, but it breaks certain options....for example a scrollable menu that is tagged with a fixed position will not expand with the browser window anymore...wish there was another way to pin something on top/always visible

iOS Launching Settings -> Restrictions URL Scheme

Works Fine for App Notification settings on IOS 10 (tested)

if(&UIApplicationOpenSettingsURLString != nil){
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

Class has been compiled by a more recent version of the Java Environment

I had a similar issue from the console after building a Jar in Intellij. Using the Java configuration to update to a newer version (Windows -> Configure Java -> Update -> Update Now) didn't work and stuck at version 1.8 (Java 8).

To switch to a more recent version locally I had to install the Java 15 JDK from https://www.oracle.com/uk/java/technologies/javase-jdk15-downloads.html and add that to my Java runtime environment settings.

Java Runtime Environment Settings

show/hide a div on hover and hover out

You could use jQuery to show the div, and set it at wherever your mouse is:

html:

<!DOCTYPE html>
<html>

  <head>
    <link href="style.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  </head>

  <body>
    <div id="trigger">
      <h1>Hover me!</h1>
      <p>Ill show you wonderful things</p>
    </div>
    <div id="secret">
     shhhh
    </div>
    <script src="script.js"></script>
  </body>

</html>

styles:

#trigger {
  border: 1px solid black;
}
#secret {
  display:none;
  top:0;  
  position:absolute;
  background: grey;
  color:white;
  width: 50%;
}

js:

$("#trigger").hover(function(e){
    $("#secret").show().css('top', e.pageY + "px").css('left', e.pageX + "px");
  },function(e){
    $("#secret").hide()
})

You can find the example here Cheers! http://plnkr.co/edit/LAhs8X9F8N3ft7qFvjzy?p=preview

How to draw a circle with text in the middle?

If it's only one line of text you could use the line-height property, with the same value as the element height:

height:100px;
line-height:100px;

If the text has multiple lines, or if the content is variable, you could use the padding-top:

padding-top:30px;
height:70px;

Example: http://jsfiddle.net/2GUFL/

nginx: [emerg] "server" directive is not allowed here

That is not an nginx configuration file. It is part of an nginx configuration file.

The nginx configuration file (usually called nginx.conf) will look like:

events {
    ...
}
http {
    ...
    server {
        ...
    }
}

The server block is enclosed within an http block.

Often the configuration is distributed across multiple files, by using the include directives to pull in additional fragments (for example from the sites-enabled directory).

Use sudo nginx -t to test the complete configuration file, which starts at nginx.conf and pulls in additional fragments using the include directive. See this document for more.

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

    [HttpPost]
    public JsonResult ContactAdd(ContactViewModel contactViewModel)
    {
        if (ModelState.IsValid)
        {
            var job = new Job { Contact = new Contact() };

            Mapper.Map(contactViewModel, job);
            Mapper.Map(contactViewModel, job.Contact);

            _db.Jobs.Add(job);

            _db.SaveChanges();

            //you do not even need this line of code,200 is the default for ASP.NET MVC as long as no exceptions were thrown
            //Response.StatusCode = (int)HttpStatusCode.OK;

            return Json(new { jobId = job.JobId });
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { jobId = -1 });
        }
    }

MySQL Orderby a number, Nulls last

I found this to be a good solution for the most part:

SELECT * FROM table ORDER BY ISNULL(field), field ASC;

How to Publish Web with msbuild?

I got it mostly working without a custom msbuild script. Here are the relevant TeamCity build configuration settings:

Artifact paths: %system.teamcity.build.workingDir%\MyProject\obj\Debug\Package\PackageTmp 
Type of runner: MSBuild (Runner for MSBuild files) 
Build file path: MyProject\MyProject.csproj 
Working directory: same as checkout directory 
MSBuild version: Microsoft .NET Framework 4.0 
MSBuild ToolsVersion: 4.0 
Run platform: x86 
Targets: Package 
Command line parameters to MSBuild.exe: /p:Configuration=Debug

This will compile, package (with web.config transformation), and save the output as artifacts. The only thing missing is copying the output to a specified location, but that could be done either in another TeamCity build configuration with an artifact dependency or with an msbuild script.

Update

Here is an msbuild script that will compile, package (with web.config transformation), and copy the output to my staging server

<?xml version="1.0" encoding="utf-8" ?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
        <SolutionName>MySolution</SolutionName>
        <SolutionFile>$(SolutionName).sln</SolutionFile>
        <ProjectName>MyProject</ProjectName>
        <ProjectFile>$(ProjectName)\$(ProjectName).csproj</ProjectFile>
    </PropertyGroup>

    <Target Name="Build" DependsOnTargets="BuildPackage;CopyOutput" />

    <Target Name="BuildPackage">
        <MSBuild Projects="$(SolutionFile)" ContinueOnError="false" Targets="Rebuild" Properties="Configuration=$(Configuration)" />
        <MSBuild Projects="$(ProjectFile)" ContinueOnError="false" Targets="Package" Properties="Configuration=$(Configuration)" />
    </Target>

    <Target Name="CopyOutput">
        <ItemGroup>
            <PackagedFiles Include="$(ProjectName)\obj\$(Configuration)\Package\PackageTmp\**\*.*"/>
        </ItemGroup>
        <Copy SourceFiles="@(PackagedFiles)" DestinationFiles="@(PackagedFiles->'\\build02\wwwroot\$(ProjectName)\$(Configuration)\%(RecursiveDir)%(Filename)%(Extension)')"/>
    </Target>
</Project>

You can also remove the SolutionName and ProjectName properties from the PropertyGroup tag and pass them to msbuild.

msbuild build.xml /p:Configuration=Deploy;SolutionName=MySolution;ProjectName=MyProject

Update 2

Since this question still gets a good deal of traffic, I thought it was worth updating my answer with my current script that uses Web Deploy (also known as MSDeploy).

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
    <ProjectFile Condition=" '$(ProjectFile)' == '' ">$(ProjectName)\$(ProjectName).csproj</ProjectFile>
    <DeployServiceUrl Condition=" '$(DeployServiceUrl)' == '' ">http://staging-server/MSDeployAgentService</DeployServiceUrl>
  </PropertyGroup>

  <Target Name="VerifyProperties">
    <!-- Verify that we have values for all required properties -->
    <Error Condition=" '$(ProjectName)' == '' " Text="ProjectName is required." />
  </Target>

  <Target Name="Build" DependsOnTargets="VerifyProperties">
    <!-- Deploy using windows authentication -->
    <MSBuild Projects="$(ProjectFile)"
             Properties="Configuration=$(Configuration);
                             MvcBuildViews=False;
                             DeployOnBuild=true;
                             DeployTarget=MSDeployPublish;
                             CreatePackageOnPublish=True;
                             AllowUntrustedCertificate=True;
                             MSDeployPublishMethod=RemoteAgent;
                             MsDeployServiceUrl=$(DeployServiceUrl);
                             SkipExtraFilesOnServer=True;
                             UserName=;
                             Password=;"
             ContinueOnError="false" />
  </Target>
</Project>

In TeamCity, I have parameters named env.Configuration, env.ProjectName and env.DeployServiceUrl. The MSBuild runner has the build file path and the parameters are passed automagically (you don't have to specify them in Command line parameters).

You can also run it from the command line:

msbuild build.xml /p:Configuration=Staging;ProjectName=MyProject;DeployServiceUrl=http://staging-server/MSDeployAgentService

Difference between links and depends_on in docker_compose.yml

[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.

[Original answer]:

It is pretty clear in the documentation. depends_on decides the dependency and the order of container creation and links not only does these, but also

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

For example, assuming the following docker-compose.yml file:

web:
  image: example/my_web_app:latest
  links:
    - db
    - cache

db:
  image: postgres:latest

cache:
  image: redis:latest

With links, code inside web will be able to access the database using db:5432, assuming port 5432 is exposed in the db image. If depends_on were used, this wouldn't be possible, but the startup order of the containers would be correct.

How can I apply a function to every row/column of a matrix in MATLAB?

You may want the more obscure Matlab function bsxfun. From the Matlab documentation, bsxfun "applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled."

@gnovice stated above that sum and other basic functions already operate on the first non-singleton dimension (i.e., rows if there's more than one row, columns if there's only one row, or higher dimensions if the lower dimensions all have size==1). However, bsxfun works for any function, including (and especially) user-defined functions.

For example, let's say you have a matrix A and a row vector B. E.g., let's say:

A = [1 2 3;
     4 5 6;
     7 8 9]
B = [0 1 2]

You want a function power_by_col which returns in a vector C all the elements in A to the power of the corresponding column of B.

From the above example, C is a 3x3 matrix:

C = [1^0 2^1 3^2;
     4^0 5^1 6^2;
     7^0 8^1 9^2]

i.e.,

C = [1 2 9;
     1 5 36;
     1 8 81]

You could do this the brute force way using repmat:

C = A.^repmat(B, size(A, 1), 1)

Or you could do this the classy way using bsxfun, which internally takes care of the repmat step:

C = bsxfun(@(x,y) x.^y, A, B)

So bsxfun saves you some steps (you don't need to explicitly calculate the dimensions of A). However, in some informal tests of mine, it turns out that repmat is roughly twice as fast if the function to be applied (like my power function, above) is simple. So you'll need to choose whether you want simplicity or speed.

What is this weird colon-member (" : ") syntax in the constructor?

I don't know how you could miss this one, it's pretty basic. That's the syntax for initializing member variables or base class constructors. It works for plain old data types as well as class objects.

How to get the element clicked (for the whole document)?

$(document).click(function (e) {
    alert($(e.target).text());
});

select certain columns of a data table

First store the table in a view, then select columns from that view into a new table.

// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
    table.Columns.Add("col" + i.ToString());

// Load the table with contrived data
for (int i = 0; i < 100; i++)
{
    System.Data.DataRow row = table.NewRow();
    for (int j = 0; j < 11; j++)
        row[j] = i.ToString() + ", " + j.ToString();
    table.Rows.Add(row);
}

// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");

Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns

Screen width in React Native

In React-Native we have an Option called Dimensions

Include Dimensions at the top var where you have include the Image,and Text and other components.

Then in your Stylesheets you can use as below,

ex: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}

In this way you can get the device window and height.

How to disable all <input > inside a form with jQuery?

Above example is technically incorrect. Per latest jQuery, use the prop() method should be used for things like disabled. See their API page.

To disable all form elements inside 'target', use the :input selector which matches all input, textarea, select and button elements.

$("#target :input").prop("disabled", true);

If you only want the elements, use this.

$("#target input").prop("disabled", true);

Can I get image from canvas element and use it in img src tag?

canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images. Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.

Copy tables from one database to another in SQL Server

Copy Data

INSERT INTO Alfestonline..url_details(url,[status],recycle) 
SELECT url,status,recycle FROM AlfestonlineOld..url_details

Highlight Bash/shell code in Markdown files

Per the documentation from GitHub regarding GFM syntax highlighted code blocks

We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.

Rendered on GitHub, console makes the lines after the console blue. bash, sh, or shell don't seem to "highlight" much ...and you can use posh for PowerShell or CMD.

How to convert IPython notebooks to PDF and HTML?

You can do it by 1st converting the notebook into HTML and then into PDF format:

Following steps I have implemented on: OS: Ubuntu, Anaconda-Jupyter notebook, Python 3

1 Save Notebook in HTML format:

  1. Start the jupyter notebook that you want to save in HTML format. First save the notebook properly so that HTML file will have a latest saved version of your code/notebook.

  2. Run the following command from the notebook itself:

    !jupyter nbconvert --to html your_notebook_name.ipynb

After execution will create HTML version of your notebook and will save it in the current working directory. You will see one html file will be added into the current directory with your_notebook_name.html name

(your_notebook_name.ipynb --> your_notebook_name.html).

2 Save html as PDF:

  1. Now open that your_notebook_name.html file (click on it). It will be opened in a new tab of your browser.
  2. Now go to print option. From here you can save this file in pdf file format.

Note that from print option we also have the flexibility of selecting a portion of a notebook to save in pdf format.

How to set HTML5 required attribute in Javascript?

And the jquery version:

$('input').attr('required', true)
$('input').attr('required', false)

I know it's beyond the question, but maybe someone will find this helpful :)

Unable to ping vmware guest from another vmware guest

There are several related solutions available on the internet, but it all depends on the configuration of the machine and the firewall rules.

For me below solution is worked:

  • Disabled the VMware Network Adapter VMNet8
  • Removed the network from the VM
  • Enabled the VMware Network Adapter VMNet8
  • Re-added the Network to VM, and set it to NAT
  • Restarted the machine

Check this blog post for detailed solution.

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Generic deep diff between two objects

The more extended and simplified function from sbgoran's answer.
This allow deep scan and find an array's simillarity.

_x000D_
_x000D_
var result = objectDifference({_x000D_
      a:'i am unchanged',_x000D_
      b:'i am deleted',_x000D_
      e: {a: 1,b:false, c: null},_x000D_
      f: [1,{a: 'same',b:[{a:'same'},{d: 'delete'}]}],_x000D_
      g: new Date('2017.11.25'),_x000D_
      h: [1,2,3,4,5]_x000D_
  },_x000D_
  {_x000D_
      a:'i am unchanged',_x000D_
      c:'i am created',_x000D_
      e: {a: '1', b: '', d:'created'},_x000D_
      f: [{a: 'same',b:[{a:'same'},{c: 'create'}]},1],_x000D_
      g: new Date('2017.11.25'),_x000D_
      h: [4,5,6,7,8]_x000D_
  });_x000D_
console.log(result);_x000D_
_x000D_
function objectDifference(obj1, obj2){_x000D_
    if((dataType(obj1) !== 'array' && dataType(obj1) !== 'object') || (dataType(obj2) !== 'array' && dataType(obj2) !== 'object')){_x000D_
        var type = '';_x000D_
_x000D_
        if(obj1 === obj2 || (dataType(obj1) === 'date' && dataType(obj2) === 'date' && obj1.getTime() === obj2.getTime()))_x000D_
            type = 'unchanged';_x000D_
        else if(dataType(obj1) === 'undefined')_x000D_
            type = 'created';_x000D_
        if(dataType(obj2) === 'undefined')_x000D_
            type = 'deleted';_x000D_
        else if(type === '') type = 'updated';_x000D_
_x000D_
        return {_x000D_
            type: type,_x000D_
            data:(obj1 === undefined) ? obj2 : obj1_x000D_
        };_x000D_
    }_x000D_
  _x000D_
    if(dataType(obj1) === 'array' && dataType(obj2) === 'array'){_x000D_
        var diff = [];_x000D_
        obj1.sort(); obj2.sort();_x000D_
        for(var i = 0; i < obj2.length; i++){_x000D_
            var type = obj1.indexOf(obj2[i]) === -1?'created':'unchanged';_x000D_
            if(type === 'created' && (dataType(obj2[i]) === 'array' || dataType(obj2[i]) === 'object')){_x000D_
                diff.push(_x000D_
                    objectDifference(obj1[i], obj2[i])_x000D_
                );_x000D_
                continue;_x000D_
            }_x000D_
            diff.push({_x000D_
                type: type,_x000D_
                data: obj2[i]_x000D_
            });_x000D_
        }_x000D_
_x000D_
        for(var i = 0; i < obj1.length; i++){_x000D_
            if(obj2.indexOf(obj1[i]) !== -1 || dataType(obj1[i]) === 'array' || dataType(obj1[i]) === 'object')_x000D_
                continue;_x000D_
            diff.push({_x000D_
                type: 'deleted',_x000D_
                data: obj1[i]_x000D_
            });_x000D_
        }_x000D_
    } else {_x000D_
        var diff = {};_x000D_
        var key = Object.keys(obj1);_x000D_
        for(var i = 0; i < key.length; i++){_x000D_
            var value2 = undefined;_x000D_
            if(dataType(obj2[key[i]]) !== 'undefined')_x000D_
                value2 = obj2[key[i]];_x000D_
_x000D_
            diff[key[i]] = objectDifference(obj1[key[i]], value2);_x000D_
        }_x000D_
_x000D_
        var key = Object.keys(obj2);_x000D_
        for(var i = 0; i < key.length; i++){_x000D_
            if(dataType(diff[key[i]]) !== 'undefined')_x000D_
                continue;_x000D_
_x000D_
            diff[key[i]] = objectDifference(undefined, obj2[key[i]]);_x000D_
        }_x000D_
    }_x000D_
_x000D_
    return diff;_x000D_
}_x000D_
_x000D_
function dataType(data){_x000D_
    if(data === undefined || data === null) return 'undefined';_x000D_
    if(data.constructor === String) return 'string';_x000D_
    if(data.constructor === Array) return 'array';_x000D_
    if(data.constructor === Object) return 'object';_x000D_
    if(data.constructor === Number) return 'number';_x000D_
    if(data.constructor === Boolean) return 'boolean';_x000D_
    if(data.constructor === Function) return 'function';_x000D_
    if(data.constructor === Date) return 'date';_x000D_
    if(data.constructor === RegExp) return 'regex';_x000D_
    return 'unknown';_x000D_
}
_x000D_
_x000D_
_x000D_

How to pass a JSON array as a parameter in URL

Send Json data string to a web address and get a result with method post

in C#

public string SendJsonToUrl(string Url, string StrJsonData)
{
    if (Url == "" || StrJsonData == "") return "";
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = StrJsonData.Length;
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(StrJsonData);
            streamWriter.Close();
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    catch (Exception exp)
    {
        throw new Exception("SendJsonToUrl", exp);
    }
}

in PHP

<?php

$input = file_get_contents('php://input');
$json = json_decode($input ,true);

?>

How to INNER JOIN 3 tables using CodeIgniter

I believe that using CodeIgniters active record framework that you would just use two join statements one after the other.
eg:

$this->db->select('*');
$this->db->from('table1');
$this->db->join('table1', 'table1.id = table2.id');
$this->db->join('table1', 'table1.id = table3.id');
$query = $this->db->get();

Give that a try and see how it goes.

Where can I find the Java SDK in Linux after installing it?

Another best way to find Java folder path is to use alternatives command in Fedora Linux (I know its for Ubuntu but I hit this post from google just by its headline). Just want to share incase people like me looking for answers for fedora flavour.

To display all information regarding java

alternatives --display java

Preserve line breaks in angularjs

Well it depends, if you want to bind datas, there shouldn't be any formatting in it, otherwise you can bind-html and do description.replace(/\\n/g, '<br>') not sure it's what you want though.

How do I set the visibility of a text box in SSRS using an expression?

instead of this

=IIf((CountRows("ScannerStatisticsData")=0),False,True)

write only the expression when you want to hide

CountRows("ScannerStatisticsData")=0

or change the order of true and false places as below

=IIf((CountRows("ScannerStatisticsData")=0),True,False)

because the Visibility expression set up the Hidden value. that you can find above the text area as

" Set expression for: Hidden " 

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 4

$('#my-modal').on('hidden.bs.modal', function () {
  window.alert('hidden event fired!');
});

See this JSFiddle for a working example:

https://jsfiddle.net/6n7bg2c9/

See the Modal Events section of the docs here:

https://getbootstrap.com/docs/4.3/components/modal/#events

How to detect iPhone 5 (widescreen devices)?

if ((int)[[UIScreen mainScreen] bounds].size.height == 568)
{
    // This is iPhone 5 screen
} else {
    // This is iPhone 4 screen
}

Objective-C: Extract filename from path string

If you're displaying a user-readable file name, you do not want to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath: method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.

How to get image size (height & width) using JavaScript?

Also (in addition to Rex and Ian's answers) there is:

imageElement.naturalHeight

and

imageElement.naturalWidth

These provide the height and width of the image file itself (rather than just the image element).

Generic Interface

Here's one suggestion:

public interface Service<T,U> {
    T executeService(U... args);
}

public class MyService implements Service<String, Integer> {
    @Override
    public String executeService(Integer... args) {
        // do stuff
        return null;
    }
}

Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.

It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable interface. It doesn't support arguments but that part of the interface has the least value (imho).

How do I get a platform-dependent new line character?

Avoid appending strings using String + String etc, use StringBuilder instead.

String separator = System.getProperty( "line.separator" );
StringBuilder lines = new StringBuilder( line1 );
lines.append( separator );
lines.append( line2 );
lines.append( separator );
String result = lines.toString( );

Connection pooling options with JDBC: DBCP vs C3P0

Another alternative, Proxool, is mentioned in this article.

You might be able to find out why Hibernate bundles c3p0 for its default connection pool implementation?

Editing hosts file to redirect url?

Make sure to double the entry with an additional "www"-prefix. If you don't addresses like "www.acme.com" will not work!

Implement a loading indicator for a jQuery AJAX call

I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like

$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });

HTML checkbox onclick called in Javascript

jQuery has a function that can do this:

  1. include the following script in your head:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    

    (or just download the jQuery.js file online and include it locally)

  2. use this script to toggle the check box when the input is clicked:

    var toggle = false;
    $("#INPUTNAMEHERE").click(function() {
            $("input[type=checkbox]").attr("checked",!toggle);
            toggle = !toggle;
    }); 
    

That should do what you want if I understood what you were trying to do.

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

This often occurs when you build software in RHEL 7 and try to run on RHEL 6.

To update GLIBC to any version, simply download the package from

https://ftp.gnu.org/gnu/libc/

For example glibc-2.14.tar.gz in your case.

1. tar xvfz glibc-2.14.tar.gz
2. cd glibc-2.14
3. mkdir build
4. cd build
5. ../configure --prefix=/opt/glibc-2.14
6. make
7. sudo make install
8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH

Then try to run your software, glibc-2.14 should be linked.

Show Current Location and Update Location in MKMapView in Swift

You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.

mapView.userTrackingMode = .follow

See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode .

".addEventListener is not a function" why does this error occur?

document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.

Update #1:

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Update #2: (with removeEventListener incorporated as well)

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment(e) {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
  for (var i = 0; i < numComments; i++) {
    comments[i].removeEventListener('click', showComment, false);
  }
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

<input type="file"> limit selectable files by extensions

NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.


Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.

Here's a simple example that only allows files that end in ".gif" to be uploaded:

<script type="text/javascript">
    function checkFile() {
        var fileElement = document.getElementById("uploadFile");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension.toLowerCase() == "gif") {
            return true;
        }
        else {
            alert("You must select a GIF file for upload");
            return false;
        }
    }
</script>

<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
    <input name="uploadFile" id="uploadFile" type="file" />

    <input type="submit" />
</form>

However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).

However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.

How do I convert from BLOB to TEXT in MySQL?

Or you can use this function:

DELIMITER $$

CREATE FUNCTION BLOB2TXT (blobfield VARCHAR(255)) RETURNS longtext
DETERMINISTIC
NO SQL
BEGIN
       RETURN CAST(blobfield AS CHAR(10000) CHARACTER SET utf8);
END
$$


DELIMITER ;

How can I override inline styles with external CSS?

The only way to override inline style is by using !important keyword beside the CSS rule. The following is an example of it.

_x000D_
_x000D_
div {
        color: blue !important;
       /* Adding !important will give this rule more precedence over inline style */
    }
_x000D_
<div style="font-size: 18px; color: red;">
    Hello, World. How can I change this to blue?
</div>
_x000D_
_x000D_
_x000D_

Important Notes:

  • Using !important is not considered as a good practice. Hence, you should avoid both !important and inline style.

  • Adding the !important keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.

  • It even overrides the inline styles from the markup.

  • The only way to override is by using another !important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.

  • Must Read - CSS Specificity by MDN

SQL Server default character encoding

You can see collation settings for each table like the following code:

SELECT t.name TableName, c.name ColumnName, collation_name  
FROM sys.columns c  
INNER JOIN sys.tables t on c.object_id = t.object_id where t.name = 'name of table';

Format Float to n decimal places

Of note, use of DecimalFormat constructor is discouraged. The javadoc for this class states:

In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.

https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

So what you need to do is (for instance):

NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP); 
Float formatedFloat = new Float(formatter.format(floatValue));

What is Mocking?

Mocking is generating pseudo-objects that simulate real objects behaviour for tests

Why is Java's SimpleDateFormat not thread-safe?

DateTimeFormatter in Java 8 is immutable and thread-safe alternative to SimpleDateFormat.

How do I remove/delete a folder that is not empty?

To delete a folder even if it might not exist (avoiding the race condition in Charles Chow's answer) but still have errors when other things go wrong (e.g. permission problems, disk read error, the file isn't a directory)

For Python 3.x:

import shutil

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, FileNotFoundError):
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

The Python 2.7 code is almost the same:

import shutil
import errno

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, OSError) and \
        except_instance.errno == errno.ENOENT:
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

How does Git handle symbolic links?

Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.

When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.

If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.

sorting a vector of structs

Yes: you can sort using a custom comparison function:

std::sort(info.begin(), info.end(), my_custom_comparison);

my_custom_comparison needs to be a function or a class with an operator() overload (a functor) that takes two data objects and returns a bool indicating whether the first is ordered prior to the second (i.e., first < second). Alternatively, you can overload operator< for your class type data; operator< is the default ordering used by std::sort.

Either way, the comparison function must yield a strict weak ordering of the elements.

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

That happened to me too, because I was trying to get an IEnumerable but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:

HttpResponseMessage response = await client.GetAsync("api/yourUrl");

if (response.IsSuccessStatusCode)
{
    IEnumerable<RootObject> rootObjects =
        awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();

    foreach (var rootObject in rootObjects)
    {
        Console.WriteLine(
            "{0}\t${1}\t{2}",
            rootObject.Data1, rootObject.Data2, rootObject.Data3);
    }

    Console.ReadLine();
}

Hope It helps.

How to get pip to work behind a proxy server

First Try to set proxy using the following command

SET HTTPS_PROXY=http://proxy.***.com:PORT#

Then Try using the command

pip install ModuleName

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Parsing JSON using C

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.

Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.

The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).

JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

Why should I prefer to use member initialization lists?

Apart from the performance reasons mentioned above, if your class stores references to objects passed as constructor parameters or your class has const variables then you don't have any choice except using initializer lists.

Making button go full-width?

Bootstrap v3 & v4

Use btn-block class on your button/element

Bootstrap v2

Use input-block-level class on your button/element

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Select a row from html table and send values onclick of a button

In my case $(document).ready(function() was missing. Try this.

$(document).ready(function(){   
("#table tr").click(function(){
       $(this).addClass('selected').siblings().removeClass('selected');    
       var value=$(this).find('td:first').html();
       alert(value);    
    });
    $('.ok').on('click', function(e){
        alert($("#table tr.selected td:first").html());
    });
});

Count the number of times a string appears within a string

Probably not the most efficient, but think it's a neat way to do it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true"));
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false"));

    }

    static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find)
    {
        var s2 = orig.Replace(find,"");
        return (orig.Length - s2.Length) / find.Length;
    }
}

Radio buttons and label to display in same line

I always avoid using float:left but instead I use display: inline

_x000D_
_x000D_
.wrapper-class input[type="radio"] {_x000D_
  width: 15px;_x000D_
}_x000D_
_x000D_
.wrapper-class label {_x000D_
  display: inline;_x000D_
  margin-left: 5px;_x000D_
  }
_x000D_
<div class="wrapper-class">_x000D_
  <input type="radio" id="radio1">_x000D_
  <label for="radio1">Test Radio</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Passing a variable from node.js to html

I have achieved this by a http API node request which returns required object from node object for HTML page at client ,

for eg: API: localhost:3000/username

returns logged in user from cache by node App object .

node route file,

app.get('/username', function(req, res) {
    res.json({ udata: req.session.user });
    });

Hide HTML element by id

.nav ul li a#nav-ask{
    display:none;
}

How to assign the output of a Bash command to a variable?

In shell you assign to a variable without the dollar-sign:

TEST=`pwd`
echo $TEST

that's better (and can be nested) but is not as portable as the backtics:

TEST=$(pwd)
echo $TEST

Always remember: the dollar-sign is only used when reading a variable.