Programs & Examples On #Jslider

JSlider is a Java Swing component that lets the user graphically select a value by sliding a knob within a bounded interval.

How to set the component size with GridLayout? Is there a better way?

For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.

how to set radio option checked onload with jQuery

How about a one liner?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);

Inserting code in this LaTeX document with indentation

Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,

Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.

How to use responsive background image in css3 in bootstrap

Set Responsive and User friendly Background

<style>
body {
background: url(image.jpg);
background-size:100%;
background-repeat: no-repeat;
width: 100%;
}
</style>

Where is a log file with logs from a container?

To directly view the logfile in less, I use:

docker inspect $1 | grep 'LogPath' | sed -n "s/^.*\(\/var.*\)\",$/\1/p" | xargs sudo less

run as ./viewLogs.sh CONTAINERNAME

Check if a variable is null in plsql

Always remember to be careful with nulls in pl/sql conditional clauses as null is never greater, smaller, equal or unequal to anything. Best way to avoid them is to use nvl.

For example

declare
  i integer;
begin
  if i <> 1 then
    i:=1;
    foobar();
  end if;
end;
/

Never goes inside the if clause.

These would work.

if 1<>nvl(i,1) then
if i<> 1 or i is null then

Assert that a method was called in a Python unit test

You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

Using pymox, you'd do it like this:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)

Monitor network activity in Android Phones

Packet Capture is the best tool to track network data on the android. DOesnot need any root access and easy to read and save the calls based on application. Check this out

JavaScript displaying a float to 2 decimal places

float_num.toFixed(2);

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.

VB.NET - Click Submit Button on Webbrowser page

Just follow two steps for clicking a any button using code.

  1. focus the button or element which you want to click

    WebBrowser1.Document.GetElementById("place id here").Focus()

  2. simulate mouse click using this following code

    SendKeys.Send("{ENTER}")

How can I find out if I have Xcode commandline tools installed?

if you want to know the install version of Xcode as well as Swift language current version:

Use below simple command by using Terminal:

1. To get install Xcode Version

 xcodebuild -version

2. To get install Swift language Version

swift --version

Check empty string in Swift?

Check check for only spaces and newlines characters in text

extension String
{
    var  isBlank:Bool {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
    }
}

using

if text.isBlank
{
  //text is blank do smth
}

showing that a date is greater than current date

For SQL Server

select *
from YourTable
where DateCol between getdate() and dateadd(d, 90, getdate())

True/False vs 0/1 in MySQL

Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.

This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.

This doesn't affect the database at all, since it's implemented in the application.

There is not really a BOOLEAN type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.

If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.

You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.

Rotate an image in image source in html

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

How to select records from last 24 hours using SQL?

MySQL :

SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 24 HOUR)

The INTERVAL can be in YEAR, MONTH, DAY, HOUR, MINUTE, SECOND

For example, In the last 10 minutes

SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 10 MINUTE)

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

How to convert string to IP address and vice versa

inet_ntoa() converts a in_addr to string:

The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format.

inet_addr() does the reverse job

The inet_addr function converts a string containing an IPv4 dotted-decimal address into a proper address for the IN_ADDR structure

PS this the first result googling "in_addr to string"!

How to set default value for HTML select?

You should define the attributes of option like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

Remove all constraints affecting a UIView

A Swift solution:

extension UIView {
  func removeAllConstraints() {
    var view: UIView? = self
    while let currentView = view {
      currentView.removeConstraints(currentView.constraints.filter {
        return $0.firstItem as? UIView == self || $0.secondItem as? UIView == self
      })
      view = view?.superview
    }
  }
}

It's important to go through all the parents, since the constraints between two elements are holds by the common ancestors, so just clearing the superview as detailed in this answer is not good enough, and you might end up having bad surprise later on.

Pass variables to Ruby script via command line

tl;dr

I know this is old, but getoptlong wasn't mentioned here and it's probably the best way to parse command line arguments today.


Parsing command line arguments

I strongly recommend getoptlong. It's pretty easy to use and works like a charm. Here is an example extracted from the link above

require 'getoptlong'

opts = GetoptLong.new(
    [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
    [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
    [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
    case opt
        when '--help'
            puts <<-EOF
hello [OPTION] ... DIR

-h, --help:
     show help

--repeat x, -n x:
     repeat x times

--name [name]:
     greet user by name, if name not supplied default is John

DIR: The directory in which to issue the greeting.
            EOF
        when '--repeat'
            repetitions = arg.to_i
        when '--name'
            if arg == ''
                name = 'John'
            else
                name = arg
            end
    end
end

if ARGV.length != 1
    puts "Missing dir argument (try --help)"
    exit 0
end

dir = ARGV.shift

Dir.chdir(dir)
for i in (1..repetitions)
    print "Hello"
    if name
        print ", #{name}"
    end
    puts
end

You can call it like this ruby hello.rb -n 6 --name -- /tmp

What OP is trying to do

In this case I think the best option is to use YAML files as suggested in this answer

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

I have a partial answer for you. This is based on what I get from GCC:

__DATE__ gives something like "Jul 27 2012"

__TIME__ gives something like 21:06:19

Put this text in an include file called build_defs.h:

#ifndef BUILD_DEFS_H

#define BUILD_DEFS_H


#define BUILD_YEAR ((__DATE__[7] - '0') * 1000 +  (__DATE__[8] - '0') * 100 + (__DATE__[9] - '0') * 10 + __DATE__[10] - '0')

#define BUILD_DATE ((__DATE__[4] - '0') * 10 + __DATE__[5] - '0')


#if 0
#if (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
    #define BUILD_MONTH  1
#elif (__DATE__[0] == 'F' && __DATE__[1] == 'e' && __DATE__[2] == 'b')
    #define BUILD_MONTH  2
#elif (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
    #define BUILD_MONTH  3
#elif (__DATE__[0] == 'A' && __DATE__[1] == 'p' && __DATE__[2] == 'r')
    #define BUILD_MONTH  4
#elif (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
    #define BUILD_MONTH  5
#elif (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
    #define BUILD_MONTH  6
#elif (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
    #define BUILD_MONTH  7
#elif (__DATE__[0] == 'A' && __DATE__[1] == 'u' && __DATE__[2] == 'g')
    #define BUILD_MONTH  8
#elif (__DATE__[0] == 'S' && __DATE__[1] == 'e' && __DATE__[2] == 'p')
    #define BUILD_MONTH  9
#elif (__DATE__[0] == 'O' && __DATE__[1] == 'c' && __DATE__[2] == 't')
    #define BUILD_MONTH 10
#elif (__DATE__[0] == 'N' && __DATE__[1] == 'o' && __DATE__[2] == 'v')
    #define BUILD_MONTH 11
#elif (__DATE__[0] == 'D' && __DATE__[1] == 'e' && __DATE__[2] == 'c')
    #define BUILD_MONTH 12
#else
    #error "Could not figure out month"
#endif
#endif

#define BUILD_HOUR ((__TIME__[0] - '0') * 10 + __TIME__[1] - '0')
#define BUILD_MIN ((__TIME__[3] - '0') * 10 + __TIME__[4] - '0')
#define BUILD_SEC ((__TIME__[6] - '0') * 10 + __TIME__[7] - '0')

#endif // BUILD_DEFS_H

I tested the above with GCC on Linux. It all works great, except for the problem that I can't figure out how to get a number for the month. If you check the section that is under #if 0 you will see my attempt to figure out the month. GCC complains with this message:

error: token ""Jul 27 2012"" is not valid in preprocessor expressions

It would be trivial to convert the three-letter month abbreviation into some sort of unique number; just subtract 'A' from the first letter and 'a' from the second and the third, and then convert to a base-26 number or something. But I want to make it evaluate to 1 for January and so on, and I can't figure out how to do that.

EDIT: I just realized that you asked for strings, not expressions that evaluate to integer values.

I tried to use these tricks to build a static string:

#define BUILD_MAJOR 1
#define BUILD_MINOR 4
#define VERSION STRINGIZE(BUILD_MAJOR) "." STRINGIZE(BUILD_MINOR)

char build_str[] = {
    BUILD_MAJOR + '0', '.' BUILD_MINOR + '0', '.',
    __DATE__[7], __DATE__[8], __DATE__[9], __DATE__[10],
    '\0'
};

GCC complains that "initializer element is not constant" for __DATE__.

Sorry, I'm not sure how to help you. Maybe you can try this stuff with your compiler? Or maybe it will give you an idea.

Good luck.

P.S. If you don't need things to be numbers, and you just want a unique build string, it's easy:

const char *build_str = "Version: " VERSION " " __DATE__ " " __TIME__;

With GCC, this results in something like:

Version: 1.4 Jul 27 2012 21:53:59

Add User to Role ASP.NET Identity

This one works for me. You can see this code on AccountController -> Register

var user = new JobUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    //add this to add role to user
     await UserManager.AddToRoleAsync(user.Id, "Name of your role");
}

but the role name must exist in your AspNetRoles table.

How to Replace dot (.) in a string in Java

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

For..In loops in JavaScript - key value pairs

You can use the for..in for that.

for (var key in data)
{
    var value = data[key];
}

Why is Tkinter Entry's get function returning nothing?

you need to put a textvariable in it, so you can use set() and get() method :

var=StringVar()
x= Entry (root,textvariable=var)

How to apply two CSS classes to a single element

Separate 'em with a space.

<div class="c1 c2"></div>

Check if a value exists in ArrayList

When Array List contains object of Primitive DataType.

Use this function:
arrayList.contains(value);

if list contains that value then it will return true else false.

When Array List contains object of UserDefined DataType.

Follow this below Link 

How to compare Objects attributes in an ArrayList?

I hope this solution will help you. Thanks

What process is listening on a certain port on Solaris?

This is sort of an indirect approach, but you could see if a website loads on your web browser of choice from whatever is running on port 80. Or you could telnet to port 80 and see if you get a response that gives you a clue as to what is running on that port and you can go shut it down. Since port 80 is the default port for http traffic chances are there is some sort of http server running there by default, but there's no guarantee.

How to use sed to remove the last n lines of a file

From the sed one-liners:

# delete the last 10 lines of a file
sed -e :a -e '$d;N;2,10ba' -e 'P;D'   # method 1
sed -n -e :a -e '1,10!{P;N;D;};N;ba'  # method 2

Seems to be what you are looing for.

How to pass multiple checkboxes using jQuery ajax post

Here's a more flexible way.

let's say this is your form.

<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>

And this is your jquery ajax below...

                // Don't get confused at this portion right here
                // cuz "var data" will get all the values that the form
                // has submitted in the $_POST. It doesn't matter if you 
                // try to pass a text or password or select form element.
                // Remember that the "form" is not a name attribute
                // of the form, but the "form element" itself that submitted
                // the current post method
                var data = $("form").serialize(); 

                $.ajax({
                    url: "link/of/your/ajax.php", // link of your "whatever" php
                    type: "POST",
                    async: true,
                    cache: false,
                    data: data, // all data will be passed here
                    success: function(data){ 
                        alert(data) // The data that is echoed from the ajax.php
                    }
                });

And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.

<?php 
    print_r($_POST); // this will be echoed back to you upon success.
    echo "This one too, will be echoed back to you";

Hope that is clear enough.

Pretty-print a Map in Java

public void printMapV2 (Map <?, ?> map) {
    StringBuilder sb = new StringBuilder(128);
    sb.append("{");
    for (Map.Entry<?,?> entry : map.entrySet()) {
        if (sb.length()>1) {
            sb.append(", ");
        }
        sb.append(entry.getKey()).append("=").append(entry.getValue());
    }
    sb.append("}");
    System.out.println(sb);
}

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

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

then of course you can't use UTF8 encoding used in other examples..

How to import/include a CSS file using PHP code and not HTML code?

You have to surround the CSS with a <style> tag:

<?php include 'header.php'; ?>
<style>
<?php include 'CSS/main.css'; ?>
</style>
...

PHP include works fine with .css ending too. In this way you can even use PHP in your CSS file. That can be really helpful to organize e.g. colors as variables.

Leader Not Available Kafka in Console Producer

Issue is resolved after adding the listener setting on server.properties file located at config directory. listeners=PLAINTEXT://localhost(or your server):9092 Restart kafka after this change. Version used 2.11

Finding all possible permutations of a given string in python

def perm(string):
   res=[]
   for j in range(0,len(string)):
       if(len(string)>1):
           for i in perm(string[1:]):
               res.append(string[0]+i)
       else:
           return [string];
       string=string[1:]+string[0];
   return res;
l=set(perm("abcde"))

This is one way to generate permutations with recursion, you can understand the code easily by taking strings 'a','ab' & 'abc' as input.

You get all N! permutations with this, without duplicates.

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

TypeError: expected a character buffer object - while trying to save integer to textfile

from __future__ import with_statement
with open('file.txt','r+') as f:
    counter = str(int(f.read().strip())+1)
    f.seek(0)
    f.write(counter)

Javascript to convert UTC to local time

You could take a look at date-and-time api for easily date manipulation.

_x000D_
_x000D_
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);_x000D_
console.log(now);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
_x000D_
_x000D_
_x000D_

Vendor code 17002 to connect to SQLDeveloper

In your case the "Vendor code 17002" is the equivalent of the ORA-12541 error: It's most likely that your listener is down, or has an improper port or service name. From the docs:

ORA-12541: TNS no listener

Cause: Listener for the source repository has not been started.

Action: Start the Listener on the machine where the source repository resides.

Difference between matches() and find() in Java Regex

matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:

public static void main(String[] args) throws ParseException {
    Pattern p = Pattern.compile("\\d\\d\\d");
    Matcher m = p.matcher("a123b");
    System.out.println(m.find());
    System.out.println(m.matches());

    p = Pattern.compile("^\\d\\d\\d$");
    m = p.matcher("123");
    System.out.println(m.find());
    System.out.println(m.matches());
}

/* output:
true
false
true
true
*/

123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.

How to increment an iterator by 2?

If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next / std::prev:

std::next(iter, 2);          // returns a copy of iter incremented by 2
std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
std::prev(iter, 2);          // returns a copy of iter decremented by 2

How to re-enable right click so that I can inspect HTML elements in Chrome?

Hi i have a shorter version. this does same as a best answer. (it works on chrome 74.03)

document.querySelectorAll('*').forEach(e => e.oncontextmenu = null)

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

If you are using SQL Server:

ORDER_BY cast(registration_no as int) ASC

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

In Java, how do you determine if a thread is running?

Have your thread notify some other thread when it’s finished. This way you’ll always know exactly what’s going on.

Eclipse won't compile/run java file

I was also in the same problem, check your build path in eclipse by Right Click on Project > build path > configure build path

Now check for Excluded Files, it should not have your file specified there by any means or by regex.

Cheers!image for error fix view, see Excluded field

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

How to use a PHP class from another file?

You can use include/include_once or require/require_once

require_once('class.php');

Alternatively, use autoloading by adding to page.php

<?php 
function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

$vars = new IUarts(); 
print($vars->data);    
?>

It also works adding that __autoload function in a lib that you include on every file like utils.php.

There is also this post that has a nice and different approach.

Efficient PHP auto-loading and naming strategies

How to add one column into existing SQL Table

alter table table_name add field_name (size);

alter table arnicsc add place number(10);

How to override the [] operator in Python?

You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6

Example of a strong and weak entity types

./Database/DataModels/RelationalDataModel/WeakEntity

It probably can be written in two factors:

  • DEPENDENCE: Depends on the existence of an identifying entity set (total, one-to-many relationship).
  • IDENTIFICATION: Does not have a primary key. It has a partial key (or discriminator). It needs to use the primary key of another table for identification.

If we would think of a database holding questions and answers, then the questions would be the strong entity and the answers would be the weak entity. So, Question (id, text) and Answer (number, question_id, text) would be our tables. But why is the Answer's table a weak entity?

  • Dependence to the question table. Every answer is connected to one question (assumption) and so it cannot be on its own. That is why we have people who ask one question and answer it themselves so that they can help other people and get some extra likings.

  • Identification from the primary key of the question. One would not be able to identify an answer (assuming that its id is a number identifier) because a question might be answered by answers whose identifier might exist in other questions too. Primary key of the answer table: (number, question_id).

Background color for Tk in Python

root.configure(background='black')

or more generally

<widget>.configure(background='black')

How can I completely remove TFS Bindings

File -> Source Control -> Advanced -> Change Source Control and then unbind and/or disconnect all projects and the solution.

This should remove all bindings from the solution and project files. (After this you can switch the SCC provider in Tools -> Options -> Source Control -> Plug-in Selection).

The SCC specification prescribes that all SCC providers should implement this behavior. (I only tested it for VSS, TFS and AnkhSVN)

Pass table as parameter into sql server UDF

you can do something like this

/* CREATE USER DEFINED TABLE TYPE */

CREATE TYPE StateMaster AS TABLE
(
 StateCode VARCHAR(2),
 StateDescp VARCHAR(250)
)
GO

/*CREATE FUNCTION WHICH TAKES TABLE AS A PARAMETER */

CREATE FUNCTION TableValuedParameterExample(@TmpTable StateMaster READONLY)
RETURNS  VARCHAR(250)
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 SELECT @StateDescp = StateDescp FROM @TmpTable
 RETURN @StateDescp
END
GO

/*CREATE STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER */

CREATE PROCEDURE TableValuedParameterExample_SP
(
@TmpTable StateMaster READONLY
)
AS
BEGIN
 INSERT INTO StateMst 
  SELECT * FROM @TmpTable
END
GO


BEGIN
/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* EXECUTE STORED PROCEDURE */
EXEC TableValuedParameterExample_SP @MyTable
GO

For more details check this link: http://sailajareddy-technical.blogspot.in/2012/09/passing-table-valued-parameter-to.html

Setting focus on an HTML input box on page load

And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.

<input type="text" name="fname" autofocus>

Update select2 data without rebuilding the control

Try this one:

var data = [{id: 1, text: 'First'}, {id: 2, text: 'Second'}, {...}];
$('select[name="my_select"]').empty().select2({
    data: data
});

multiple figure in latex with captions

Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.

\begin{figure}[htp]
  \centering
  \label{figur}\caption{equation...}

  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \\
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \\
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}

\end{figure}

How to compile a 64-bit application using Visual C++ 2010 Express?

And make sure you download the Windows7.1 SDK, not just the Windows 7 one. That caused me a lot of head pounding.

How to convert String to Date value in SAS?

Formats like

date9. 

or

mmddyy10. 

are not valid for input command while converting text to a sas date. You can use

Date = input( cdate , ANYDTDTE11.);

or

Date = input( cdate , ANYDTDTE10.); 

for conversion.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

I logged in using my username instead of email and it started working.

When does a process get SIGABRT (signal 6)?

SIGABRT is commonly used by libc and other libraries to abort the program in case of critical errors. For example, glibc sends an SIGABRT in case of a detected double-free or other heap corruptions.

Also, most assert implementations make use of SIGABRT in case of a failed assert.

Furthermore, SIGABRT can be sent from any other process like any other signal. Of course, the sending process needs to run as same user or root.

How get an apostrophe in a string in javascript

You can use double quotes instead of single quotes:

theAnchorText = "I'm home";

Alternatively, escape the apostrophe:

theAnchorText = 'I\'m home';

The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.

There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

How can I return pivot table output in MySQL?

One option would be combining use of CASE..WHEN statement is redundant within an aggregation for MySQL Database, and considering the needed query generation dynamically along with getting proper column title for the result set as in the following code block :

SET @sql = NULL;

SELECT GROUP_CONCAT(
             CONCAT('SUM( `action` = ''', action, '''',pc0,' ) AS ',action,pc1)
       )
  INTO @sql
  FROM 
  ( 
   SELECT DISTINCT `action`, 
          IF(`pagecount` IS NULL,'',CONCAT('page',`pagecount`)) AS pc1,
          IF(`pagecount` IS NULL,'',CONCAT(' AND `pagecount` = ', pagecount, '')) AS pc0
     FROM `tab` 
    ORDER BY CONCAT(action,pc0) 
  ) t;

SET @sql = CONCAT('SELECT company_name,',@sql,' FROM `tab` GROUP BY company_name'); 
SELECT @sql; 

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Demo

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

There is a way to insert sections in partial views, though it's not pretty. You need to have access to two variables from the parent View. Since part of your partial view's very purpose is to create that section, it makes sense to require these variables.

Here's what it looks like to insert a section in the partial view:

@model KeyValuePair<WebPageBase, HtmlHelper>
@{
    Model.Key.DefineSection("SectionNameGoesHere", () =>
    {
        Model.Value.ViewContext.Writer.Write("Test");
    });
}

And in the page inserting the partial view...

@Html.Partial(new KeyValuePair<WebPageBase, HtmlHelper>(this, Html))

You can also use this technique to define the contents of a section programmatically in any class.

Enjoy!

How can I stop a running MySQL query?

Connect to mysql

mysql -uusername -p  -hhostname

show full processlist:

mysql> show full processlist;
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| Id      | User   | Host              | db      | Command | Time | State | Info             |
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| 9255451 | logreg | dmin001.ops:37651 | logdata | Query   |    0 | NULL  | show processlist |
+---------+--------+-------------------+---------+---------+------+-------+------------------+

Kill the specific query. Here id=9255451

mysql> kill 9255451;

If you get permission denied, try this SQL:

CALL mysql.rds_kill(9255451)

Android, How to create option Menu

Good Day I was checked And if You choose Empty Activity You Don't have build in Menu functions For Build in You must choose Basic Activity In this way You Activity will run onCreateOptionsMenu

Or if You work in Empty Activity from start Chenge in styles.xml the

How to display scroll bar onto a html table

The CSS: div{ overflow-y:scroll; overflow-x:scroll; width:20px; height:30px; } table{ width:50px; height:50px; }

You can make the table and the DIV around the table be any size you want, just make sure that the DIV is smaller than the table. You MUST contain the table inside of the DIV.

Is there any simple way to convert .xls file to .csv file? (Excel)

Checkout the .SaveAs() method in Excel object.

wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)

Or following:

public static void SaveAs()
{
    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
    Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
    Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
    Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];

    Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];

    thisCell.Value2 = "This is a test.";

    wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    wbWorkbook.Close(false, "", true);
}

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

If you really sure that you installed cv2 but it gives no module error. There is a solution for this. Probably you have cv2.so file in your directory

/usr/local/lib/python2.7/site-packages/cv2.so

move this cv2.so file to

/usr/lib/python2.7/site-packages

copy the file into site-packages directory

JavaScript: how to change form action attribute value based on selection?

It's better to use

$('#search-form').setAttribute('action', '/controllerName/actionName');

rather than

$('#search-form').attr('action', '/controllerName/actionName');

So, based on trante's answer we have:

$('#search-form').submit(function() {
    var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
    $("#search-form").setAttribute("action", "/search/" + formAction);
}); 

Using setAttribute can save you a lot of time potentially.

How to merge lists into a list of tuples?

I am not sure if this a pythonic way or not but this seems simple if both lists have the same number of elements :

list_a = [1, 2, 3, 4]

list_b = [5, 6, 7, 8]

list_c=[(list_a[i],list_b[i]) for i in range(0,len(list_a))]

Cluster analysis in R: determine the optimal number of clusters

In order to determine optimal k-cluster in clustering methods. I usually using Elbow method accompany by Parallel processing to avoid time-comsuming. This code can sample like this:

Elbow method

elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}

Running Elbow parallel

no_cores <- detectCores()
    cl<-makeCluster(no_cores)
    clusterEvalQ(cl, library(GMD))
    clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
 start.time <- Sys.time()
 elbow.k.handle(data.clustering))
 k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
    end.time <- Sys.time()
    cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)

It works well.

Serializing class instance to JSON

The basic problem is that the JSON encoder json.dumps() only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders

One good solution would be to make your class inherit from JSONEncoder and then implement the JSONEncoder.default() function, and make that function emit the correct JSON for your class.

A simple solution would be to call json.dumps() on the .__dict__ member of that instance. That is a standard Python dict and if your class is simple it will be JSON serializable.

class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

The above approach is discussed in this blog posting:

    Serializing arbitrary Python objects to JSON using __dict__

How does HttpContext.Current.User.Identity.Name know which usernames exist?

Assume a network environment where a "user" (aka you) has to logon. Usually this is a User ID (UID) and a Password (PW). OK then, what is your Identity, or who are you? You are the UID, and this gleans that "name" from your logon session. Simple! It should also work in an internet application that needs you to login, like Best Buy and others.

This will pull my UID, or "Name", from my session when I open the default page of the web application I need to use. Now, in my instance, I am part of a Domain, so I can use initial Windows authentication, and it needs to verify who I am, thus the 2nd part of the code. As for Forms Authentication, it would rely on the ticket (aka cookie most likely) sent to your workstation/computer. And the code would look like:

string id = HttpContext.Current.User.Identity.Name;

// Strip the domain off of the result
id = id.Substring(id.LastIndexOf(@"\", StringComparison.InvariantCulture) + 1);

Now it has my business name (aka UID) and can display it on the screen.

Cannot use a leading ../ to exit above the top directory

I moved my project from "standard" hosting to Azure and get the same error when I try to open page with url-rewrite. I.e. rule is :

<add key="/iPod-eBook-Creator.html" value="/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR" />

try to open my_site/iPod-eBook-Creator.html and get this error (page my_site/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR can be opened without any problem).

I checked the fully site - never used .. to "level up"

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I used this config:

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v2.0"/>
    <supportedRuntime version="v4.0"/>
</startup>

Worked for me

Python, print all floats to 2 decimal places in output

Format String Syntax.

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

The output would be:

'3.14, kg=6.28, lb=9.42, gal=12.57'

What is the Oracle equivalent of SQL Server's IsNull() function?

Instead of ISNULL(), use NVL().

T-SQL:

SELECT ISNULL(SomeNullableField, 'If null, this value') FROM SomeTable

PL/SQL:

SELECT NVL(SomeNullableField, 'If null, this value') FROM SomeTable

How can I echo HTML in PHP?

This is how I do it:

<?php if($contition == true){ ?>
         <input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
         <p>No input here </p>
<?php } ?>

How to prompt for user input and read command-line arguments

To read user input you can try the cmd module for easily creating a mini-command line interpreter (with help texts and autocompletion) and raw_input (input for Python 3+) for reading a line of text from the user.

text = raw_input("prompt")  # Python 2
text = input("prompt")  # Python 3

Command line inputs are in sys.argv. Try this in your script:

import sys
print (sys.argv)

There are two modules for parsing command line options: optparse (deprecated since Python 2.7, use argparse instead) and getopt. If you just want to input files to your script, behold the power of fileinput.

The Python library reference is your friend.

How to call a vue.js function on page load

If you get data in array you can do like below. It's worked for me

    <template>
    {{ id }}
    </template>
    <script>

    import axios from "axios";

        export default {
            name: 'HelloWorld',
            data () {
                return {
                    id: "",

                }
            },
    mounted() {
                axios({ method: "GET", "url": "https://localhost:42/api/getdata" }).then(result => {
                    console.log(result.data[0].LoginId);
                    this.id = result.data[0].LoginId;
                }, error => {
                    console.error(error);
                });
            },
</script>

Statically rotate font-awesome icons

Before FontAwesome 5:

The standard declarations just contain .fa-rotate-90, .fa-rotate-180 and .fa-rotate-270. However you can easily create your own:

.fa-rotate-45 {
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
}

With FontAwesome 5:

You can use what’s so called “Power Transforms”. Example:

<i class="fas fa-snowman" data-fa-transform="rotate-90"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-180"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-270"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-30"></i>
<i class="fas fa-snowman" data-fa-transform="rotate--30"></i>

You need to add the data-fa-transform attribute with the value of rotate- and your desired rotation in degrees.

Source: https://fontawesome.com/how-to-use/on-the-web/styling/power-transforms

How to use classes from .jar files?

Not every jar file is executable.

Now, you need to import the classes, which are there under the jar, in your java file. For example,

import org.xml.sax.SAXException;

If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.

And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar file, and include all the required jars within that. Then, in order to execute your jar, like,

java -jar my_program.jar

you should have a META-INF/MANIFEST.MF file in your jar. See here, for how-to.

replace NULL with Blank value or Zero in sql server

You should always return the same type on all case condition:

In the first one you have an character and on the else you have an int.

You can use:

Select convert(varchar(11),isnull(totalamount,0))

or if you want with your solution:

Case when total_amount = 0 then '0'   
else convert(varchar(11),isnull(total_amount, 0))  
end as total_amount  

Input button target="_blank" isn't causing the link to load in a new window/tab

Please try this it's working for me

onClick="window.open('http://www.facebook.com/','facebook')"

<button type="button" class="btn btn-default btn-social" onClick="window.open('http://www.facebook.com/','facebook')">
          <i class="fa fa-facebook" aria-hidden="true"></i>
</button>

adding multiple event listeners to one element

You can just define a function and pass it. Anonymous functions are not special in any way, all functions can be passed around as values.

var elem = document.getElementById('first');

elem.addEventListener('touchstart', handler, false);
elem.addEventListener('click', handler, false);

function handler(event) {
    do_something();
}

How to check the exit status using an if statement

Alternative to explicit if statement

Minimally:

test $? -eq 0 || echo "something bad happened"

Complete:

EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened"; 
exit $EXITCODE

How to get your Netbeans project into Eclipse

In Eclipse:

File>Import>General>Existing projects in Workspace

Browse until get the netbeans project folder > Finish

How to detect string which contains only spaces?

The fastest solution would be using the regex prototype function test() and looking for any character that is not a space, tab, or line break \S :

if (!/\S/.test(str)) {
  // Didn't find something other than a space which means it's empty
}

In case you have a super long string, it can make a significant difference as it will stop processing as soon as it finds a non-space character.

Programmatically saving image to Django ImageField

What I did was to create my own storage that will just not save the file to the disk:

from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):

    def _open(self, name, mode='rb'):
        return File(open(self.path(name), mode))

    def _save(self, name, content):
        # here, you should implement how the file is to be saved
        # like on other machines or something, and return the name of the file.
        # In our case, we just return the name, and disable any kind of save
        return name

    def get_available_name(self, name):
        return name

Then, in my models, for my ImageField, I've used the new custom storage:

from custom_storage import CustomStorage

custom_store = CustomStorage()

class Image(models.Model):
    thumb = models.ImageField(storage=custom_store, upload_to='/some/path')

Mysql database sync between two databases

Replication is not very hard to create.

Here's some good tutorials:

http://www.ghacks.net/2009/04/09/set-up-mysql-database-replication/

http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html

http://www.lassosoft.com/Beginners-Guide-to-MySQL-Replication

Here some simple rules you will have to keep in mind (there's more of course but that is the main concept):

  1. Setup 1 server (master) for writing data.
  2. Setup 1 or more servers (slaves) for reading data.

This way, you will avoid errors.

For example: If your script insert into the same tables on both master and slave, you will have duplicate primary key conflict.

You can view the "slave" as a "backup" server which hold the same information as the master but cannot add data directly, only follow what the master server instructions.

NOTE: Of course you can read from the master and you can write to the slave but make sure you don't write to the same tables (master to slave and slave to master).

I would recommend to monitor your servers to make sure everything is fine.

Let me know if you need additional help

How can I pad an int with leading zeros when using cout << operator?

With the following,

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 25;
}

the output will be

00025

setfill is set to the space character (' ') by default. setw sets the width of the field to be printed, and that's it.


If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.

Basic HTTP authentication with Node and Express 4

A lot of the middleware was pulled out of the Express core in v4, and put into separate modules. The basic auth module is here: https://github.com/expressjs/basic-auth-connect

Your example would just need to change to this:

var basicAuth = require('basic-auth-connect');
app.use(basicAuth('username', 'password'));

Pip Install not installing into correct directory?

1 - Something that might work

The pip executable is actually a Python script.

By default it contains (on Linux):

#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==1.5.6','console_scripts','pip'
__requires__ = 'pip==1.5.6'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
    )

So if you got the same in MacOS, pip would always use /usr/bin/python.

But this is a default. You can still provide the version of python you want either by editing the file or by using python explicitly.

If which python returns /usr/bin/python then something went wrong when you installed your own version. If it is /Library/Frameworks/Python.framework/Versions/2.7/bin/python, you can directly call:

sudo python `which pip` install scikit-learn --upgrade

However, chances are high that it won't work. The reason is that sudo is resetting all your environment variables. To make it work, the easiest would be to use:

sudo -E pip install scikit-learn --upgrade

or

sudo -E python `which pip` install scikit-learn --upgrade

depending on your setup.

2 - What you should do

pip was not thought of as something that root should execute. The actual best way to use it is to install a local, non-root, python version. You just have to make sure that you use it by default by setting up the correct environment variables (such as PATH on Linux) and then install pip without sudo using that python version.

An even better way would be to setup virtualenvs from your root install.

This way, you can install/update whatever you want without root privileges and never bother again about why sudo pip is not working. You would also avoid to provide root privileges to whatever is on Pypi and that would warrant that you don't mix system libs with your own.

Global Angular CLI version greater than local version

Two ways to solve this global and local angular CLI version issue.
1. Keep a specific angular-cli version for both environments.
2. Goto latest angular-cli version for both environments.

1. Specific angular-cli version

First, find out which angular version you want to keep on the global and local environment.

ng --version

for example: here we keeping local angular CLI version 8.3.27

So, we have to change the global version also on 8.3.27. use cmd>

npm install --save-dev @angular/[email protected] -g

here, '-g' flag for a set global angular-cli version.

2. Goto latest angular version for both CLI environment.

npm install --save-dev @angular/cli@latest -g  
npm install --save-dev @angular/cli@latest 

How to make an Asynchronous Method return a value?

Probably the simplest way to do it is to create a delegate and then BeginInvoke, followed by a wait at some time in the future, and an EndInvoke.

public bool Foo(){
    Thread.Sleep(100000); // Do work
    return true;
}

public SomeMethod()
{
    var fooCaller = new Func<bool>(Foo);
    // Call the method asynchronously
    var asyncResult = fooCaller.BeginInvoke(null, null);

    // Potentially do other work while the asynchronous method is executing.

    // Finally, wait for result
    asyncResult.AsyncWaitHandle.WaitOne();
    bool fooResult = fooCaller.EndInvoke(asyncResult);

    Console.WriteLine("Foo returned {0}", fooResult);
}

R: "Unary operator error" from multiline ggplot2 command

This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source() a script to when you copy-and-paste the lines, both with multiline and comments)

Rule: always put the dangling '+' at the end of a line so R knows the command is unfinished:

ggplot(...) + geom_whatever1(...) +
  geom_whatever2(...) +
  stat_whatever3(...) +
  geom_title(...) + scale_y_log10(...)

Don't put the dangling '+' at the start of the line, since that tickles the error:

Error in "+ geom_whatever2(...) invalid argument to unary operator"

And obviously don't put dangling '+' at both end and start since that's a syntax error.

So, learn a habit of being consistent: always put '+' at end-of-line.

cf. answer to "Split code over multiple lines in an R script"

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

Git submodule update

To address the --rebase vs. --merge option:

Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling

git submodule update

you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B

cd B
git checkout -b bestIdeaForBEver
<do work>

Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.

<in A>
git merge develop
git submodule update

Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:

git merge develop
git submodule update --rebase

Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'

Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!

(The --merge will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)

How do I ignore files in a directory in Git?

Both examples in the question are actually very bad examples that can lead to data loss!

My advice: never append /* to directories in .gitignore files, unless you have a good reason!

A good reason would be for example what Jefromi wrote: "if you intend to subsequently un-ignore something in the directory".

The reason why it otherwise shouldn't be done is that appending /* to directories does on the one hand work in the manner that it properly ignores all contents of the directory, but on the other hand it has a dangerous side effect:

If you execute git stash -u (to temporarily stash tracked and untracked files) or git clean -df (to delete untracked but keep ignored files) in your repository, all directories that are ignored with an appended /* will be irreversibly deleted!

Some background

I had to learn this the hard way. Somebody in my team was appending /* to some directories in our .gitignore. Over the time I had occasions where certain directories would suddenly disappear. Directories with gigabytes of local data needed by our application. Nobody could explain it and I always hat to re-download all data. After a while I got a notion that it might have to do with git stash. One day I wanted to clean my local repo (while keeping ignored files) and I was using git clean -df and again my data was gone. This time I had enough and investigated the issue. I finally figured that the reason is the appended /*.

I assume it can be explained somehow by the fact that directory/* does ignore all contents of the directory but not the directory itself. Thus it's neither considered tracked nor ignored when things get deleted. Even though git status and git status --ignored give a slightly different picture on it.

How to reproduce

Here is how to reproduce the behaviour. I'm currently using Git 2.8.4.

A directory called localdata/ with a dummy file in it (important.dat) will be created in a local git repository and the contents will be ignored by putting /localdata/* into the .gitignore file. When one of the two mentioned git commands is executed now, the directory will be (unexpectedly) lost.

mkdir test
cd test
git init
echo "/localdata/*" >.gitignore
git add .gitignore
git commit -m "Add .gitignore."
mkdir localdata
echo "Important data" >localdata/important.dat
touch untracked-file

If you do a git status --ignored here, you'll get:

On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

  untracked-file

Ignored files:
  (use "git add -f <file>..." to include in what will be committed)

  localdata/

Now either do

git stash -u
git stash pop

or

git clean -df

In both cases the allegedly ignored directory localdata will be gone!

Not sure if this can be considered a bug, but I guess it's at least a feature that nobody needs.

I'll report that to the git development list and see what they think about it.

jQuery attr('onclick')

Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use

$('#next').die().live('click', stopMoving);

this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.

How to customize listview using baseadapter

I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id/image"
        android:layout_alignParentRight="true"
        android:paddingRight="4dp" />
    <TextView
        android:id="@+id/title"
        android:layout_toLeftOf="@id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="23sp"
        android:maxLines="1" />
    <TextView
        android:id="@+id/subtitle"
        android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 
</RelativeLayout>

Assuming you have a custom class like this

public class CustomClass {

    private long id;
    private String title, subtitle, picture;

    public CustomClass () {
    }

    public CustomClass (long id, String title, String subtitle, String picture) {
        this.id = id;
        this.title= title;
        this.subtitle= subtitle;
        this.picture= picture;
    }
    //add getters and setters
}

And a CustomAdapter.java uses the xml-layout

public class CustomAdapter extends ArrayAdapter {

private Context context;
private int resource;
private LayoutInflater inflater;

public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever

    super(context, R.layout.customlistviewitem, values);

    this.context = context;
    this.resource = R.layout.customlistview;
    this.inflater = LayoutInflater.from(context);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    convertView = (RelativeLayout) inflater.inflate(resource, null);

    CustomClass item = (CustomClass) getItem(position);

    TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
    TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
    ImageView imageview = (ImageView) convertView.findViewById(R.id.image);

    //fill the textviews and imageview with the values
    textviewTitle = item.getTtile();
    textviewSubtitle = item.getSubtitle();

    if (item.getAfbeelding() != null) {
        int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
    }
    imageview.setImageDrawable(image);

    return convertView;
    }
}

Did you manage to do it? Feel free to ask if you want more info on something :)

EDIT: Changed the adapter to suit a List instead of just a List

Check if SQL Connection is Open or Closed

This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

if (_databaseConnection.State == ConnectionState.Closed) {
    _databaseConnection.Open();
}

Golang append an item to a slice

Try this, which I think makes it clear. the underlying array is changed but our slice is not, print just prints len() chars, by another slice to the cap(), you can see the changed array:

func main() {

  for i := 0; i < 7; i++ {
      a[i] = i
  }

  Test(a)

  fmt.Println(a) // prints [0..6]
  fmt.Println(a[:cap(a)] // prints [0..6,100]
}

How to add conditional attribute in Angular 2?

I wanted to have tooltip only for a particular field as added below in code but you want to have tooltip on multiplent you can have an array valdidate using:

Multiple Elements haveing custom data-tooltip attribute:

1: ['key1ToHaveTooltip', `key2ToHaveTooltip'].includes(key)

2: ['key1ToHaveTooltip', 'key2ToHaveTooltip'].indexOf(key) > -1

to have tooltip attribute on more than 1 element.

   <div *ngFor="let key of Keys"
             [attr.data-tooltip]="key === 'IwantOnlyThisKeyToHaveTooltipAttribute' 
                                           ? 'Hey! I am a tooltip on key matched'
                                           : null">
   </div>

Service will not start: error 1067: the process terminated unexpectedly

This is a problem related permission. Make sure that the current user has access to the folder which contains installation files.

Phone number formatting an EditText in Android

There is a library called PhoneNumberUtils that can help you to cope with phone number conversions and comparisons. For instance, use ...

EditText text = (EditText) findViewById(R.id.editTextId);
PhoneNumberUtils.formatNumber(text.getText().toString())

... to format your number in a standard format.

PhoneNumberUtils.compare(String a, String b);

... helps with fuzzy comparisons. There are lots more. Check out http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html for more.

p.s. setting the the EditText to phone is already a good choice; eventually it might be helpful to add digits e.g. in your layout it looks as ...

<EditText
    android:id="@+id/editTextId"
    android:inputType="phone"
    android:digits="0123456789+" 
/> 

How to modify WooCommerce cart, checkout pages (main theme portion)

I used the page-checkout.php template to change the header for my cart page. I renamed it to page-cart.php in my /wp-content/themes/childtheme/woocommerce/. This gives you more control over the wrapping html, header and footer.

CodeIgniter: How to get Controller, Action, URL information

You could use the URI Class:

$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

I've also been told that the following work, but am currently unable to test:

$this->router->fetch_class();
$this->router->fetch_method();

How to find the users list in oracle 11g db?

The command select username from all_users; requires less privileges

Detect network connection type on Android

String active_network = ((ConnectivityManager)
    .getSystemService(Context.CONNECTIVITY_SERVICE))
    .getActiveNetworkInfo().getSubtypeName();

should get you the network name

fatal error: Python.h: No such file or directory

If you are using a Raspberry Pi:

sudo apt-get install python-dev

print arraylist element?

If you want to print an arraylist with integer numbers, as an example you can use below code.

class Test{
    public static void main(String[] args){
        ArrayList<Integer> arraylist = new ArrayList<Integer>();

        for(int i=0; i<=10; i++){
            arraylist .add(i);
        }
       for (Integer n : arraylist ){
            System.out.println(n);
       }
   }
}

The output is above code:

0
1
2
3
4
5
6
7
8
9
10

Failed to authenticate on SMTP server error using gmail

Did you turn on the "Allow less secure apps" on? go to this link

https://myaccount.google.com/security#connectedapps

Take a look at the Sign-in & security -> Apps with account access menu.

You must turn the option "Allow less secure apps" ON.

If is still doesn't work try one of these:

And change your .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls

because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.

Node.js - EJS - including a partial

app.js add

app.set('view engine','ejs')

add your partial file(ejs) in views/partials

in index.ejs

<%- include('partials/header.ejs') %>

#pragma once vs include guards?

I generally don't bother with #pragma once as my code sometimes does have to compile with something other than MSVC or GCC (compilers for embedded systems don't always have the #pragma).

So I have to use #include guards anyway. I could also use #pragma once as some answers suggest, but there doesn't seem to be much reason and it will often cause needless warnings on the compilers that don't support it.

I'm not sure what time savings the pragma might bring. I've heard that compilers generally already recognize when a header has nothing but comments outside of the guard macros and will do the #pragma once equivalent in that case (ie., never processing the file again). But I'm not sure if it's true or just a case of compilers could do this optimization.

In either case, it's just easier for me to use #include guards which will work everywhere and not worry about it further.

Eclipse Bug: Unhandled event loop exception No more handles

I had this issue after installing HP ProtectTools on HP Probook 6470b, because of included Password Manager.

To disable it run "HP ProtectTools Administrative Console", go to "Applications->Settings", open "Applications" tab and uncheck "Status" checkbox.

After PC restart problem should be solved, but you can't use Password Manager anymore :(

How to enable Ad Hoc Distributed Queries

The following command may help you..

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

How to convert string to date to string in Swift iOS?

Swift 2 and below

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 3 and higher this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)

Copy a file from one folder to another using vbscripting

Just posted my finished code for a similar project. It copies files of certain extensions in my code its pdf tif and tiff you can change them to whatever you want copied or delete the if statements if you only need 1 or 2 types. When a file is created or modified it gets the archive attribute this code also looks for that attribute and only copies it if it exists and then removes it after its copied so you dont copy unneeded files. It also has a log setup in it so that you will see a log of what time and day evetrything was transfered from the last time you ran the script. Hope it helps! the link is Error: Object Required; 'objDIR' Code: 800A01A8

Query to convert from datetime to date mysql

syntax of date_format:

SELECT date_format(date_born, '%m/%d/%Y' ) as my_date FROM date_tbl

    '%W %D %M %Y %T'    -> Wednesday 5th May 2004 23:56:25
    '%a %b %e %Y %H:%i' -> Wed May 5 2004 23:56
    '%m/%d/%Y %T'       -> 05/05/2004 23:56:25
    '%d/%m/%Y'          -> 05/05/2004
    '%m-%d-%y'          -> 04-08-13

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

Is it possible to declare two variables of different types in a for loop?

No - but technically there is a work-around (not that i'd actually use it unless forced to):

for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}

WordPress path url in js script file

If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}

How do I change the font-size of an <option> element within <select>?

.service-small option {
    font-size: 14px;
    padding: 5px;
    background: #5c5c5c;
}

I think it because you used .styled-select in start of the class code.

Mock a constructor with parameter

Starting with version 3.5.0 of Mockito and using the InlineMockMaker, you can now mock object constructions:

 try (MockedConstruction mocked = mockConstruction(A.class)) {
   A a = new A();
   when(a.check()).thenReturn("bar");
 }

Inside the try-with-resources construct all object constructions are returning a mock.

How to force file download with PHP

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");

What Language is Used To Develop Using Unity

You can use C#, Javascript, Boo.

Unless computing requirement for the function you write cause heavy load on processor, Javascript gives good enough performance for most cases.

Can I disable a CSS :hover effect via JavaScript?

You can manipulate the stylesheets and stylesheet rules themselves with javascript

var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
    ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
    ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);

Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.

python pandas dataframe columns convert to dict key and value

You can also do this if you want to play around with pandas. However, I like punchagan's way.

# replicating your dataframe
lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'], 
                 'area': [10, 20, 30, 40], 
                 'count': [7, 5, 2, 3]})
lake.set_index('co tp', inplace=True)

# to get key value using pandas
area_dict = lake.set_index('area').T.to_dict('records')[0]
print(area_dict)

output: {10: 7, 20: 5, 30: 2, 40: 3}

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Try this, it must be work, otherwise you need to print the error to specify your problem

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

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

Better late than never!

https://getbootstrap.com/docs/4.5/layout/grid/

<div class="container">
  <div class="row">
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
  </div>
</div>

Android studio Gradle icon error, Manifest Merger

I have same issue , I fix it like this by adding xmlns:tools="http://schemas.android.com/tools" to the top of mainfest file , and add tools:replace="android:icon" to be look like

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"  // add tools line here 
    package="yourpackage">


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon"> ///add this line 

.....

</application>

</manifest>

Ripple effect on Android Lollipop CardView

Add these two like of code work like a charm for any view like Button, Linear Layout, or CardView Just put these two lines and see the magic...

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

How to print Two-Dimensional Array like table

If you don't mind the commas and the brackets you can simply use:

System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));

VBA Subscript out of range - error 9

Option Explicit

Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook


TitleId = 4
Resultid = 0

Dim FileName1, FileName2 As String
Dim Difference As Long



'TestPassCount = 0
'TestFailCount = 0

'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count

If (TestDataRowCount <= 2) Then
  MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
  For RecordId = 3 To TestDataRowCount
    RefreshResultSheet

    'Source File row count
    SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
    Set sourcewb = Workbooks.Open(SrceFile)
    With sourcewb.Worksheets(1)
      SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      sourcewb.Close
    End With

    'Target File row count
    TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
    Set targetwb = Workbooks.Open(TrgtFile)
    With targetwb.Worksheets(1)
      TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      targetwb.Close
    End With

    ' Set Row Count Result Test data value
    TitleId = TitleId + 3
    Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value

    'Compare Source and Target Row count
    Resultid = TitleId + 1
    Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
    If (SourceRowCount = TargetRowCount) Then
       Worksheets("Result").Range("B" & Resultid).Value = "Passed"
       Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
       TestPassCount = TestPassCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Failed"
      Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
      TestFailCount = TestFailCount + 1
    End If


    'For comparison of two files

    FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
    FileName2 = Worksheets("TestData").Range("E" & RecordId).Value

    Set myWorkbook1 = Workbooks.Open(FileName1)
    Set myWorkbook2 = Workbooks.Open(FileName2)

    Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
    myWorkbook1.Close
    myWorkbook2.Close


    'MsgBox Difference

    'Set Result of data validation in result sheet
    Resultid = Resultid + 1

    Worksheets("Result").Activate
    Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"

    If Difference > 0 Then
        Worksheets("Result").Range("B" & Resultid).Value = "Failed"
        Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
        TestFailCount = TestFailCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Passed"
      Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
      TestPassCount = TestPassCount + 1
    End If


  Next RecordId
End If

UpdateTestExecData TestPassCount, TestFailCount
End Sub

Sub RefreshResultSheet()
  Worksheets("Result").Activate
  Worksheets("Result").Range("B1:B4").Select
  Selection.ClearContents
  Worksheets("Result").Range("D1:D4").Select
  Selection.ClearContents
  Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
  Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
  Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
  Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub

Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
  Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
  Worksheets("Result").Range("D2").Value = TestPassCount
  Worksheets("Result").Range("D3").Value = TestFailCount
  Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub

Background blur with CSS

You could make it through iframes... I made something, but my only problem for now is syncing those divs to scroll simultaneous... its terrible way, because its like you load 2 websites, but the only way I found... you could also work with divs and overflow I guess...

Bootstrap - floating navbar button right

You would need to use the following markup. If you want to float any menu items to the right, create a separate <ul class="nav navbar-nav"> with navbar-right class to it.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
    <div class="container">_x000D_
      <div class="navbar-header">_x000D_
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
            <span class="sr-only">Toggle navigation</span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
          </button>_x000D_
        <a class="navbar-brand" href="#">Project name</a>_x000D_
      </div>_x000D_
      <div class="collapse navbar-collapse">_x000D_
        <ul class="nav navbar-nav">_x000D_
          <li class="active"><a href="#">Home</a></li>_x000D_
          <li><a href="#about">About</a></li>_x000D_
_x000D_
        </ul>_x000D_
        <ul class="nav navbar-nav navbar-right">_x000D_
          <li><a href="#contact">Contact</a></li>_x000D_
        </ul>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Multiple Buttons' OnClickListener() android

You can use this

    TextView output = (TextView) findViewById(R.id.output);
    one.setOnClickListener(youractivity.this);
    // set the onclicklistener for other buttons also

    @Override
    public void onClick(View v) {
      int id = v.getId();
    switch(id) {
    case R.id.oneButton:      
       append("1",output);
       break;
    case R.id.twoButton:
        append("2",output);
       break;
    case R.id.threeButton:
        append("3",output);
       break;
     } 
      }

 private void append(String s,TextView t){
  t.setText(s); 
}

you can identify the views in your activity in a separate method.

How to load npm modules in AWS Lambda?

You can now use Lambda Layers for this matters. Simply add a layer containing the package you need and it will run perfectly.

Follow this post: https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e

How to compare two dates?

Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True

Given final block not properly padded

depending on the cryptography algorithm you are using, you may have to add some padding bytes at the end before encrypting a byte array so that the length of the byte array is multiple of the block size:

Specifically in your case the padding schema you chose is PKCS5 which is described here: http://www.rsa.com/products/bsafe/documentation/cryptoj35html/doc/dev_guide/group_CJ_SYM__PAD.html

(I assume you have the issue when you try to encrypt)

You can choose your padding schema when you instantiate the Cipher object. Supported values depend on the security provider you are using.

By the way are you sure you want to use a symmetric encryption mechanism to encrypt passwords? Wouldn't be a one way hash better? If you really need to be able to decrypt passwords, DES is quite a weak solution, you may be interested in using something stronger like AES if you need to stay with a symmetric algorithm.

if else in a list comprehension

Here is another illustrative example:

>>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
Ha, ha, ha!

It exploits the fact that if i evaluates to False for 0 and to True for all other values generated by the function range(). Therefore the list comprehension evaluates as follows:

>>> ["ha" if i else "Ha" for i in range(3)]
['Ha', 'ha', 'ha']

Capture key press (or keydown) event on DIV element

Here example on plain JS:

_x000D_
_x000D_
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
  console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
  outline: none;_x000D_
}
_x000D_
<div _x000D_
  id="myDiv"_x000D_
  tabindex="0"_x000D_
>_x000D_
  Press me and start typing_x000D_
</div>
_x000D_
_x000D_
_x000D_

Make a div fill up the remaining width

The Div that has to take the remaining space has to be a class.. The other divs can be id(s) but they must have width..

CSS:

#main_center {
    width:1000px;
    height:100px;
    padding:0px 0px;
    margin:0px auto;
    display:block;
}
#left {
    width:200px;
    height:100px;
    padding:0px 0px;
    margin:0px auto;
    background:#c6f5c6;
    float:left;
}
.right {
    height:100px;
    padding:0px 0px;
    margin:0px auto;
    overflow:hidden;
    background:#000fff;
}
.clear {
    clear:both;
}

HTML:

<body>
    <div id="main_center">
        <div id="left"></div>
        <div class="right"></div>
        <div class="clear"></div>
    </div>
</body>

The following link has the code in action, which should solve the remaining area coverage issue.

jsFiddle

Use latest version of Internet Explorer in the webbrowser control

I saw Veer's answer. I think it's right, but it did not I work for me. Maybe I am using .NET 4 and am using 64x OS so kindly check this.

You may put in setup or check it in start-up of your application:

private void Form1_Load(object sender, EventArgs e)
{
    var appName = Process.GetCurrentProcess().ProcessName + ".exe";
    SetIE8KeyforWebBrowserControl(appName);
}

private void SetIE8KeyforWebBrowserControl(string appName)
{
    RegistryKey Regkey = null;
    try
    {
        // For 64 bit machine
        if (Environment.Is64BitOperatingSystem)
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
        else  //For 32 bit machine
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

        // If the path is not correct or
        // if the user haven't priviledges to access the registry
        if (Regkey == null)
        {
            MessageBox.Show("Application Settings Failed - Address Not found");
            return;
        }

        string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        // Check if key is already present
        if (FindAppkey == "8000")
        {
            MessageBox.Show("Required Application Settings Present");
            Regkey.Close();
            return;
        }

        // If a key is not present add the key, Key value 8000 (decimal)
        if (string.IsNullOrEmpty(FindAppkey))
            Regkey.SetValue(appName, unchecked((int)0x1F40), RegistryValueKind.DWord);

        // Check for the key after adding
        FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        if (FindAppkey == "8000")
            MessageBox.Show("Application Settings Applied Successfully");
        else
            MessageBox.Show("Application Settings Failed, Ref: " + FindAppkey);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Application Settings Failed");
        MessageBox.Show(ex.Message);
    }
    finally
    {
        // Close the Registry
        if (Regkey != null)
            Regkey.Close();
    }
}

You may find messagebox.show, just for testing.

Keys are as the following:

  • 11001 (0x2AF9) - Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.

  • 11000 (0x2AF8) - Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.

  • 10001 (0x2711)- Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.

  • 10000 (0x2710)- Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.

  • 9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.

  • 9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

  • 8888 (0x22B8) - Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.

  • 8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.

  • 7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

Reference: MSDN: Internet Feature Controls

I saw applications like Skype use 10001. I do not know.

NOTE

The setup application will change the registry. You may need to add a line in the Manifest File to avoid errors due to permissions of change in registry:

<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

UPDATE 1

This is a class will get the latest version of IE on windows and make changes as should be;

public class WebBrowserHelper
{


    public static int GetEmbVersion()
    {
        int ieVer = GetBrowserVersion();

        if (ieVer > 9)
            return ieVer * 1000 + 1;

        if (ieVer > 7)
            return ieVer * 1111;

        return 7000;
    } // End Function GetEmbVersion

    public static void FixBrowserVersion()
    {
        string appName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
        FixBrowserVersion(appName);
    }

    public static void FixBrowserVersion(string appName)
    {
        FixBrowserVersion(appName, GetEmbVersion());
    } // End Sub FixBrowserVersion

    // FixBrowserVersion("<YourAppName>", 9000);
    public static void FixBrowserVersion(string appName, int ieVer)
    {
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".vshost.exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".vshost.exe", ieVer);
    } // End Sub FixBrowserVersion 

    private static void FixBrowserVersion_Internal(string root, string appName, int ieVer)
    {
        try
        {
            //For 64 bit Machine 
            if (Environment.Is64BitOperatingSystem)
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);
            else  //For 32 bit Machine 
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);


        }
        catch (Exception)
        {
            // some config will hit access rights exceptions
            // this is why we try with both LOCAL_MACHINE and CURRENT_USER
        }
    } // End Sub FixBrowserVersion_Internal 

    public static int GetBrowserVersion()
    {
        // string strKeyPath = @"HKLM\SOFTWARE\Microsoft\Internet Explorer";
        string strKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer";
        string[] ls = new string[] { "svcVersion", "svcUpdateVersion", "Version", "W2kVersion" };

        int maxVer = 0;
        for (int i = 0; i < ls.Length; ++i)
        {
            object objVal = Microsoft.Win32.Registry.GetValue(strKeyPath, ls[i], "0");
            string strVal = System.Convert.ToString(objVal);
            if (strVal != null)
            {
                int iPos = strVal.IndexOf('.');
                if (iPos > 0)
                    strVal = strVal.Substring(0, iPos);

                int res = 0;
                if (int.TryParse(strVal, out res))
                    maxVer = Math.Max(maxVer, res);
            } // End if (strVal != null)

        } // Next i

        return maxVer;
    } // End Function GetBrowserVersion 


}

using of class as followed

WebBrowserHelper.FixBrowserVersion();
WebBrowserHelper.FixBrowserVersion("SomeAppName");
WebBrowserHelper.FixBrowserVersion("SomeAppName",intIeVer);

you may face a problem for in comparability of windows 10, may due to your website itself you may need to add this meta tag

<meta http-equiv="X-UA-Compatible" content="IE=11" >

Enjoy :)

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

How can I drop a table if there is a foreign key constraint in SQL Server?

1-firstly, drop the foreign key constraint after that drop the tables.

2-you can drop all foreign key via executing the following query:

DECLARE @SQL varchar(4000)=''
SELECT @SQL = 
@SQL + 'ALTER TABLE ' + s.name+'.'+t.name + ' DROP CONSTRAINT [' + RTRIM(f.name) +'];' + CHAR(13)
FROM sys.Tables t
INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id
INNER JOIN sys.schemas     s ON s.schema_id = f.schema_id

--EXEC (@SQL)

PRINT @SQL

if you execute the printed results @SQL, the foreign keys will be dropped.

The project cannot be built until the build path errors are resolved.

Go to > Right CLick on your project folder > Build Path > Configure Build Path > Libraries Tab > remove project and external dependencies > apply & close

Now, Gradle refresh your project.

Mean filter for smoothing images in Matlab

and the convolution is defined through a multiplication in transform domain:

conv2(x,y) = fftshift(ifft2(fft2(x).*fft2(y)))

if one channel is considered... for more channels this has to be done every channel

How to remove square brackets in string using regex?

here you go

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

How to properly use unit-testing's assertRaises() with NoneType objects?

If you are using python2.7 or above you can use the ability of assertRaises to be use as a context manager and do:

with self.assertRaises(TypeError):
    self.testListNone[:1]

If you are using python2.6 another way beside the one given until now is to use unittest2 which is a back port of unittest new feature to python2.6, and you can make it work using the code above.

N.B: I'm a big fan of the new feature (SkipTest, test discovery ...) of unittest so I intend to use unittest2 as much as I can. I advise to do the same because there is a lot more than what unittest come with in python2.6 <.

How to globally replace a forward slash in a JavaScript string?

Without using regex (though I would only do this if the search string is user input):

var str = 'Hello/ world/ this has two slashes!';
alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!' 

How to embed new Youtube's live video permanent URL?

Here's how to do it in Squarespace using the embed block classes to create responsiveness.

Put this into a code block:

<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
    <div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
        <div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
            <iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
            </iframe>
        </div>
    </div>
</div>

Tweak however you'd like!

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

How can I add an item to a IEnumerable<T> collection?

you can do this.

//Create IEnumerable    
IEnumerable<T> items = new T[]{new T("msg")};

//Convert to list.
List<T> list = items.ToList();

//Add new item to list.
list.add(new T("msg2"));

//Cast list to IEnumerable
items = (IEnumerable<T>)items;

ValueError: Wrong number of items passed - Meaning and suggestions?

In general, the error ValueError: Wrong number of items passed 3, placement implies 1 suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation

results['predictedY'] = predictedY

is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.

Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess() is coming from (I'm guessing, but correct me and revise the question if this is wrong).

Now, you generate predicted values for y here:

predictedY, MSE = gp.predict(testX, eval_MSE = True)

However, as we can see from the documentation for GaussianProcess, predict() returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets) which, depending on testX, could be (1000, 3) (just to pick numbers). Thus, your predictedY might have 3 columns.

If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

Scanner is never closed

Here is some better usage of java for scanner

try(Scanner sc = new Scanner(System.in)) {

    //Use sc as you need

} catch (Exception e) {

        //  handle exception

}

How to disable a input in angular2

A note in response to Belter's comment on fedtuck's accepted answer above, since I lack the reputation to add comments.

This is not true for any of which I am aware, in line with the Mozilla docs

disabled equals to true or false

When the disabled attribute is present the element is disabled regardless of value. See this example

<input placeholder="i can be changed"/>
<input disabled placeholder="i can NOT be changed"/>
<input disabled="true" placeholder="i can NOT be changed"/>
<input disabled="false" placeholder="i can NOT be changed"/>

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

First verify which version of microsoft.ace.oledb.12.0 is installed in your system.

Check in below path C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL --64 bit is installed

Check in below path C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL --x86 bit is installed

If (x86) is installed then using configuration manager change solution platform to x86, for x64 change to x64.

If not available then install using below link

https://www.microsoft.com/en-us/download/details.aspx?id=23734

How to invoke the super constructor in Python?

In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

Python-2.x

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(B, self).__init__()

Python-3.x

class A(object):
 def __init__(self):
   print("world")

class B(A):
 def __init__(self):
   print("hello")
   super().__init__()

super() is now equivalent to super(<containing classname>, self) as per the docs.

add column to mysql table if it does not exist

Just tried the stored procedure script. Seems the problem is the ' marks around the delimiters. The MySQL Docs show that delimiter characters do not need the single quotes.

So you want:

delimiter //

Instead of:

delimiter '//'

Works for me :)

What does "implements" do on a class?

You should look into Java's interfaces. A quick Google search revealed this page, which looks pretty good.

I like to think of an interface as a "promise" of sorts: Any class that implements it has certain behavior that can be expected of it, and therefore you can put an instance of an implementing class into an interface-type reference.

A simple example is the java.lang.Comparable interface. By implementing all methods in this interface in your own class, you are claiming that your objects are "comparable" to one another, and can be partially ordered.

Implementing an interface requires two steps:

  1. Declaring that the interface is implemented in the class declaration
  2. Providing definitions for ALL methods that are part of the interface.

Interface java.lang.Comparable has just one method in it, public int compareTo(Object other). So you need to provide that method.

Here's an example. Given this class RationalNumber:

public class RationalNumber
{
    public int numerator;
    public int denominator;

    public RationalNumber(int num, int den)
    {
        this.numerator = num;
        this.denominator = den;
    }
}

(Note: It's generally bad practice in Java to have public fields, but I am intending this to be a very simple plain-old-data type so I don't care about public fields!)

If I want to be able to compare two RationalNumber instances (for sorting purposes, maybe?), I can do that by implementing the java.lang.Comparable interface. In order to do that, two things need to be done: provide a definition for compareTo and declare that the interface is implemented.

Here's how the fleshed-out class might look:

public class RationalNumber implements java.lang.Comparable
{
    public int numerator;
    public int denominator;

    public RationalNumber(int num, int den)
    {
        this.numerator = num;
        this.denominator = den;
    }

    public int compareTo(Object other)
    {
        if (other == null || !(other instanceof RationalNumber))
        {
            return -1; // Put this object before non-RationalNumber objects
        }

        RationalNumber r = (RationalNumber)other;

        // Do the calculations by cross-multiplying. This isn't really important to
        // the answer, but the point is we're comparing the two rational numbers.
        // And no, I don't care if it's mathematically inaccurate.

        int myTotal = this.numerator * other.denominator;
        int theirTotal = other.numerator * this.denominator;

        if (myTotal < theirTotal) return -1;
        if (myTotal > theirTotal) return 1;
        return 0;
    }
}

You're probably thinking, what was the point of all this? The answer is when you look at methods like this: sorting algorithms that just expect "some kind of comparable object". (Note the requirement that all objects must implement java.lang.Comparable!) That method can take lists of ANY kind of comparable objects, be they Strings or Integers or RationalNumbers.

NOTE: I'm using practices from Java 1.4 in this answer. java.lang.Comparable is now a generic interface, but I don't have time to explain generics.

Adding Lombok plugin to IntelliJ project

You need to Enable Annotation Processing on IntelliJ IDEA

> Settings > Build, Execution, Deployment > Compiler > Annotation Processors

enter image description here

Referencing value in a closed Excel workbook using INDIRECT?

The problem is that a link to a closed file works with index( but not with index(indirect(

It seems to me that it is a programming issue of the index function. I solved it with a if clause row

C2=sheetname
if(c2=Sheet1,index(sheet1....),if(C2="Sheet2",index(sheet2....

I did it over five sheets, it's a long formula, but does what I need.

How to send email in ASP.NET C#

This is the easiest script to test.

<%@ Import Namespace="System.Net" %> 
<%@ Import Namespace="System.Net.Mail" %> 

<script language="C#" runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
       //create the mail message 
        MailMessage mail = new MailMessage(); 

        //set the addresses 
        mail.From = new MailAddress("From email account"); 
        mail.To.Add("To email account"); 

        //set the content 
        mail.Subject = "This is a test email from C# script"; 
        mail.Body = "This is a test email from C# script"; 
        //send the message 
         SmtpClient smtp = new SmtpClient("mail.domainname.com"); 

         NetworkCredential Credentials = new NetworkCredential("to email account", "Password"); 
         smtp.Credentials = Credentials;
         smtp.Send(mail); 
         lblMessage.Text = "Mail Sent"; 
    } 
</script> 
<html> 
<body> 
    <form runat="server"> 
        <asp:Label id="lblMessage" runat="server"></asp:Label> 
    </form> 
</body>

How to add pandas data to an existing csv file?

A little helper function I use with some header checking safeguards to handle it all:

def appendDFToCSV_void(df, csvFilePath, sep=","):
    import os
    if not os.path.isfile(csvFilePath):
        df.to_csv(csvFilePath, mode='a', index=False, sep=sep)
    elif len(df.columns) != len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns):
        raise Exception("Columns do not match!! Dataframe has " + str(len(df.columns)) + " columns. CSV file has " + str(len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns)) + " columns.")
    elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all():
        raise Exception("Columns and column order of dataframe and csv file do not match!!")
    else:
        df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False)

/usr/bin/ld: cannot find

@Alwin Doss You should provide the -L option before -l. You would have done the other way round probably. Try this :)

Android. Fragment getActivity() sometimes returns null

In Kotlin you can try this way to handle getActivity() null condition.

   activity.let { // activity == getActivity() in java

        //your code here

   }

It will check activity is null or not and if not null then execute inner code.

How to change an element's title attribute using jQuery

If you are creating a div and trying to add a title to it.

Try

var myDiv= document.createElement("div");
myDiv.setAttribute('title','mytitle');

Warning: Found conflicts between different versions of the same dependent assembly

Here's the solution, .NET Core 3.0 style: https://github.com/HTD/ref-check

When you find what conflicts, maybe you would be able to resolve the conflicts. If the conflicting references are from other packages, you either out of luck, or you need to use sources instead.

In my case, the packages conflicting are often of my own, so I can fix dependency problems and republish them.

How to split a String by space

An alternative way would be:

import java.util.regex.Pattern;

...

private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split

Saw it here

How to get .app file of a xcode application

Under Xcode 4.5.2, you can find the .app file in this way:

  1. Select Window > Organizer in the Xcode's menu(or just press 'Shift+Command+2')
  2. Select your project on the left side of Organizer, and you will find the Derived Data path on the right side. Just click the mini arrow in the end of the path, this will open Finder at the path.
  3. In the Finder, click "Build > Products > Release", you will find the .app.

WPF User Control Parent

I've found that the parent of a UserControl is always null in the constructor, but in any event handlers the parent is set correctly. I guess it must have something to do with the way the control tree is loaded. So to get around this you can just get the parent in the controls Loaded event.

For an example checkout this question WPF User Control's DataContext is Null

How to position a div scrollbar on the left hand side?

Kind of an old question, but I thought I should throw in a method which wasn't widely available when this question was asked.

You can reverse the side of the scrollbar in modern browsers using transform: scaleX(-1) on a parent <div>, then apply the same transform to reverse a child, "sleeve" element.

HTML

<div class="parent">
  <div class="sleeve">
    <!-- content -->
  </div>
</div>

CSS

.parent {
  overflow: auto;
  transform: scaleX(-1); //Reflects the parent horizontally
}

.sleeve {
  transform: scaleX(-1); //Flips the child back to normal
}

Note: You may need to use an -ms-transform or -webkit-transform prefix for browsers as old as IE 9. Check CanIUse and click "show all" to see older browser requirements.

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with /> at the end. In React, we have to close every element. Your code should be:

<input id="icon_prefix" type="text" class="validate/">

Best way to check if object exists in Entity Framework?

From a performance point of view, I guess that a direct SQL query using the EXISTS command would be appropriate. See here for how to execute SQL directly in Entity Framework: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx

Android camera android.hardware.Camera deprecated

Now we have to use android.hardware.camera2 as android.hardware.Camera is deprecated which will only work on API >23 FlashLight

   public class MainActivity extends AppCompatActivity {

     Button button;

     Boolean light=true;

     CameraDevice cameraDevice;

     private CameraManager cameraManager;

     private CameraCharacteristics cameraCharacteristics;

     String cameraId;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);
        cameraManager = (CameraManager) 
        getSystemService(Context.CAMERA_SERVICE);
        try {
          cameraId = cameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(light){
                    try {

                        cameraManager.setTorchMode(cameraId,true);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }

                    light=false;}
                    else {

                    try {

                      cameraManager.setTorchMode(cameraId,false);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }


                    light=true;
                    }


            }
        });
    }
}

How can I get the current date and time in UTC or GMT in Java?

This worked for me, returns the timestamp in GMT!

    Date currDate;
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    long currTime = 0;
    try {

        currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
        currTime = currDate.getTime();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

C++ equivalent of Java's toString?

The question has been answered. But I wanted to add a concrete example.

class Point{

public:
      Point(int theX, int theY) :x(theX), y(theY)
      {}
      // Print the object
      friend ostream& operator <<(ostream& outputStream, const Point& p);
private:
      int x;
      int y;
};

ostream& operator <<(ostream& outputStream, const Point& p){
       int posX = p.x;
       int posY = p.y;

       outputStream << "x="<<posX<<","<<"y="<<posY;
      return outputStream;
}

This example requires understanding operator overload.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

How can building a heap be O(n) time complexity?

Lets suppose you have N elements in a heap. Then its height would be Log(N)

Now you want to insert another element, then the complexity would be : Log(N), we have to compare all the way UP to the root.

Now you are having N+1 elements & height = Log(N+1)

Using induction technique it can be proved that the complexity of insertion would be ?logi.

Now using

log a + log b = log ab

This simplifies to : ?logi=log(n!)

which is actually O(NlogN)

But

we are doing something wrong here, as in all the case we do not reach at the top. Hence while executing most of the times we may find that, we are not going even half way up the tree. Whence, this bound can be optimized to have another tighter bound by using mathematics given in answers above.

This realization came to me after a detail though & experimentation on Heaps.

How to find out when a particular table was created in Oracle?

You copy and paste the following code. It will display all the tables with Name and Created Date

SELECT object_name,created FROM user_objects
WHERE object_name LIKE  '%table_name%'
AND object_type = 'TABLE'; 

Note: Replace '%table_name%' with the table name you are looking for.

Use FontAwesome or Glyphicons with css :before

What you are describing is actually what FontAwesome is doing already. They apply the FontAwesome font-family to the ::before pseudo element of any element that has a class that starts with "icon-".

[class^="icon-"]:before,
[class*=" icon-"]:before {
  font-family: FontAwesome;
  font-weight: normal;
  font-style: normal;
  display: inline-block;
  text-decoration: inherit;
}

Then they use the pseudo element ::before to place the icon in the element with the class. I just went to http://fortawesome.github.com/Font-Awesome/ and inspected the code to find this:

.icon-cut:before {
  content: "\f0c4";
}

So if you are looking to add the icon again, you could use the ::after element to achieve this. Or for your second part of your question, you could use the ::after pseudo element to insert the bullet character to look like a list item. Then use absolute positioning to place it to the left, or something similar.

i:after{ content: '\2022';}

SimpleXml to string

Sometimes you can simply typecast:

// this is the value of my $xml
object(SimpleXMLElement)#10227 (1) {
  [0]=>
  string(2) "en"
}

$s = (string) $xml; // returns "en";

Use multiple css stylesheets in the same html page

Yes, you can include multiple style sheets, but you need to label them as alternate style sheets and give the user some way to activate them using JavaScript - perhaps by clicking a link.

To create an alternate style sheet:

<link type="text/css" href="nameOfAlterateStyleSheet.css" rel="alternate stylesheet" title="Blue" />

Next create a method in your Javascript file that will: 1. Load all the style sheets in an array 2. Example:

function getCSSArray()
{
var links = document.getElementsByTagName("link");
var link;
for(var i = 0; i < links.length; i++)
{
    link = links[i];
    if(/stylesheet/.test(link.rel))
    {
        sheets.push(link);
    }
}

    return sheets;
}

Then go through the array using some type of if/else loop that disables the style sheets you don't want and enables the style sheet you want. (You can write a separate method or insert the loop into the method above. I like to use the onload command to load the CSS array with the page, then call the printView method.)

function printView()
{
var sheet;
var title1 = "printVersion";
for(i = 0; i < sheets.length; i++)
{
    sheet = sheets[i];
            if(sheet.title == title1)
    {
        sheet.disabled = false;
    }
    else
    {
        sheet.disabled = true;
    }

Lastly, create code in your HTML document that the user will activate the JavaScript method such as:

 <a href="#" onClick ="methodName();">Link Name</a>

LINQ's Distinct() on a particular property

When we faced such a task in our project we defined a small API to compose comparators.

So, the use case was like this:

var wordComparer = KeyEqualityComparer.Null<Word>().
    ThenBy(item => item.Text).
    ThenBy(item => item.LangID);
...
source.Select(...).Distinct(wordComparer);

And API itself looks like this:

using System;
using System.Collections;
using System.Collections.Generic;

public static class KeyEqualityComparer
{
    public static IEqualityComparer<T> Null<T>()
    {
        return null;
    }

    public static IEqualityComparer<T> EqualityComparerBy<T, K>(
        this IEnumerable<T> source,
        Func<T, K> keyFunc)
    {
        return new KeyEqualityComparer<T, K>(keyFunc);
    }

    public static KeyEqualityComparer<T, K> ThenBy<T, K>(
        this IEqualityComparer<T> equalityComparer,
        Func<T, K> keyFunc)
    {
        return new KeyEqualityComparer<T, K>(keyFunc, equalityComparer);
    }
}

public struct KeyEqualityComparer<T, K>: IEqualityComparer<T>
{
    public KeyEqualityComparer(
        Func<T, K> keyFunc,
        IEqualityComparer<T> equalityComparer = null)
    {
        KeyFunc = keyFunc;
        EqualityComparer = equalityComparer;
    }

    public bool Equals(T x, T y)
    {
        return ((EqualityComparer == null) || EqualityComparer.Equals(x, y)) &&
                EqualityComparer<K>.Default.Equals(KeyFunc(x), KeyFunc(y));
    }

    public int GetHashCode(T obj)
    {
        var hash = EqualityComparer<K>.Default.GetHashCode(KeyFunc(obj));

        if (EqualityComparer != null)
        {
            var hash2 = EqualityComparer.GetHashCode(obj);

            hash ^= (hash2 << 5) + hash2;
        }

        return hash;
    }

    public readonly Func<T, K> KeyFunc;
    public readonly IEqualityComparer<T> EqualityComparer;
}

More details is on our site: IEqualityComparer in LINQ.

Select2() is not a function

Add $("#id").select2() out of document.ready() function.

MVC controller : get JSON object from HTTP body?

use Request.Form to get the Data

Controller:

    [HttpPost]
    public ActionResult Index(int? id)
    {
        string jsonData= Request.Form[0]; // The data from the POST
    }

I write this to try

View:

<input type="button" value="post" id="btnPost" />

<script type="text/javascript">
    $(function () {
        var test = {
            number: 456,
            name: "Ryu"
        }
        $("#btnPost").click(function () {
            $.post('@Url.Action("Index", "Home")', JSON.stringify(test));
        });
    });
</script>

and write Request.Form[0] or Request.Params[0] in controller can get the data.

I don't write <form> tag in view.

How to scale down a range of numbers with a known min and max value

I came across this solution but this does not really fit my need. So I digged a bit in the d3 source code. I personally would recommend to do it like d3.scale does.

So here you scale the domain to the range. The advantage is that you can flip signs to your target range. This is useful since the y axis on a computer screen goes top down so large values have a small y.

public class Rescale {
    private final double range0,range1,domain0,domain1;

    public Rescale(double domain0, double domain1, double range0, double range1) {
        this.range0 = range0;
        this.range1 = range1;
        this.domain0 = domain0;
        this.domain1 = domain1;
    }

    private double interpolate(double x) {
        return range0 * (1 - x) + range1 * x;
    }

    private double uninterpolate(double x) {
        double b = (domain1 - domain0) != 0 ? domain1 - domain0 : 1 / domain1;
        return (x - domain0) / b;
    }

    public double rescale(double x) {
        return interpolate(uninterpolate(x));
    }
}

And here is the test where you can see what I mean

public class RescaleTest {

    @Test
    public void testRescale() {
        Rescale r;
        r = new Rescale(5,7,0,1);
        Assert.assertTrue(r.rescale(5) == 0);
        Assert.assertTrue(r.rescale(6) == 0.5);
        Assert.assertTrue(r.rescale(7) == 1);

        r = new Rescale(5,7,1,0);
        Assert.assertTrue(r.rescale(5) == 1);
        Assert.assertTrue(r.rescale(6) == 0.5);
        Assert.assertTrue(r.rescale(7) == 0);

        r = new Rescale(-3,3,0,1);
        Assert.assertTrue(r.rescale(-3) == 0);
        Assert.assertTrue(r.rescale(0) == 0.5);
        Assert.assertTrue(r.rescale(3) == 1);

        r = new Rescale(-3,3,-1,1);
        Assert.assertTrue(r.rescale(-3) == -1);
        Assert.assertTrue(r.rescale(0) == 0);
        Assert.assertTrue(r.rescale(3) == 1);
    }
}

Hadoop/Hive : Loading data from .csv on a local machine

For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE 
'org.apache.hadoop.hive.serde2.OpenCSVSerde' 
STORED AS TEXTFILE ;