Programs & Examples On #Jini

jini (aka Apache River) is a SOA programming model that extends Java to create secure distributed systems consisting of clients and services. It allows for advanced distributed operations such as dynamic discovery, mobile code, and service groups (called federations).

Entity Framework The underlying provider failed on Open

Seems like a connection issue. You can use the Data link properties to find if the connection is fine. Do the following:

  1. Create a blank notepad and rename it to "X.UDL"
  2. Double click to open it
  3. Under connections tab choose the server name/enter the name use the correct credentials and DB
  4. Click OK to save it.

Now open the file in Notepad and compare the connection string properties.

pycharm running way slow

Every performance problem with PyCharm is unique, a solution that helps to one person will not work for another. The only proper way to fix your specific performance problem is by capturing the CPU profiler snapshot as described in this document and sending it to PyCharm support team, either by submitting a ticket or directly into the issue tracker.

After the CPU snapshot is analyzed, PyCharm team will work on a fix and release a new version which will (hopefully) not be affected by this specific performance problem. The team may also suggest you some configuration change or workaround to remedy the problem based on the analysis of the provided data.

All the other "solutions" (like enabling Power Save mode and changing the highlighting level) will just hide the real problems that should be fixed.

position: fixed doesn't work on iPad and iPhone

The simple way to fix this problem just types transform property for your element. and it will be fixed. Happy Coding :-)

.classname{
  position: fixed;
  transform: translate3d(0,0,0);
}

Also you can try his way as well this is also work fine.

.classname{
      position: -webkit-sticky;
    }

UTF-8: General? Bin? Unicode?

  • utf8_bin compares the bits blindly. No case folding, no accent stripping.
  • utf8_general_ci compares one byte with one byte. It does case folding and accent stripping, but no 2-character comparisions: ij is not equal ? in this collation.
  • utf8_*_ci is a set of language-specific rules, but otherwise like unicode_ci. Some special cases: Ç, C, ch, ll
  • utf8_unicode_ci follows an old Unicode standard for comparisons. ij=?, but ae != æ
  • utf8_unicode_520_ci follows an newer Unicode standard. ae = æ

See collation chart for details on what is equal to what in various utf8 collations.

utf8, as defined by MySQL is limited to the 1- to 3-byte utf8 codes. This leaves out Emoji and some of Chinese. So you should really switch to utf8mb4 if you want to go much beyond Europe.

The above points apply to utf8mb4, after suitable spelling change. Going forward, utf8mb4 and utf8mb4_unicode_520_ci are preferred.

  • utf16 and utf32 are variants on utf8; there is virtually no use for them.
  • ucs2 is closer to "Unicode" than "utf8"; there is virtually no use for it.

Error: Cannot find module 'gulp-sass'

I worked with Yarn and I got the same issue and I solve it doing this:

delete node_modules
yarn install
yarn upgrade

yarn install gulp-sass --save-dev

Integrating CSS star rating into an HTML form

CSS:

.rate-container > i {
    float: right;
}

.rate-container > i:HOVER,
.rate-container > i:HOVER ~ i {
    color: gold;
}

HTML:

<div class="rate-container">
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
</div>

How to append something to an array?

There are a couple of ways to append an array in JavaScript:

1) The push() method adds one or more elements to the end of an array and returns the new length of the array.

var a = [1, 2, 3];
a.push(4, 5);
console.log(a);

Output:

[1, 2, 3, 4, 5]

2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:

var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a); 

Output:

[4, 5, 1, 2, 3]

3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);

Output:

[ "a", "b", "c", "d", "e", "f" ]

4) You can use the array's .length property to add an element to the end of the array:

var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar ); 

Output:

 ["one", "two", "three", "four"]

5) The splice() method changes the content of an array by removing existing elements and/or adding new elements:

var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);

Output:

["angel", "clown", "mandarin", "surgeon","nemo"]

6) You can also add a new element to an array simply by specifying a new index and assigning a value:

var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);

Output:

["one", "two","three","four"]

Two submit buttons in one form

Simple you can change the action of form on different submit buttons Click.

Try this in document.Ready

$(".acceptOffer").click(function () {
       $("form").attr("action", "/Managers/SubdomainTransactions");
});

$(".declineOffer").click(function () {
       $("form").attr("action", "/Sales/SubdomainTransactions");
});

XSS prevention in JSP/Servlet web application

I would suggest regularly testing for vulnerabilities using an automated tool, and fixing whatever it finds. It's a lot easier to suggest a library to help with a specific vulnerability then for all XSS attacks in general.

Skipfish is an open source tool from Google that I've been investigating: it finds quite a lot of stuff, and seems worth using.

List of IP addresses/hostnames from local network in Python

I have done following code to get the IP of MAC known device. This can be modified accordingly to obtain all IPs with some string manipulation. Hope this will help you.

#running windows cmd line  statement and put output into a string
cmd_out = os.popen("arp -a").read()
line_arr = cmd_out.split('\n')
line_count = len(line_arr)


#search in all lines for ip
for i in range(0, line_count):
    y = line_arr[i]
    z = y.find(mac_address)

    #if mac address is found then get the ip using regex matching
    if z > 0:
        ip_out= re.search('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', y, re.M | re.I)

How do I put a variable inside a string?

With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

With the example given in the question, it would look like this

plot.savefig(f'hanning{num}.pdf')

Checking host availability by using ping in bash scripts

I liked the idea of checking a list like:

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

but that snippet doesn't care if a host is unreachable, so is not a great answer IMHO.

I ran with it and wrote

for i in `cat Hostlist`
do
  ping -c1 -w2 $i >/dev/null 2>&1 ; echo $i $?
done

And I can then handle each accordingly.

How can I create an MSI setup?

Look for Windows Installer XML (WiX)

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

Hello @sahil I update your answer for swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

Hope it's helpful. Thanks

Add support library to Android Studio project

Android no longer downloading the libraries from the SDK manager, it has to be accessed through Google's Maven repository.

You will have to do something similar to this in your build.gradle file:

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}



dependencies {
    ...
    compile "com.android.support:support-core-utils:27.0.2"
}

Find more details about the setting up process here and about the different support library revisions here.

How to execute my SQL query in CodeIgniter

 return $this->db->select('(CASE 
            enter code hereWHEN orderdetails.ProductID = 0   THEN dealmaster.deal_name
            WHEN orderdetails.DealID = 0 THEN products.name
            END) as product_name')

C# : changing listbox row color?

Once you've added your listbox item to your form, change DrawMode with OwnerDrawFixed option from the Properties panel. If you forget to do this, none of the codes below will work. Then click DrawItem event from the Events area.

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   // 1. Get the item
   string selectedItem = listBox1.Items[e.Index].ToString();
                    
   // 2. Choose font 
   Font font = new Font("Arial", 12);
        
   // 3. Choose colour
   SolidBrush solidBrush = new SolidBrush(Color.Red);
        
   // 4. Get bounds
   int left = e.Bounds.Left;
   int top = e.Bounds.Top;
                    
   // 5. Use Draw the background within the bounds
   e.DrawBackground();
        
   // 6. Colorize listbox items
   e.Graphics.DrawString(selectedItem, font, solidBrush, left, top);
}

sql delete statement where date is greater than 30 days

Instead of converting to varchar to get just the day (convert(varchar(8), [Date], 112)), I prefer keeping it a datetime field and making it only the date (without the time).

SELECT * FROM Results 
WHERE CONVERT(date, [Date]) >= CONVERT(date, GETDATE())

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

For me, I changed C:\apps\Java\jdk1.8_162\bin\javac.exe to C:\apps\Java\jdk1.8_162\bin\javacpl.exe Since there was no executable with that name in the bin folder. That worked.

How to wait for a JavaScript Promise to resolve before resuming function?

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

_x000D_
_x000D_
function append_output(suffix, value) {
  $("#output_"+suffix).append(value)
}

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
    resolve("start")
  })
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  })
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")
  })

  Promise.all([start, middle, end]).then(results => {
    results.forEach(
      result => append_output("later", result))
  })
}

kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
_x000D_
_x000D_

In Java, how to append a string more efficiently?

- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.

HTTP Ajax Request via HTTPS Page

In some cases a one-way request without a response can be fired to a TCP server, without a SSL certificate. A TCP server, in contrast to a HTTP server, will catch you request. However there will be no access to any data sent from the browser, because the browser will not send any data without a positive certificate check. And in special cases even a bare TCP signal without any data is enough to execute some tasks. For example for an IoT device within a LAN to start a connection to an external service. Link

This is a kind of a "Wake Up" trigger, that works on a port without any security.

In case a response is needed, this can be implemented using a secured public https server, which can send the needed data back to the browser using e.g. Websockets.

How to empty a list?

You could try:

alist[:] = []

Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)

The [:] is the slice operator. See this question for more information.

Python error: AttributeError: 'module' object has no attribute

More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12

An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

>>> from lib.pkg1 import mod11

Then reference the function as simply mod11.mod12().

How to concatenate int values in java?

just to not forget the format method

String s = String.format("%s%s%s%s%s", a, b, c, d, e);

(%1.1s%1.1s%1.1s%1.1s%1.1s if you only want the first digit of each number...)

How to get and set the current web page scroll position?

The currently accepted answer is incorrect - document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, whereas Firefox and IE use html.

To get the current position, you want:

document.documentElement.scrollTop || document.body.scrollTop

You can set the current position to 1000px down the page like so:

document.documentElement.scrollTop = document.body.scrollTop = 1000;

Or, using jQuery (animate it while you're at it!):

$("html, body").animate({ scrollTop: "1000px" });

How to vertically center content with variable height within a div?

This seems to be the best solution I’ve found to this problem, as long as your browser supports the ::before pseudo element: CSS-Tricks: Centering in the Unknown.

It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table method because table elements don’t obey the max-height property.

_x000D_
_x000D_
.block {_x000D_
  height: 300px;_x000D_
  text-align: center;_x000D_
  background: #c0c0c0;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.block::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -0.25em; /* Adjusts for spacing */_x000D_
_x000D_
  /* For visualization _x000D_
  background: #808080; width: 5px;_x000D_
  */_x000D_
}_x000D_
_x000D_
.centered {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  width: 300px;_x000D_
  padding: 10px 15px;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  background: #f5f5f5;_x000D_
}
_x000D_
<div class="block">_x000D_
    <div class="centered">_x000D_
        <h1>Some text</h1>_x000D_
        <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
           shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
           towards that ship a while ago?"</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MySQL and PHP - insert NULL rather than empty string

All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Android - R cannot be resolved to a variable

Save all layouts, and replace them from the previous version. Start to copy one by one and clean the project everytime, sometimes one of the layouts has something, that eclipse doesn't like. It worked for me.

.htaccess not working on localhost with XAMPP

I had a similar problem. But the problem was in the file name '.htaccess', because the Windows doesn't let the file's name begin with a ".", the solution was rename the file with a CMD command. "rename c:\xampp\htdocs\htaccess.txt .htaccess"

Get Enum from Description attribute

The solution works good except if you have a Web Service.

You would need to do the Following as the Description Attribute is not serializable.

[DataContract]
public enum ControlSelectionType
{
    [EnumMember(Value = "Not Applicable")]
    NotApplicable = 1,
    [EnumMember(Value = "Single Select Radio Buttons")]
    SingleSelectRadioButtons = 2,
    [EnumMember(Value = "Completely Different Display Text")]
    SingleSelectDropDownList = 3,
}

public static string GetDescriptionFromEnumValue(Enum value)
{
        EnumMemberAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(EnumMemberAttribute), false)
            .SingleOrDefault() as EnumMemberAttribute;
        return attribute == null ? value.ToString() : attribute.Value;
}

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

HTML text-overflow ellipsis detection

This sample show tooltip on cell table with text truncated. Is dynamic based on table width:

$.expr[':'].truncated = function (obj) {
    var element = $(obj);

    return (element[0].scrollHeight > (element.innerHeight() + 1)) || (element[0].scrollWidth > (element.innerWidth() + 1));
};

$(document).ready(function () {
    $("td").mouseenter(function () {
        var cella = $(this);
        var isTruncated = cella.filter(":truncated").length > 0;
        if (isTruncated) 
            cella.attr("title", cella.text());
        else 
            cella.attr("title", null);
    });
});

Demo: https://jsfiddle.net/t4qs3tqs/

It works on all version of jQuery

Behaviour of increment and decrement operators in Python

++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)

++count

Parses as

+(+count)

Which translates to

count

You have to use the slightly longer += operator to do what you want to do:

count += 1

I suspect the ++ and -- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:

  • Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It's not a significant syntactic ambiguity, but it does exist.
  • Simpler language. ++ is nothing more than a synonym for += 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimize a += 1 into the inc instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
  • Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.

How to edit my Excel dropdown list?

Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.

Why does python use 'else' after for and while loops?

Great answers are:

  • this which explain the history, and
  • this gives the right citation to ease yours translation/understanding.

My note here comes from what Donald Knuth once said (sorry can't find reference) that there is a construct where while-else is indistinguishable from if-else, namely (in Python):

x = 2
while x > 3:
    print("foo")
    break
else:
    print("boo")

has the same flow (excluding low level differences) as:

x = 2
if x > 3:
    print("foo")
else:
    print("boo")

The point is that if-else can be considered as syntactic sugar for while-else which has implicit break at the end of its if block. The opposite implication, that while loop is extension to if, is more common (it's just repeated/looped conditional check), because if is often taught before while. However that isn't true because that would mean else block in while-else would be executed each time when condition is false.

To ease your understanding think of it that way:

Without break, return, etc., loop ends only when condition is no longer true and in such case else block will also execute once. In case of Python for you must consider C-style for loops (with conditions) or translate them to while.

Another note:

Premature break, return, etc. inside loop makes impossible for condition to become false because execution jumped out of the loop while condition was true and it would never come back to check it again.

SQL query for extracting year from a date

How about this one?

SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE

switch case statement error: case expressions must be constant expression

It was throwing me this error when I using switch in a function with variables declared in my class:

private void ShowCalendar(final Activity context, Point p, int type) 
{
    switch (type) {
        case type_cat:
            break;

        case type_region:
            break;

        case type_city:
            break;

        default:
            //sth
            break;
    }
}

The problem was solved when I declared final to the variables in the start of the class:

final int type_cat=1, type_region=2, type_city=3;

How to use a table type in a SELECT FROM statement?

In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;

In package body:

initialize the table in declarations:

exch_rt exch_tbl := exch_tbl();

in order to add record to the local collection, in begin - end block you can do:

exch_rt.extend;
                                one_row.exch_rt_usd := 2;
                                one_row.exch_rt_eur := 1;
                                one_row.currency_cd := 'dollar';
                                exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop 

in order to get data from this table , inside package body you can use:

select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)

enjoy!

P.S. sorry for a late answer :D

Make a simple fade in animation in Swift?

The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5) {
        self.myFirstLabel.alpha = 1.0
        self.myFirstButton.alpha = 1.0
        self.mySecondButton.alpha = 1.0
    }
}

Why is __dirname not defined in node REPL?

If you are using Node.js modules, __dirname and __filename don't exist.

From the Node.js documentation:

No require, exports, module.exports, __filename, __dirname

These CommonJS variables are not available in ES modules.

require can be imported into an ES module using module.createRequire().

Equivalents of __filename and __dirname can be created inside of each file via import.meta.url:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_no_filename_or_dirname

Get jQuery version from inspecting the jQuery object

console.log( 'You are running jQuery version: ' + $.fn.jquery );

How to enable/disable bluetooth programmatically in android

try this:

//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            // Bluetooth is not enable :)
            return false;
        }
        else{
            return true;
        }

    }

//method to enable bluetooth
    public static void enableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

//method to disable bluetooth
    public static void disableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }
    }

Add these permissions in manifest

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

htaccess redirect if URL contains a certain string

RewriteCond %{REQUEST_URI} foobar
RewriteRule .* index.php

or some variant thereof.

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Update

Below you've said:

Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.

That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).


Original answer:

If the format is always dd/mm/yyyy, then this is trivial:

var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
                  parseInt(parts[1], 10) - 1,
                  parseInt(parts[0], 10));

split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.

Omitting one Setter/Getter in Lombok

According to @Data description you can use:

All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.

New line in JavaScript alert box

Works with \n but if the script is into a java tag you must write \\\n

<script type="text/javascript">alert('text\ntext');</script>

or

<h:commandButton action="#{XXXXXXX.xxxxxxxxxx}" value="XXXXXXXX" 
    onclick="alert('text\\\ntext');" />

What is the correct JSON content type?

The right MIME type is application/json

BUT

I experienced many situations where the browser type or the framework user needed:

text/html

application/javascript

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

jQuery Upload Progress and AJAX file upload

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

(It also includes the drag/drop interface but that's easily ignored.)

Basically what it comes down to is this:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

This is how I handled the request (1 image per request) in PHP:

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

Regular expression to find two strings anywhere in input

(.* word1.* word2.* )|(.* word2.* word1.*)

Search and replace a line in a file in Python

Based on the answer by Thomas Watnedal. However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis

This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.

Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.

Reading the file as a single string instead of line by line allows for multiline match and replacement.

import re

def replace(file, pattern, subst):
    # Read contents from file as a single string
    file_handle = open(file, 'r')
    file_string = file_handle.read()
    file_handle.close()

    # Use RE package to allow for replacement (also allowing for (multiline) REGEX)
    file_string = (re.sub(pattern, subst, file_string))

    # Write contents to file.
    # Using mode 'w' truncates the file.
    file_handle = open(file, 'w')
    file_handle.write(file_string)
    file_handle.close()

What is the difference between Promises and Observables?

There is one downside of Observables missing in the answers. Promises allow to use the ES7 async/await functions. With them you can write asynchronous code like it would be a synchronous function call, so you don't need callbacks anymore. The only possibility for Observables to do this, is to convert them to Promises. But when you convert them to Promises, you can only have one return value again:

async function getData(){
    const data = await observable.first().toPromise();
    //do stuff with 'data' (no callback function needed)
}

Further reading: How can I `await` on an Rx Observable?

Android Min SDK Version vs. Target SDK Version

The comment posted by the OP to the question (basically stating that the targetSDK doesn't affect the compiling of an app) is entirely wrong! Sorry to be blunt.

In short, here is the purpose to declaring a different targetSDK from the minSDK: It means you are using features from a higher level SDK than your minimum, but you have ensured backwards compatibility. In other words, imagine that you want to use a feature that was only recently introduced, but that isn't critical to your application. You would then set the targetSDK to the version where this new feature was introduced and the minimum to something lower so that everyone could still use your app.

To give an example, let's say you're writing an app that makes extensive use of gesture detection. However, every command that can be recognised by a gesture can also be done by a button or from the menu. In this case, gestures are a 'cool extra' but aren't required. Therefore you would set the target sdk to 7 ("Eclair" when the GestureDetection library was introduced), and the minimumSDK to level 3 ("Cupcake") so that even people with really old phones could use your app. All you'd have to do is make sure that your app checked the version of Android it was running on before trying to use the gesture library, to avoid trying to use it if it didn't exist. (Admittedly this is a dated example since hardly anyone still has a v1.5 phone, but there was a time when maintaining compatibility with v1.5 was really important.)

To give another example, you could use this if you wanted to use a feature from Gingerbread or Honeycomb. Some people will get the updates soon, but many others, particularly with older hardware, might stay stuck with Eclair until they buy a new device. This would let you use some of the cool new features, but without excluding part of your possible market.

There is a really good article from the Android developer's blog about how to use this feature, and in particular, how to design the "check the feature exists before using it" code I mentioned above.

To the OP: I've written this mainly for the benefit of anyone who happens to stumble upon this question in the future, as I realise your question was asked a long time ago.

String to Binary in C#

It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010

This will do that for you...

//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
    //storage for the resulting string
    string result = string.Empty;
    //iterate through the byte[]
    foreach(byte value in data)
    {
        //storage for the individual byte
        string binarybyte = Convert.ToString(value, 2);
        //if the binarybyte is not 8 characters long, its not a proper result
        while(binarybyte.Length < 8)
        {
            //prepend the value with a 0
            binarybyte = "0" + binarybyte;
        }
        //append the binarybyte to the result
        result += binarybyte;
    }
    //return the result
    return result;
}

SQL set values of one column equal to values of another column in the same table

Sounds like you're working in just one table so something like this:

update your_table
set B = A
where B is null

Java Array, Finding Duplicates

public static ArrayList<Integer> duplicate(final int[] zipcodelist) {

    HashSet<Integer> hs = new HashSet<>();
    ArrayList<Integer> al = new ArrayList<>();
    for(int element: zipcodelist) {
        if(hs.add(element)==false) {
            al.add(element);
        }   
    }
    return al;
}

Browse files and subfolders in Python

from tkinter import *
import os

root = Tk()
file = filedialog.askdirectory()
changed_dir = os.listdir(file)
print(changed_dir)
root.mainloop()

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

Best way to check for nullable bool in a condition expression (if ...)

I think its up to you. I certainly think the .HasValue approach is more readable, especially with developers not familiar with the ?? syntax.

The other point of a nullable boolean type is that it is tristate, so you may want to do something else when it is just null, and not default to false.

How to make UIButton's text alignment center? Using IB

For swift 4, xcode 9

myButton.contentHorizontalAlignment = .center

How to select a record and update it, with a single queryset in Django?

If you need to set the new value based on the old field value that is do something like:

update my_table set field_1 = field_1 + 1 where pk_field = some_value

use query expressions:

MyModel.objects.filter(pk=some_value).update(field1=F('field1') + 1)

This will execute update atomically that is using one update request to the database without reading it first.

Using npm behind corporate proxy .pac

I had a similar issue and I tried all the workarounds above but none of them worked for me ( I was using special characters (like '@' symbol) in my password and I also needed to add domain name).

Apart from that I was bit apprehensive to add my password as plain text. It turned-out the easiest solution to overcome all these challenges was to use some sort of reverse proxy (like Fiddler).

I have already detailed the configuration steps in this answer in SO.

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

What is Vim recording and how can it be disabled?

As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

I find it easier to push or append arrays and then flatten them in place, like so:

somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push anotherarray # => ["some", "thing", ["another", "thing"]]
#or
somearray << anotherarray # => ["some", "thing", ["another", "thing"]]
somearray.flatten!  # => ["some", "thing", "another", "thing"]
somearray # => ["some", "thing", "another", "thing"]

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

Extract directory path and filename

echo $fspec | tr "/" "\n"|tail -1

PHP Fatal error: Uncaught exception 'Exception'

Just adding a bit of extra information here in case someone has the same issue as me.

I use namespaces in my code and I had a class with a function that throws an Exception.

However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.

Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.

Troubleshooting misplaced .git directory (nothing to commit)

I just had this problem myself because I was in the wrong folder. I was nested 1 level in, so there were no git files to be found.

When I execute cd .. to the correct directory, I was able to commit, as expected.

535-5.7.8 Username and Password not accepted

In my case removing 2 factor authentication solves my problem.

How to start mongodb shell?

In the terminal, use "mongo" command to switch the terminal into the MongoDB shell:

$ mongo
MongoDB shell version: 2.6.10
connecting to: admin
>

Once you get > symbol in the terminal, you have entered into the MongoDB shell.

Remove all files in a directory

#python 2.7
import tempfile
import shutil
import exceptions
import os

def TempCleaner():
    temp_dir_name = tempfile.gettempdir()
    for currentdir in os.listdir(temp_dir_name):
        try:
           shutil.rmtree(os.path.join(temp_dir_name, currentdir))
        except exceptions.WindowsError, e:
            print u'?? ??????? ???????:'+ e.filename

How to create a Java / Maven project that works in Visual Studio Code?

Here is a complete list of steps - you may not need steps 1-3 but am including them for completeness:-

  1. Download VS Code and Apache Maven and install both.
  2. Install the Visual Studio extension pack for Java - e.g. by pasting this URL into a web browser: vscode:extension/vscjava.vscode-java-pack and then clicking on the green Install button after it opens in VS Code.
  3. NOTE: See the comment from ADTC for an "Easier GUI version of step 3...(Skip step 4)." If necessary, the Maven quick start archetype could be used to generate a new Maven project in an appropriate local folder: mvn archetype:generate -DgroupId=com.companyname.appname-DartifactId=appname-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false. This will create an appname folder with Maven's Standard Directory Layout (i.e. src/main/java/com/companyname/appname and src/main/test/com/companyname/appname to begin with and a sample "Hello World!" Java file named appname.java and associated unit test named appnameTest.java).*
  4. Open the Maven project folder in VS Code via File menu -> Open Folder... and select the appname folder.
  5. Open the Command Palette (via the View menu or by right-clicking) and type in and select Tasks: Configure task then select Create tasks.json from template.
  6. Choose maven ("Executes common Maven commands"). This creates a tasks.json file with "verify" and "test" tasks. More can be added corresponding to other Maven Build Lifecycle phases. To specifically address your requirement for classes to be built without a JAR file, a "compile" task would need to be added as follows:

    {
        "label": "compile",
        "type": "shell",
        "command": "mvn -B compile",
        "group": "build"
    },
    
  7. Save the above changes and then open the Command Palette and select "Tasks: Run Build Task" then pick "compile" and then "Continue without scanning the task output". This invokes Maven, which creates a target folder at the same level as the src folder with the compiled class files in the target\classes folder.


Addendum: How to run/debug a class

Following a question in the comments, here are some steps for running/debugging:-

  1. Show the Debug view if it is not already shown (via View menu - Debug or CtrlShiftD).
  2. Click on the green arrow in the Debug view and select "Java".
  3. Assuming it hasn't already been created, a message "launch.json is needed to start the debugger. Do you want to create it now?" will appear - select "Yes" and then select "Java" again.
  4. Enter the fully qualified name of the main class (e.g. com.companyname.appname.App) in the value for "mainClass" and save the file.
  5. Click on the green arrow in the Debug view again.

Sorting a tab delimited file

pipe it through something like awk '{ print print $1"\t"$2"\t"$3"\t"$4"\t"$5 }'. This will change the spaces to tabs.

Create a symbolic link of directory in Ubuntu

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

How do I add a reference to the MySQL connector for .NET?

"Add a reference to MySql.Data.dll" means you need to add a library reference to the downloaded connector. The IDE will link the database connection library with your application when it compiles.

Step-by-Step Example

I downloaded the binary (no installer) zip package from the MySQL web site, extracted onto the desktop, and did the following:

  1. Create a new project in Visual Studio
  2. In the Solution Explorer, under the project name, locate References and right-click on it. Select "Add Reference".
  3. In the "Add Reference" dialog, switch to the "Browse" tab and browse to the folder containing the downloaded connector. Navigate to the "bin" folder, and select the "MySql.Data.dll" file. Click OK.
  4. At the top of your code, add using MySql.Data.MySqlClient;. If you've added the reference correctly, IntelliSense should offer to complete this for you.

How do I detect the Python version at runtime?

Try this code, this should work:

import platform
print(platform.python_version())

How do I disable directory browsing?

Create an .htaccess file containing the following line:

Options -Indexes

That is one option. Another option is editing your apache configuration file.

In order to do so, you first need to open it with the command:

vim /etc/httpd/conf/httpd.conf

Then find the line: Options Indexes FollowSymLinks

Change that line to: Options FollowSymLinks

Lastly save and exit the file, and restart apache server with this command:

sudo service httpd restart

(You have a guide with screenshots here.)

Update a column in MySQL

if you want to fill all the column:

update 'column' set 'info' where keyID!=0;

Label encoding across multiple columns in scikit-learn

We don't need a LabelEncoder.

You can convert the columns to categoricals and then get their codes. I used a dictionary comprehension below to apply this process to every column and wrap the result back into a dataframe of the same shape with identical indices and column names.

>>> pd.DataFrame({col: df[col].astype('category').cat.codes for col in df}, index=df.index)
   location  owner  pets
0         1      1     0
1         0      2     1
2         0      0     0
3         1      1     2
4         1      3     1
5         0      2     1

To create a mapping dictionary, you can just enumerate the categories using a dictionary comprehension:

>>> {col: {n: cat for n, cat in enumerate(df[col].astype('category').cat.categories)} 
     for col in df}

{'location': {0: 'New_York', 1: 'San_Diego'},
 'owner': {0: 'Brick', 1: 'Champ', 2: 'Ron', 3: 'Veronica'},
 'pets': {0: 'cat', 1: 'dog', 2: 'monkey'}}

How to get cookie expiration date / creation date from javascript?

The information is not available through document.cookie, but if you're really desperate for it, you could try performing a request through the XmlHttpRequest object to the current page and access the cookie header using getResponseHeader().

Javascript - Track mouse position

Just a simplified version of @T.J. Crowder and @RegarBoy's answers.

Less is more in my opinion.

Check out onmousemove event for more info about the event.

Image mouse tracker

There's a new value of posX and posY every time the mouse moves according to the horizontal and vertical coordinates.

<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Example Mouse Tracker</title>
      <style>    
        body {height: 3000px;}
        .dot {width: 2px;height: 2px;background-color: black;position: absolute;}
      </style>
    </head>
    <body>
    <p>Mouse tracker</p>
    <script>
    onmousemove = function(e){
        //Logging purposes
        console.log("mouse location:", e.clientX, e.clientY);

        //meat and potatoes of the snippet
        var pos = e;
        var dot;
        dot = document.createElement('div');
        dot.className = "dot";
        dot.style.left = pos.x + "px";
        dot.style.top = pos.y + "px";
        document.body.appendChild(dot);
    }      
    </script>
    </body>
    </html>

How to declare empty list and then add string in scala?

Maybe you can use ListBuffers in scala to create empty list and add strings later because ListBuffers are mutable. Also all the List functions are available for the ListBuffers in scala.

import scala.collection.mutable.ListBuffer 

val dm = ListBuffer[String]()
dm: scala.collection.mutable.ListBuffer[String] = ListBuffer()
dm += "text1"
dm += "text2"
dm = ListBuffer(text1, text2)

if you want you can convert this to a list by using .toList

Make DateTimePicker work as TimePicker only in WinForms

You want to set its 'Format' property to be time and add a spin button control to it:

yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;

Any reason to prefer getClass() over instanceof when generating .equals()?

The reason to use getClass is to ensure the symmetric property of the equals contract. From equals' JavaDocs:

It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

By using instanceof, it's possible to not be symmetric. Consider the example: Dog extends Animal. Animal's equals does an instanceof check of Animal. Dog's equals does an instanceof check of Dog. Give Animal a and Dog d (with other fields the same):

a.equals(d) --> true
d.equals(a) --> false

This violates the symmetric property.

To strictly follow equal's contract, symmetry must be ensured, and thus the class needs to be the same.

:not(:empty) CSS selector is not working?

Being a void element, an <input> element is considered empty by the HTML definition of "empty", since the content model of all void elements is always empty. So they will always match the :empty pseudo-class, whether or not they have a value. This is also why their value is represented by an attribute in the start tag, rather than text content within start and end tags.

Also, from the Selectors spec:

The :empty pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness;

Consequently, input:not(:empty) will never match anything in a proper HTML document. (It would still work in a hypothetical XML document that defines an <input> element that can accept text or child elements.)

I don't think you can style empty <input> fields dynamically using just CSS (i.e. rules that apply whenever a field is empty, and don't once text is entered). You can select initially empty fields if they have an empty value attribute (input[value=""]) or lack the attribute altogether (input:not([value])), but that's about it.

Git push failed, "Non-fast forward updates were rejected"

Add --force to your command line if you are sure you want to push. E.g. use git push origin --force (I recommend the command line as you will find much more support from other users with the command line. Also this may not be possible with SmartGit.) See this site for more information: http://help.github.com/remotes/

Python Timezone conversion

import datetime
import pytz

def convert_datetime_timezone(dt, tz1, tz2):
    tz1 = pytz.timezone(tz1)
    tz2 = pytz.timezone(tz2)

    dt = datetime.datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
    dt = tz1.localize(dt)
    dt = dt.astimezone(tz2)
    dt = dt.strftime("%Y-%m-%d %H:%M:%S")

    return dt

-

  • dt: date time string
  • tz1: initial time zone
  • tz2: target time zone

-

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "PST8PDT")
'2017-05-13 05:56:32'

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "UTC")
'2017-05-13 12:56:32'

-

> pytz.all_timezones[0:10]
['Africa/Abidjan',
 'Africa/Accra',
 'Africa/Addis_Ababa',
 'Africa/Algiers',
 'Africa/Asmara',
 'Africa/Asmera',
 'Africa/Bamako',
 'Africa/Bangui',
 'Africa/Banjul',
 'Africa/Bissau']

Window vs Page vs UserControl for WPF navigation?

  • Window is like Windows.Forms.Form, so just a new window
  • Page is, according to online documentation:

    Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.

    So you basically use this if going you visualize some HTML content

  • UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows

Hide scroll bar, but while still being able to scroll

As of December 11th 2018 (Firefox 64 and above), the answer to this question is very simple indeed as Firefox 64+ now implements the CSS Scrollbar Styling spec.

Just use the following CSS:

scrollbar-width: none;

Firefox 64 release note link here.

How do I convert a String object into a Hash object?

Ran across a similar issue that needed to use the eval().

My situation, I was pulling some data from an API and writing it to a file locally. Then being able to pull the data from the file and use the Hash.

I used IO.read() to read the contents of the file into a variable. In this case IO.read() creates it as a String.

Then used eval() to convert the string into a Hash.

read_handler = IO.read("Path/To/File.json")

puts read_handler.kind_of?(String) # Returns TRUE

a = eval(read_handler)

puts a.kind_of?(Hash) # Returns TRUE

puts a["Enter Hash Here"] # Returns Key => Values

puts a["Enter Hash Here"].length # Returns number of key value pairs

puts a["Enter Hash Here"]["Enter Key Here"] # Returns associated value

Also just to mention that IO is an ancestor of File. So you can also use File.read instead if you wanted.

When does System.gc() do something?

You need to be very careful if you call System.gc(). Calling it can add unnecessary performance issues to your application, and it is not guaranteed to actually perform a collection. It is actually possible to disable explicit System.gc() via the java argument -XX:+DisableExplicitGC.

I'd highly recommend reading through the documents available at Java HotSpot Garbage Collection for more in depth details about garbage collection.

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

How to see data from .RData file?

isfar<-load("C:/Users/isfar.RData") 
if(is.data.frame(isfar)){
   names(isfar)
}

If isfar is a dataframe, this will print out the names of its columns.

Check if space is in a string

def word_in(s):
   return " " not in s 

nginx: send all requests to a single html page

This worked for me:

location / {
    try_files $uri $uri/ /base.html;
}

Shortcut to create properties in Visual Studio?

ReSharper offers property generation in its extensive feature set. (It's not cheap though, unless you're working on an open-source project.)

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

How do I change Eclipse to use spaces instead of tabs?

Eclipse IDE for C/C++ Developers, Version: Helios Service Release 2

You need to create new profile by pressing New button inside "Window->Preferences->Code Style"

Go to Indentation tab and select "Tab policy = Space only"


Eclipse IDE for C/C++ Developers, Version: Kepler Service Release 1

Follow the path below to create new profile: "Window > Preferences > C/C++ > Code Style > Formatter"

Go to Indentation tab and select "Tab policy = Space only"

Failed to run sdkmanager --list with Java 9

(WINDOWS)

If you have installed Android Studio already go to File >> Project Structure... >> SDK Location.

Go to that location + \cmdline-tools\latest\bin Copy the Path into Environment Variables

than it is OK to use the command line tool.

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

Where can I get a list of Ansible pre-defined variables?

Note the official docs on connection configuration variables or "behavioral" variables - which aren't listed in host vars, appears to be List of Behavioral Inventory Parameters in the Inventory documentation.

P.S. The sudo option is undocumented there (yes its sudo not ansible_sudo as you'd expect ...) and probably a couple more aren't, but thats best doc I've found on em.

jQuery: go to URL with target="_blank"

Question: How can I open the href in the new window or tab with jQuery?

var url = $(this).attr('href').attr('target','_blank');

React - Display loading screen while DOM is rendering?

This could be done by placing the loading icon in your html file (index.html for ex), so that users see the icon immediately after the html file has been loaded.

When your app finishes loading, you could simply remove that loading icon in a lifecycle hook, I usually do that in componentDidMount.

What are all possible pos tags of NLTK?

The tag set depends on the corpus that was used to train the tagger. The default tagger of nltk.pos_tag() uses the Penn Treebank Tag Set.

In NLTK 2, you could check which tagger is the default tagger as follows:

import nltk
nltk.tag._POS_TAGGER
>>> 'taggers/maxent_treebank_pos_tagger/english.pickle'

That means that it's a Maximum Entropy tagger trained on the Treebank corpus.

nltk.tag._POS_TAGGER does not exist anymore in NLTK 3 but the documentation states that the off-the-shelf tagger still uses the Penn Treebank tagset.

Reactjs - setting inline styles correctly

It's not immediately obvious from the documentation why the following does not work:

<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>

But when doing it entirely inline:

  • You need double curly brackets
  • You don't need to put your values in quotes
  • React will add some default if you omit "em"
  • Remember to camelCase style names that have dashes in CSS - e.g. font-size becomes fontSize:
  • class is className

The correct way looks like this:

<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>

Bind a function to Twitter Bootstrap Modal Close

Bootstrap provide events that you can hook into modal, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event like this

    /* hidden.bs.modal event example */
    $('#myModal').on('hidden.bs.modal', function () {
          window.alert('hidden event fired!');
    })

Check a working fiddle here read more about modal methods and events here in Documentation

gridview data export to excel in asp.net

may be problem in data binding in export excel . check that data properly bin to a gridview or not.

Use this code for export grid view in excel sheet and note that you must add iTextSharp dll in you project.

protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;

        // Re-Bind data to GridView 

        using (CompMSEntities1 CompObj = new CompMSEntities1())
        {
            Start = Convert.ToDateTime(txtStart.Text);
            End = Convert.ToDateTime(txtEnd.Text);

            GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
            SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
            GridView1.DataBind();
           GridView1.Visible = true;
            ExportTable.Visible = true;
        }

        //Change the Header Row back to white color

        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");


       GridView1.Style.Add(" font-size", "10px");




        //Apply style to Individual Cells

        GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
        GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");

        for (int i = 1; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];

            //Change Color back to white

            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row

        //    row.Attributes.Add("class", "textmode");

            //Apply style to Individual Cells of Alternating Row

            if (i % 2 != 0)
            {
                row.Cells[0].Style.Add("background-color", "#C2D69B");
                row.Cells[1].Style.Add("background-color", "#C2D69B");
                row.Cells[2].Style.Add("background-color", "#C2D69B");
                row.Cells[3].Style.Add("background-color", "#C2D69B");
                row.Cells[4].Style.Add("background-color", "#C2D69B");
            }
        }
        GridView1.RenderControl(hw);

        //style to format numbers to string

        string style = @"<style> .textmode { mso-number-format:\@; } </style>";

        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

log4j:WARN No appenders could be found for logger in web.xml

Put these lines in the beginning of web.xml:

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:/main/resources/log4j.xml</param-value>
</context-param> 

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

Selecting Values from Oracle Table Variable / Array?

You might need a GLOBAL TEMPORARY TABLE.

In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

CREATE GLOBAL TEMPORARY TABLE temp_number
   ( number_column   NUMBER( 10, 0 )
   )
   ON COMMIT DELETE ROWS;

BEGIN 
   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 
      ); 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
    LOOP 
        -- Do something here
        NULL; 
    END LOOP; 
END; 
/

Initialization of an ArrayList in one line

interestingly no one-liner with the other overloaded Stream::collect method is listed

ArrayList<String> places = Stream.of( "Buenos Aires", "Córdoba", "La Plata" ).collect( ArrayList::new, ArrayList::add, ArrayList::addAll );

How to get an element's top position relative to the browser's viewport?

I am assuming an element having an id of btn1 exists in the web page, and also that jQuery is included. This has worked across all modern browsers of Chrome, FireFox, IE >=9 and Edge. jQuery is only being used to determine the position relative to document.

var screenRelativeTop =  $("#btn1").offset().top - (window.scrollY || 
                                            window.pageYOffset || document.body.scrollTop);

var screenRelativeLeft =  $("#btn1").offset().left - (window.scrollX ||
                                           window.pageXOffset || document.body.scrollLeft);

How can I concatenate strings in VBA?

There is the concatenate function. For example

=CONCATENATE(E2,"-",F2)
But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.

For..In loops in JavaScript - key value pairs

No one has mentioned Object.keys so I'll mention it.

Object.keys(obj).forEach(function (key) {
   // do something with obj[key]
});

Random word generator- Python

get the words online

from urllib.request import Request, urlopen
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')
print(webpage)

Randomizing the first 500 words

from urllib.request import Request, urlopen
import random


url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')
first500 = webpage[:500].split("\n")
random.shuffle(first500)
print(first500)

Output

['abnegation', 'able', 'aborning', 'Abigail', 'Abidjan', 'ablaze', 'abolish', 'abbe', 'above', 'abort', 'aberrant', 'aboriginal', 'aborigine', 'Aberdeen', 'Abbott', 'Abernathy', 'aback', 'abate', 'abominate', 'AAA', 'abc', 'abed', 'abhorred', 'abolition', 'ablate', 'abbey', 'abbot', 'Abelson', 'ABA', 'Abner', 'abduct', 'aboard', 'Abo', 'abalone', 'a', 'abhorrent', 'Abelian', 'aardvark', 'Aarhus', 'Abe', 'abjure', 'abeyance', 'Abel', 'abetting', 'abash', 'AAAS', 'abdicate', 'abbreviate', 'abnormal', 'abject', 'abacus', 'abide', 'abominable', 'abode', 'abandon', 'abase', 'Ababa', 'abdominal', 'abet', 'abbas', 'aberrate', 'abdomen', 'abetted', 'abound', 'Aaron', 'abhor', 'ablution', 'abeyant', 'about']

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

Measuring code execution time

If you use the Stopwatch class, you can use the .StartNew() method to reset the watch to 0. So you don't have to call .Reset() followed by .Start(). Might come in handy.

If a DOM Element is removed, are its listeners also removed from memory?

Yes, the garbage collector will remove them as well. Might not always be the case with legacy browsers though.

How to append contents of multiple files into one file

All of the (text-) files into one

find . | xargs cat > outfile

xargs makes the output-lines of find . the arguments of cat.

find has many options, like -name '*.txt' or -type.

you should check them out if you want to use it in your pipeline

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

This happens because you try to access plotOptions property using string name. TypeScript understands that name may have any value, not only property name from plotOptions. So TypeScript requires to add index signature to plotOptions, so it knows that you can use any property name in plotOptions. But I suggest to change type of name, so it can only be one of plotOptions properties.

interface trainInfo {
    name: keyof typeof plotOptions;
    x: Array<number>;
    y: Array<number>;
    type: string;
    mode: string;
}

Now you'll be able to use only property names that exist in plotOptions.

You also have to slightly change your code.

First assign array to some temp variable, so TS knows array type:

const plotDataTemp: Array<trainInfo> = [
    {
      name: "train_1",
      x: data.filtrationData.map((i: any) => i["1-CumVol"]),
      y: data.filtrationData.map((i: any) => i["1-PressureA"]),
      type: "scatter",
      mode: "lines"
    },
    // ...
}

Then filter:

const plotData = plotDataTemp.filter(({ name }) => plotOptions[name]);

If you're getting data from API and have no way to type check props at compile time the only way is to add index signature to your plotOptions:

type tplotOptions = {
    [key: string]: boolean
}

const plotOptions: tplotOptions = {
    train_1: true,
    train_2: true,
    train_3: true,
    train_4: true
}

PHP Fatal error: Using $this when not in object context

First you understand one thing, $this inside a class denotes the current object.
That is which is you are created out side of the class to call class function or variable.

So when you are calling your class function like foobar::foobarfunc(), object is not created. But inside that function you written return $this->foo(). Now here $this is nothing. Thats why its saying Using $this when not in object context in class.php

Solutions:

  1. Create a object and call foobarfunc().

  2. Call foo() using class name inside the foobarfunc().

How to insert data into elasticsearch

I started off using curl, but since have migrated to use kibana. Here is some more information on the ELK stack from elastic.co (E elastic search, K kibana): https://www.elastic.co/elk-stack

With kibana your POST requests are a bit more simple:

POST /<INDEX_NAME>/<TYPE_NAME>
{
    "field": "value",
    "id": 1,
    "account_id": 213,
    "name": "kimchy"
}

Remove all newlines from inside a string

strip() returns the string after removing leading and trailing whitespace. see doc

In your case, you may want to try replace():

string2 = string1.replace('\n', '')

Convert java.util.Date to String

Let's try this

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

Or a utility function

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

From Convert Date to String in Java

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

How to save to local storage using Flutter?

A late answer but I hope it will help anyone visiting here later too..

I will provide categories to save and their respective best methods...

  1. Shared Preferences Use this when storing simple values on storage e.g Color theme, app language, last scroll position(in reading apps).. these are simple settings that you would want to persist when the app restarts.. You could, however, use this to store large things(Lists, Maps, Images) but that would require serialization and deserialization.. To learn more on this deserialization and serialization go here.
  2. Files This helps a lot when you have data that is defined more by you for example log files, image files and maybe you want to export csv files.. I heard that this type of persistence can be washed by storage cleaners once disk runs out of space.. Am not sure as i have never seen it.. This also can store almost anything but with the help of serialization and deserialization..
  3. Saving to a database This is enormously helpful in data which is a bit complex. And I think this doesn't get washed up by disc cleaners as it is stored in AppData(for android).. In this, your data is stored in an SQLite database. Its plugin is SQFLite. Kinds of data that you might wanna put in here are like everything that can be represented by a database.

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

exception in initializer error in java when using Netbeans

Retrofit have recently updated to 2.7.1 version. After that Android 4.x clients have crashed. See https://stackoverflow.com/a/60071876/2914140.

Downgrade Retrofit to 2.6.4.

Is there a performance difference between a for loop and a for-each loop?

foreach makes the intention of your code clearer and that is normally preferred over a very minor speed improvement - if any.

Whenever I see an indexed loop I have to parse it a little longer to make sure it does what I think it does E.g. Does it start from zero, does it include or exclude the end point etc.?

Most of my time seems to be spent reading code (that I wrote or someone else wrote) and clarity is almost always more important than performance. Its easy to dismiss performance these days because Hotspot does such an amazing job.

How to correct indentation in IntelliJ

Code ? Reformat Code... (default Ctrl + Alt + L) for the whole file or Code ? Auto-Indent Lines (default Ctrl + Alt + I) for the current line or selection.

You can customise the settings for how code is auto-formatted under File ? Settings ? Editor ? Code Style.


To ensure comments are also indented to the same level as the code, you can simply do as follows:

UI screenshot (example for JavaScript)

Javascript Thousand Separator / string format

I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.

function getFormattedCurrency(num) {
    num = num.toFixed(2)
    var cents = (num - Math.floor(num)).toFixed(2);
    return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
}

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

If you know that the bean exists and its just a problem of the inspections, then just add the following before the variable declaration:

@SuppressWarnings("SpringJavaAutowiringInspection")
@Inject MyClass myVariable;

Sometimes IntelliJ cannot resolve if a bean has been declared, for example when the bean is included conditionally and the condition resolution happens at runtime.

How to set IE11 Document mode to edge as default?

The rendering mode in Internet Explorer 11 can appear stuck if the site is added to your local Compatibility View list. When this happens, the rendering mode inside the developer tools and out will default to the specified compatibility settings.

While this may not be the only way a site can get on this list, Microsoft does document the steps for how to manually add a site to this list.

From Fix site display problems with Compatibility View:

To add a site to the Compatibility View list

  1. Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.

  2. Tap or click the Tools button, and then tap or click Compatibility View settings.

  3. Under Add this website, enter the URL of the site you want to add to the list, and then tap or click Add.

Site Compatibility View Removal Instructions:

To remove a site from this list, follow these instructions.

  1. Go to Tools > Compatibility View settings.
  2. In the resulting dialog, click on the site you want to remove from the list.
  3. Click the Remove button.

Screenshots:

Tools - Compatibility View settings

Compatibility View settings dialog

AppSettings get value from .config file

ConfigurationManager.RefreshSection("appSettings")
string value = System.Configuration.ConfigurationManager.AppSettings[key];

How to get the cursor to change to the hand when hovering a <button> tag

 #more {
    background:none;
    border:none;
    color:#FFF;
    font-family:Verdana, Geneva, sans-serif;
    cursor: pointer;
}

Vue.js unknown custom element

This is a good way to create a component in vue.

let template = `<ul>
  <li>Your data here</li>
</ul>`;

Vue.component('my-task', {
  template: template,
  data() {

  },
  props: {
    task: {
      type: String
    }
  },
  methods: {

  },
  computed: {

  },
  ready() {

  }
});

new Vue({
 el : '#app'
});

Angular2 router (@angular/router), how to set default route?

I faced same issue apply all possible solution but finally this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

How to create a DateTime equal to 15 minutes ago?

from datetime import timedelta    
datetime.datetime.now() - datetime.timedelta(0, 900)

Actually 900 is in seconds. Which is equal to 15 minutes. `15*60 = 900`

MVC 5 Access Claims Identity User Data

Remember that in order to query the IEnumerable you need to reference system.linq.
It will give you the extension object needed to do:

CaimsList.FirstOrDefault(x=>x.Type =="variableName").toString();

Inputting a default image in case the src attribute of an html <img> is not valid?

If you're using Angular/jQuery then this might help...

<img ng-src="{{item.url}}" altSrc="{{item.alt_url}}" onerror="this.src = $(this).attr('altSrc')">

Explanation

Assuming that item has a property url that might be null, when it is then the image will show up as broken. That triggers execution of onerror attribute expression, as described above. You need to override the src attribute as described above, but you will need jQuery to access your altSrc. Couldn't get it to work with vanilla JavaScript.

Might seem a little hacky but saved the day on my project.

Can we set a Git default to fetch all tags during a remote pull?

For me the following seemed to work.

git pull --tags

How to resolve conflicts in EGit

GIT has the most irritating way of resolving conflicts (Unlike svn where you can simply compare and do the changes). I strongly feel git has complex conflict resolution process. If I were to resolve, I would simply take another code from GIT as fresh, add my changes and commit them. It simple and not so process oriented.

How to download videos from youtube on java?

I know i am answering late. But this code may useful for some one. So i am attaching it here.

Use the following java code to download the videos from YouTube.

package com.mycompany.ytd;

import java.io.File;
import java.net.URL;
import com.github.axet.vget.VGet;

/**
 *
 * @author Manindar
 */
public class YTD {

    public static void main(String[] args) {
        try {
            String url = "https://www.youtube.com/watch?v=s10ARdfQUOY";
            String path = "D:\\Manindar\\YTD\\";
            VGet v = new VGet(new URL(url), new File(path));
            v.download();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Add the below Dependency in your POM.XML file

        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>vget</artifactId>
            <version>1.1.33</version>
        </dependency>

Hope this will be useful.

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

What is Java String interning?

There are some "catchy interview" questions, such as why you get equals! if you execute the below piece of code.

String s1 = "testString";
String s2 = "testString";
if(s1 == s2) System.out.println("equals!");

If you want to compare Strings you should use equals(). The above will print equals because the testString is already interned for you by the compiler. You can intern the strings yourself using intern method as is shown in previous answers....

How can I iterate over files in a given directory?

Here's how I iterate through files in Python:

import os

path = 'the/name/of/your/path'

folder = os.fsencode(path)

filenames = []

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith( ('.jpeg', '.png', '.gif') ): # whatever file types you're using...
        filenames.append(filename)

filenames.sort() # now you have the filenames and can do something with them

NONE OF THESE TECHNIQUES GUARANTEE ANY ITERATION ORDERING

Yup, super unpredictable. Notice that I sort the filenames, which is important if the order of the files matters, i.e. for video frames or time dependent data collection. Be sure to put indices in your filenames though!

jquery select element by xpath

First create an xpath selector function.

function _x(STR_XPATH) {
    var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
    var xnodes = [];
    var xres;
    while (xres = xresult.iterateNext()) {
        xnodes.push(xres);
    }

    return xnodes;
}

To use the xpath selector with jquery, you can do like this:

$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');

Hope this can help.

Difference between agile and iterative and incremental development

Agile is mostly used technique in project development.In agile technology peoples are switches from one technology to other ..Main purpose is to remove dependancy. Like Peoples shifted from production to development,and development to testing. Thats why dependancy will remove on a single team or person..

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

How do I return the SQL data types from my query?

SELECT COLUMN_NAME,
       DATA_TYPE,
       CHARACTER_MAXIMUM_LENGTH
FROM information_schema.columns
WHERE TABLE_NAME = 'YOUR_TABLE_NAME'

You can use columns aliases for better looking output.

How to "crop" a rectangular image into a square with CSS?

I had a similar issue and could not "compromise" with background images. I came up with this.

<div class="container">
    <img src="http://lorempixel.com/800x600/nature">
</div>

.container {
    position: relative;
    width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
    border: 2px solid #fff; /* just to separate the images */
    overflow: hidden; /* "crop" the image */
    background: #000; /* incase the image is wider than tall/taller than wide */
}

.container img {
    position: absolute;
    display: block;
    height: 100%; /* all images at least fill the height */
    top: 50%; /* top, left, transform trick to vertically and horizontally center image */
    left: 50%;
    transform: translate3d(-50%,-50%,0);
}

//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});

Hope this helps!

Example: https://jsfiddle.net/cfbuwxmr/1/

If condition inside of map() React

If you're a minimalist like me. Say you only want to render a record with a list containing entries.

<div>
  {data.map((record) => (
    record.list.length > 0
      ? (<YourRenderComponent record={record} key={record.id} />)
      : null
  ))}
</div>

How do I download and save a file locally on iOS using objective C?

I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}

How do I set up cron to run a file just once at a specific time?

Try this out to execute a command on 30th March 2011 at midnight:

0 0 30 3 ? 2011  /command

WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.

Convert string to datetime in vb.net

You can try with ParseExact method

Sample

Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

How to properly create composite primary keys - MYSQL

I would not make the primary key of the "info" table a composite of the two values from other tables.

Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?

I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.

How to find distinct rows with field in list using JPA and Spring?

@Query("SELECT DISTINCT name FROM people WHERE name NOT IN (:names)")
List<String> findNonReferencedNames(@Param("names") List<String> names);

Reading InputStream as UTF-8

String file = "";

try {

    InputStream is = new FileInputStream(filename);
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;

    BufferedReader br = new BufferedReader(new InputStreamReader(is,
            UTF8), BUFFER_SIZE);
    String str;
    while ((str = br.readLine()) != null) {
        file += str;
    }
} catch (Exception e) {

}

Try this,.. :-)

How do you use youtube-dl to download live streams (that are live)?

Some websites with m3u streaming cannot be downloaded in a single youtube-dl step, you can try something like this :

$ URL=https://www.arte.tv/fr/videos/078132-001-A/cosmos-une-odyssee-a-travers-l-univers/
$ youtube-dl -F $URL | grep m3u
HLS_XQ_2     m3u8       1280x720   VA-STA, Allemand 2200k 
HLS_XQ_1     m3u8       1280x720   VF-STF, Français 2200k 
$ CHOSEN_FORMAT=HLS_XQ_1
$ youtube-dl -F "$(youtube-dl -gf $CHOSEN_FORMAT)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[info] Available formats for master:
format code  extension  resolution note
61           mp4        audio only   61k , mp4a.40.2
419          mp4        384x216     419k , avc1.66.30, mp4a.40.2
923          mp4        640x360     923k , avc1.77.30, mp4a.40.2
1737         mp4        720x406    1737k , avc1.77.30, mp4a.40.2
2521         mp4        1280x720   2521k , avc1.77.30, mp4a.40.2 (best)
$ youtube-dl --hls-prefer-native -f 1737 "$(youtube-dl -gf $CHOSEN_FORMAT $URL)" -o "$(youtube-dl -f $CHOSEN_FORMAT --get-filename $URL)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 257
[download] Destination: Cosmos_une_odyssee_a_travers_l_univers__HLS_XQ_1__078132-001-A.mp4
[download]   0.9% of ~731.27MiB at 624.95KiB/s ETA 13:13
....

PyCharm error: 'No Module' when trying to import own module (python script)

Pycharm 2017.1.1

  1. Click on View->ToolBar & View->Tool Buttons
  2. On the left pane Project would be visible, right click on it and press Autoscroll to source and then run your code.

This worked for me.

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

`React/RCTBridgeModule.h` file not found

If you want to make it from your editor also open SMobile.xcscheme

And change parallelizeBuildables = "NO"

How to check if a specific key is present in a hash or not?

While Hash#has_key? gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

hash.key?(some_key)

Plotting two variables as lines using ggplot2 on the same graph

I am also new to R but trying to understand how ggplot works I think I get another way to do it. I just share probably not as a complete perfect solution but to add some different points of view.

I know ggplot is made to work with dataframes better but maybe it can be also sometimes useful to know that you can directly plot two vectors without using a dataframe.

Loading data. Original date vector length is 100 while var0 and var1 have length 50 so I only plot the available data (first 50 dates).

var0 <- 100 + c(0, cumsum(runif(49, -20, 20)))
var1 <- 150 + c(0, cumsum(runif(49, -10, 10)))
date <- seq(as.Date("2002-01-01"), by="1 month", length.out=50)    

Plotting

ggplot() + geom_line(aes(x=date,y=var0),color='red') + 
           geom_line(aes(x=date,y=var1),color='blue') + 
           ylab('Values')+xlab('date')

enter image description here

However I was not able to add a correct legend using this format. Does anyone know how?

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

QString to char* conversion

Maybe

my_qstring.toStdString().c_str();

or safer, as Federico points out:

std::string str = my_qstring.toStdString();
const char* p = str.c_str();

It's far from optimal, but will do the work.

Assigning a variable NaN in python without numpy

Use float("nan"):

>>> float("nan")
nan

How to configure CORS in a Spring Boot + Spring Security application?

After much searching for the error coming from javascript CORS, the only elegant solution I found for this case was configuring the cors of Spring's own class org.springframework.web.cors.CorsConfiguration.CorsConfiguration()

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
    }

hide/show a image in jquery

What image do you want to hide? Assuming all images, the following should work:

$("img").hide();

Otherwise, using selectors, you could find all images that are child elements of the containing div, and hide those.

However, i strongly recommend you read the Jquery docs, you could have figured it out yourself: http://docs.jquery.com/Main_Page

How to hide columns in HTML table?

You can use the nth-child CSS selector to hide a whole column:

#myTable tr > *:nth-child(2) {
    display: none;
}

This works under assumption that a cell of column N (be it a th or td) is always the Nth child element of its row.

Here's a demo.


? If you want the column number to be dynamic, you could do that using querySelectorAll or any framework presenting similar functionality, like jQuery here:

$('#myTable tr > *:nth-child(2)').hide();

Demo with jQuery

(The jQuery solution also works on legacy browsers that don't support nth-child).

Algorithm for solving Sudoku

Hi I've blogged about writing a sudoku solver from scratch in Python and currently writing a whole series about writing a constraint programming solver in Julia (another high level but faster language) You can read the sudoku problem from a file which seems to be easier more handy than a gui or cli way. The general idea it uses is constraint programming. I use the all different / unique constraint but I coded it myself instead of using a constraint programming solver.

If someone is interested:

What's the best way to loop through a set of elements in JavaScript?

I had a very similar problem earlier with document.getElementsByClassName(). I didn't know what a nodelist was at the time.

var elements = document.getElementsByTagName('div');
for (var i=0; i<elements.length; i++) {
    doSomething(elements[i]);
}

My issue was that I expected that elements would be an array, but it isn't. The nodelist Document.getElementsByTagName() returns is iterable, but you can't call array.prototype methods on it.

You can however populate an array with nodelist elements like this:

var myElements = [];
for (var i=0; i<myNodeList.length; i++) {                               
    var element = myNodeList[i];
    myElements.push(element);
};

After that you can feel free to call .innerHTML or .style or something on the elements of your array.

"std::endl" vs "\n"

The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

jQuery, checkboxes and .is(":checked")

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

  if ($(this).prop('checked')){
    console.log('checked');
  }
});

print call stack in C or C++

Linux specific, TLDR:

  1. backtrace in glibc produces accurate stacktraces only when -lunwind is linked (undocumented platform-specific feature).
  2. To output function name, source file and line number use #include <elfutils/libdwfl.h> (this library is documented only in its header file). backtrace_symbols and backtrace_symbolsd_fd are least informative.

On modern Linux your can get the stacktrace addresses using function backtrace. The undocumented way to make backtrace produce more accurate addresses on popular platforms is to link with -lunwind (libunwind-dev on Ubuntu 18.04) (see the example output below). backtrace uses function _Unwind_Backtrace and by default the latter comes from libgcc_s.so.1 and that implementation is most portable. When -lunwind is linked it provides a more accurate version of _Unwind_Backtrace but this library is less portable (see supported architectures in libunwind/src).

Unfortunately, the companion backtrace_symbolsd and backtrace_symbols_fd functions have not been able to resolve the stacktrace addresses to function names with source file name and line number for probably a decade now (see the example output below).

However, there is another method to resolve addresses to symbols and it produces the most useful traces with function name, source file and line number. The method is to #include <elfutils/libdwfl.h>and link with -ldw (libdw-dev on Ubuntu 18.04).

Working C++ example (test.cc):

#include <stdexcept>
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <string>

#include <boost/core/demangle.hpp>

#include <execinfo.h>
#include <elfutils/libdwfl.h>

struct DebugInfoSession {
    Dwfl_Callbacks callbacks = {};
    char* debuginfo_path = nullptr;
    Dwfl* dwfl = nullptr;

    DebugInfoSession() {
        callbacks.find_elf = dwfl_linux_proc_find_elf;
        callbacks.find_debuginfo = dwfl_standard_find_debuginfo;
        callbacks.debuginfo_path = &debuginfo_path;

        dwfl = dwfl_begin(&callbacks);
        assert(dwfl);

        int r;
        r = dwfl_linux_proc_report(dwfl, getpid());
        assert(!r);
        r = dwfl_report_end(dwfl, nullptr, nullptr);
        assert(!r);
        static_cast<void>(r);
    }

    ~DebugInfoSession() {
        dwfl_end(dwfl);
    }

    DebugInfoSession(DebugInfoSession const&) = delete;
    DebugInfoSession& operator=(DebugInfoSession const&) = delete;
};

struct DebugInfo {
    void* ip;
    std::string function;
    char const* file;
    int line;

    DebugInfo(DebugInfoSession const& dis, void* ip)
        : ip(ip)
        , file()
        , line(-1)
    {
        // Get function name.
        uintptr_t ip2 = reinterpret_cast<uintptr_t>(ip);
        Dwfl_Module* module = dwfl_addrmodule(dis.dwfl, ip2);
        char const* name = dwfl_module_addrname(module, ip2);
        function = name ? boost::core::demangle(name) : "<unknown>";

        // Get source filename and line number.
        if(Dwfl_Line* dwfl_line = dwfl_module_getsrc(module, ip2)) {
            Dwarf_Addr addr;
            file = dwfl_lineinfo(dwfl_line, &addr, &line, nullptr, nullptr, nullptr);
        }
    }
};

std::ostream& operator<<(std::ostream& s, DebugInfo const& di) {
    s << di.ip << ' ' << di.function;
    if(di.file)
        s << " at " << di.file << ':' << di.line;
    return s;
}

void terminate_with_stacktrace() {
    void* stack[512];
    int stack_size = ::backtrace(stack, sizeof stack / sizeof *stack);

    // Print the exception info, if any.
    if(auto ex = std::current_exception()) {
        try {
            std::rethrow_exception(ex);
        }
        catch(std::exception& e) {
            std::cerr << "Fatal exception " << boost::core::demangle(typeid(e).name()) << ": " << e.what() << ".\n";
        }
        catch(...) {
            std::cerr << "Fatal unknown exception.\n";
        }
    }

    DebugInfoSession dis;
    std::cerr << "Stacktrace of " << stack_size << " frames:\n";
    for(int i = 0; i < stack_size; ++i) {
        std::cerr << i << ": " << DebugInfo(dis, stack[i]) << '\n';
    }
    std::cerr.flush();

    std::_Exit(EXIT_FAILURE);
}

int main() {
    std::set_terminate(terminate_with_stacktrace);
    throw std::runtime_error("test exception");
}

Compiled on Ubuntu 18.04.4 LTS with gcc-8.3:

g++ -o test.o -c -m{arch,tune}=native -std=gnu++17 -W{all,extra,error} -g -Og -fstack-protector-all test.cc
g++ -o test -g test.o -ldw -lunwind

Outputs:

Fatal exception std::runtime_error: test exception.
Stacktrace of 7 frames:
0: 0x55f3837c1a8c terminate_with_stacktrace() at /home/max/src/test/test.cc:76
1: 0x7fbc1c845ae5 <unknown>
2: 0x7fbc1c845b20 std::terminate()
3: 0x7fbc1c845d53 __cxa_throw
4: 0x55f3837c1a43 main at /home/max/src/test/test.cc:103
5: 0x7fbc1c3e3b96 __libc_start_main at ../csu/libc-start.c:310
6: 0x55f3837c17e9 _start

When no -lunwind is linked, it produces a less accurate stacktrace:

0: 0x5591dd9d1a4d terminate_with_stacktrace() at /home/max/src/test/test.cc:76
1: 0x7f3c18ad6ae6 <unknown>
2: 0x7f3c18ad6b21 <unknown>
3: 0x7f3c18ad6d54 <unknown>
4: 0x5591dd9d1a04 main at /home/max/src/test/test.cc:103
5: 0x7f3c1845cb97 __libc_start_main at ../csu/libc-start.c:344
6: 0x5591dd9d17aa _start

For comparison, backtrace_symbols_fd output for the same stacktrace is least informative:

/home/max/src/test/debug/gcc/test(+0x192f)[0x5601c5a2092f]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x92ae5)[0x7f95184f5ae5]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(_ZSt9terminatev+0x10)[0x7f95184f5b20]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(__cxa_throw+0x43)[0x7f95184f5d53]
/home/max/src/test/debug/gcc/test(+0x1ae7)[0x5601c5a20ae7]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe6)[0x7f9518093b96]
/home/max/src/test/debug/gcc/test(+0x1849)[0x5601c5a20849]

In a production version (as well as C language version) you may like to make this code extra robust by replacing boost::core::demangle, std::string and std::cout with their underlying calls.

You can also override __cxa_throw to capture the stacktrace when an exception is thrown and print it when the exception is caught. By the time it enters catch block the stack has been unwound, so it is too late to call backtrace, and this is why the stack must be captured on throw which is implemented by function __cxa_throw. Note that in a multi-threaded program __cxa_throw can be called simultaneously by multiple threads, so that if it captures the stacktrace into a global array that must be thread_local.

How do you delete an ActiveRecord object?

  1. User.destroy

User.destroy(1) will delete user with id == 1 and :before_destroy and :after_destroy callbacks occur. For example if you have associated records

has_many :addresses, :dependent => :destroy

After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.

  1. User.destroy, User.delete

  2. User.destroy_all(<conditions>) or User.delete_all(<conditions>)

Notice: User is a class and user is an instance object

"Fatal error: Unable to find local grunt." when running "grunt" command

This solved the issue for me. I mistakenly installed grunt using:

sudo npm install -g grunt --save-dev

and then ran the following command in the project folder:

npm install

This resulted in the error seen by the author of the question. I then uninstalled grunt using:

sudo npm uninstall -g grunt

Deleted the node_modules folder. And reinstalled grunt using:

npm install grunt --save-dev

and running the following in the project folder:

npm install

For some odd reason when you global install grunt using -g and then uninstall it, the node_modules folder holds on to something that prevents grunt from being installed locally to the project folder.

Add MIME mapping in web.config for IIS Express

Thanks for this post. I got this worked for using mustache templates in my asp.net mvc project I used the following, and it worked for me.

<system.webServer>   
  <staticContent>
   <mimeMap fileExtension=".mustache" mimeType="text/html"/>
  </staticContent>
</system.WebServer>

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.

Kolorobot’s example application includes the following:

  • No-xml Spring MVC 3.2 web application for Servlet 3.0 environment
  • Apache Tiles with configuration in place,
  • Bootstrap
  • JPA 2.0 (Hibernate/HSQLDB)
  • JUnit/Mockito
  • Spring Security 3.1

How to declare an ArrayList with values?

Use:

List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));

If you don't want to add new elements to the list later, you can also use (Arrays.asList returns a fixed-size list):

List<String> x = Arrays.asList("xyz", "abc");

Note: you can also use a static import if you like, then it looks like this:

import static java.util.Arrays.asList;

...

List<String> x = new ArrayList<>(asList("xyz", "abc"));

or

List<String> x = asList("xyz", "abc");

How to start a background process in Python?

Use subprocess.Popen() with the close_fds=True parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.

https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f

import os, time, sys, subprocess

if len(sys.argv) == 2:
    time.sleep(5)
    print 'track end'
    if sys.platform == 'darwin':
        subprocess.Popen(['say', 'hello'])
else:
    print 'main begin'
    subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
    print 'main end'

Search for value in DataGridView in a column

//     This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
    string searchValue=textBoxSearch.Text;
    int rowIndex = 1;  //this one is depending on the position of cell or column
    //string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        bool valueResulet = true;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dataGridView1.Rows[rowIndex].Selected = true;
                rowIndex++;
                valueResulet = false;
            }
        }
        if (valueResulet != false)
        {
            MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Vertical align in bootstrap table

Based on what you have provided your CSS selector is not specific enough to override the CSS rules defined by Bootstrap.

Try this:

.table > tbody > tr > td {
     vertical-align: middle;
}

In Boostrap 4, this can be achieved with the .align-middle Vertical Alignment utility class.

<td class="align-middle">Text</td>

Filtering DataSet

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));

C# DLL config file

you can use this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace GClass1
{
[Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface _GesGasConnect
{
    [DispId(1)]
    int SetClass1Ver(string version);


}

[Guid("13FE32AD-4BF8-495f-AB4D-6C61BD463EA4")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("InterfacesSMS.Setting")]
public class Class1 : _Class1
{
    public Class1() { }


    public int SetClass1(string version)
    {
        return (DateTime.Today.Day);
    }
}
}

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

Modern Solution

The result is that the circle never gets distorted and the text stays exactly in the middle of the circle - vertically and horizontally.

_x000D_
_x000D_
.circle {
  background: gold;
  width: 40px; 
  height: 40px;
  border-radius: 50%;
  display: flex; /* or inline-flex */
  align-items: center; 
  justify-content: center;
}
_x000D_
<div class="circle">text</div>
_x000D_
_x000D_
_x000D_

Simple and easy to use. Enjoy!

OSX -bash: composer: command not found

If you have to run composer with sudo, you should change the directory of composer to

/usr/bin

this was tested on Centos8.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

Can I use CASE statement in a JOIN condition?

This seems nice

https://bytes.com/topic/sql-server/answers/881862-joining-different-tables-based-condition

FROM YourMainTable
LEFT JOIN AirportCity DepCity ON @TravelType = 'A' and DepFrom =  DepCity.Code
LEFT JOIN AirportCity DepCity ON @TravelType = 'B' and SomeOtherColumn = SomeOtherColumnFromSomeOtherTable

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

Today not working adjustResize on full screen issue is actual for android sdk.

From answers i found:
the solution - but solution has this showing on picture issue :

Than i found the solution and remove the one unnecessary action:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

So, see my fixed solution code on Kotlin:

class AndroidBug5497Workaround constructor(val activity: Activity) {

    private val content = activity.findViewById<View>(android.R.id.content) as FrameLayout

    private val mChildOfContent = content.getChildAt(0)
    private var usableHeightPrevious: Int = 0
    private val contentContainer = activity.findViewById(android.R.id.content) as ViewGroup
    private val rootView = contentContainer.getChildAt(0)
    private val rootViewLayout = rootView.layoutParams as FrameLayout.LayoutParams

    private val listener = {
        possiblyResizeChildOfContent()
    }

    fun addListener() {
        mChildOfContent.apply {
            viewTreeObserver.addOnGlobalLayoutListener(listener)

        }
    }

    fun removeListener() {
        mChildOfContent.apply {
            viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
    }

    private fun possiblyResizeChildOfContent() {
        val contentAreaOfWindowBounds = Rect()
        mChildOfContent.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds)
        val usableHeightNow = contentAreaOfWindowBounds.height()

        if (usableHeightNow != usableHeightPrevious) {
            rootViewLayout.height = usableHeightNow
            rootView.layout(contentAreaOfWindowBounds.left,
                    contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
            mChildOfContent.requestLayout()
            usableHeightPrevious = usableHeightNow
        }
    }
}

My bug fixing implement code:

 class LeaveDetailActivity : BaseActivity(){

    private val keyBoardBugWorkaround by lazy {
        AndroidBug5497Workaround(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }

    override fun onResume() {
        keyBoardBugWorkaround.addListener()
        super.onResume()
    }

    override fun onPause() {
        keyBoardBugWorkaround.removeListener()
        super.onPause()
    }
}

How to get current date in jquery?

var d = new Date();

var today = d.getFullYear() + '/' + ('0'+(d.getMonth()+1)).slice(-2) + '/' + ('0'+d.getDate()).slice(-2);