Programs & Examples On #Nameservers

0

How do I get a list of all subdomains of a domain?

If you can't get this information from DNS (e.g. you aren't authorized) then one alternative is to use Wolfram Alpha.

  1. Enter the domain into the search box and run the search. (E.g. stackexchange.com)

Wolfram - Homepage

  1. In the 3rd section from the top (named "Web statistics for all of stackexchange.com") click Subdomains

Wolfram - Subdomains button

  1. In the Subdomains section click More

Wolfram - More subdomains button

You will be able to see a list of sub-domains there. Although I suspect it does not show ALL sub-domains.

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Parse JSON file using GSON

One thing that to be remembered while solving such problems is that in JSON file, a { indicates a JSONObject and a [ indicates JSONArray. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.

The Gson JsonReader documentation explains how to handle parsing of JsonObjects and JsonArrays:

  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().

Webfont Smoothing and Antialiasing in Firefox and Opera

I found the solution with this link : http://pixelsvsbytes.com/blog/2013/02/nice-web-fonts-for-every-browser/

Step by step method :

  • send your font to a WebFontGenerator and get the zip
  • find the TTF font on the Zip file
  • then, on linux, do this command (or install by apt-get install ttfautohint):
    ttfautohint --strong-stem-width=g neosansstd-black.ttf neosansstd-black.changed.ttf
  • then, one more, send the new TTF file (neosansstd-black.changed.ttf) on the WebFontGenerator
  • you get a perfect Zip with all your webfonts !

I hope this will help.

Spring: @Component versus @Bean

Difference between Bean and Component:

Difference between Bean and Component

Nginx -- static file serving confusion with root & alias

In your case, you can use root directive, because $uri part of the location directive is the same with last root directive part.

Nginx documentation advices it as well:
When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the root directive instead:

location /images/ {
    root /data/w3;
}

and root directive will append $uri to the path.

Locate the nginx.conf file my nginx is actually using

In addition to @Daniel Li's answer, the nginx installation with Valet would use the Velet configuration as well, this is found in "/usr/local/etc/nginx/valet/valet.conf". The nginx.conf file would have imported this Valet conf file. The settings you need may be in the Valet file.

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

Difference between Destroy and Delete

delete will only delete current object record from db but not its associated children records from db.

destroy will delete current object record from db and also its associated children record from db.

Their use really matters:

If your multiple parent objects share common children objects, then calling destroy on specific parent object will delete children objects which are shared among other multiple parents.

jQuery AJAX Character Encoding

I have been fiddling around with this problem and found out that this solution works for Firefox and safari (yes, im on a mac at the moment).

when getting the request, i made a content-type=iso-8859-1 here:

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml; charset=ISO-8859-1');
        }
    }

Please tell me if someone finds out this doesn't work in ie.

What is the difference between a function expression vs declaration in JavaScript?

They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.

Function declarations load before any code is executed.

Function expressions load only when the interpreter reaches that line of code.

So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.

Example: Function Expression

alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; } 

Example: Function Declaration

alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; } 


As for the second part of your question:

var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.

Laravel Rule Validation for Numbers

$this->validate($request,[
        'input_field_name'=>'digits_between:2,5',
       ]);

Try this it will be work

Declare multiple module.exports in Node.js

module1.js:

var myFunctions = { 
    myfunc1:function(){
    },
    myfunc2:function(){
    },
    myfunc3:function(){
    },
}
module.exports=myFunctions;

main.js

var myModule = require('./module1');
myModule.myfunc1(); //calling myfunc1 from module
myModule.myfunc2(); //calling myfunc2 from module
myModule.myfunc3(); //calling myfunc3 from module

Forking vs. Branching in GitHub

It has to do with the general workflow of Git. You're unlikely to be able to push directly to the main project's repository. I'm not sure if GitHub project's repository support branch-based access control, as you wouldn't want to grant anyone the permission to push to the master branch for example.

The general pattern is as follows:

  • Fork the original project's repository to have your own GitHub copy, to which you'll then be allowed to push changes.
  • Clone your GitHub repository onto your local machine
  • Optionally, add the original repository as an additional remote repository on your local repository. You'll then be able to fetch changes published in that repository directly.
  • Make your modifications and your own commits locally.
  • Push your changes to your GitHub repository (as you generally won't have the write permissions on the project's repository directly).
  • Contact the project's maintainers and ask them to fetch your changes and review/merge, and let them push back to the project's repository (if you and them want to).

Without this, it's quite unusual for public projects to let anyone push their own commits directly.

How to connect to a remote Windows machine to execute commands using python?

is it too late?

I personally agree with Beatrice Len, I used paramiko maybe is an extra step for windows, but I have an example project git hub, feel free to clone or ask me.

https://github.com/davcastroruiz/django-ssh-monitor

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

How to monitor SQL Server table changes by using c#?

Since SQL Server 2005 you have the option of using Query Notifications, which can be leveraged by ADO.NET see http://msdn.microsoft.com/en-us/library/t9x04ed2.aspx

Extract a substring using PowerShell

I needed to extract a few lines in a log file and this post was helpful in solving my issue, so i thought of adding it here. If someone needs to extract muliple lines, you can use the script to get the index of the a word matching that string (i'm searching for "Root") and extract content in all lines.

$File_content = Get-Content "Path of the text file"
$result = @()

foreach ($val in $File_content){
    $Index_No = $val.IndexOf("Root")
    $result += $val.substring($Index_No)
}

$result | Select-Object -Unique

Cheers..!

Angularjs: input[text] ngChange fires while the value is changing

In case anyone else looking for additional "enter" keypress support, here's an update to the fiddle provided by Gloppy

Code for keypress binding:

elm.bind("keydown keypress", function(event) {
    if (event.which === 13) {
        scope.$apply(function() {
            ngModelCtrl.$setViewValue(elm.val());
        });
    }
});

How to change text color and console color in code::blocks?

system("COLOR 0A");'

where 0A is a combination of background and font color 0

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Instead of using window.open you can use a link with the onclick event.
And you can put the html table into the uri and set the file name to be downloaded.

Live demo :

_x000D_
_x000D_
function exportF(elem) {_x000D_
  var table = document.getElementById("table");_x000D_
  var html = table.outerHTML;_x000D_
  var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url _x000D_
  elem.setAttribute("href", url);_x000D_
  elem.setAttribute("download", "export.xls"); // Choose the file name_x000D_
  return false;_x000D_
}
_x000D_
<table id="table" border="1">_x000D_
  <tr>_x000D_
    <td>_x000D_
      Foo_x000D_
    </td>_x000D_
    <td>_x000D_
      Bar_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<a id="downloadLink" onclick="exportF(this)">Export to excel</a>
_x000D_
_x000D_
_x000D_

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

Stretch image to fit full container width bootstrap

container class has 15px left & right padding, so if you want to remove this padding, use following, because row class has -15px left & right margin.

<div class="container">
  <div class="row">
     <img class='img-responsive' src="#" alt="" />
  </div>
</div>

Codepen: http://codepen.io/m-dehghani/pen/jqeKgv

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))

TypeError: 'function' object is not subscriptable - Python

You can use this:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bankHoliday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

WinError 2 The system cannot find the file specified (Python)

thank you, your first error guides me here and the solution solve mine too!

for permission error, f = open('output', 'w+'), change it into f = open(output+'output', 'w+').

or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.

for sure, you could probably running python/your script as administrator to pass permission error though

How can I debug a .BAT script?

The only way I can think of is spinkle the code with echos and pauses.

Why are C++ inline functions in the header?

There are two ways to look at it:

  1. Inline functions are defined in the header because, in order to inline a function call, the compiler must be able to see the function body. For a naive compiler to do that, the function body must be in the same translation unit as the call. (A modern compiler can optimize across translation units, and so a function call may be inlined even though the function definition is in a separate translation unit, but these optimizations are expensive, aren't always enabled, and weren't always supported by the compiler)

  2. functions defined in the header must be marked inline because otherwise, every translation unit which includes the header will contain a definition of the function, and the linker will complain about multiple definitions (a violation of the One Definition Rule). The inline keyword suppresses this, allowing multiple translation units to contain (identical) definitions.

The two explanations really boil down to the fact that the inline keyword doesn't exactly do what you'd expect.

A C++ compiler is free to apply the inlining optimization (replace a function call with the body of the called function, saving the call overhead) any time it likes, as long as it doesn't alter the observable behavior of the program.

The inline keyword makes it easier for the compiler to apply this optimization, by allowing the function definition to be visible in multiple translation units, but using the keyword doesn't mean the compiler has to inline the function, and not using the keyword doesn't forbid the compiler from inlining the function.

Eclipse error "ADB server didn't ACK, failed to start daemon"

Killing Eclipse and then rebooting did not help me. I added the Android tool to the PATH variables, started Task Manager and killed adb.exe.

I restarted Eclipse, and then it worked.

Getting scroll bar width using JavaScript

I've used next function to get scrollbar height/width:

function getBrowserScrollSize(){

    var css = {
        "border":  "none",
        "height":  "200px",
        "margin":  "0",
        "padding": "0",
        "width":   "200px"
    };

    var inner = $("<div>").css($.extend({}, css));
    var outer = $("<div>").css($.extend({
        "left":       "-1000px",
        "overflow":   "scroll",
        "position":   "absolute",
        "top":        "-1000px"
    }, css)).append(inner).appendTo("body")
    .scrollLeft(1000)
    .scrollTop(1000);

    var scrollSize = {
        "height": (outer.offset().top - inner.offset().top) || 0,
        "width": (outer.offset().left - inner.offset().left) || 0
    };

    outer.remove();
    return scrollSize;
}

This jQuery-based solutions works in IE7+ and all other modern browsers (including mobile devices where scrollbar height/width will be 0).

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

A beginner's guide to SQL database design

Experience counts for a lot, but in terms of table design you can learn a lot from how ORMs like Hibernate and Grails operate to see why they do things. In addition:

  1. Keep different types of data separate - don't store addresses in your order table, link to an address in a separate addresses table, for example.

  2. I personally like having an integer or long surrogate key on each table (that holds data, not those that link different tables together, e,g., m:n relationships) that is the primary key.

  3. I also like having a created and modified timestamp column.

  4. Ensure that every column that you do "where column = val" in any query has an index. Maybe not the most perfect index in the world for the data type, but at least an index.

  5. Set up your foreign keys. Also set up ON DELETE and ON MODIFY rules where relevant, to either cascade or set null, depending on your object structure (so you only need to delete once at the 'head' of your object tree, and all that object's sub-objects get removed automatically).

  6. If you want to modularise your code, you might want to modularise your DB schema - e.g., this is the "customers" area, this is the "orders" area, and this is the "products" area, and use join/link tables between them, even if they're 1:n relations, and maybe duplicate the important information (i.e., duplicate the product name, code, price into your order_details table). Read up on normalisation.

  7. Someone else will recommend exactly the opposite for some or all of the above :p - never one true way to do some things eh!

What does "publicPath" in Webpack do?

The webpack2 documentation explains this in a much cleaner way: https://webpack.js.org/guides/public-path/#use-cases

webpack has a highly useful configuration that let you specify the base path for all the assets on your application. It's called publicPath.

Reading file contents on the client-side in javascript in various browsers

There's a modern native alternative: File implements Blob, so we can call Blob.text().

_x000D_
_x000D_
async function readText(event) {
  const file = event.target.files.item(0)
  const text = await file.text();
  
  document.getElementById("output").innerText = text
}
_x000D_
<input type="file" onchange="readText(event)" />
<pre id="output"></pre>
_x000D_
_x000D_
_x000D_

Currently (September 2020) this is supported in Chrome and Firefox, for other Browser you need to load a polyfill, e.g. blob-polyfill.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

I think I had a similar problem in the past, with another python library. I believe that it was a windows permission issue. Try adding "Users" to your python directory, and give them full access.

Search an array for matching attribute

you can use ES5 some. Its pretty first by using callback

function findRestaurent(foodType) {
    var restaurant;
    restaurants.some(function (r) {
        if (r.food === id) {
            restaurant = r;
            return true;
        }
   });
  return restaurant;
}

How does one convert a grayscale image to RGB in OpenCV (Python)?

One you convert your image to gray-scale you cannot got back. You have gone from three channel to one, when you try to go back all three numbers will be the same. So the short answer is no you cannot go back. The reason your backtorgb function this throwing that error is because it needs to be in the format:

CvtColor(input, output, CV_GRAY2BGR)

OpenCV use BGR not RGB, so if you fix the ordering it should work, though your image will still be gray.

JSON.stringify output to div in pretty print way

If this is really for a user, better than just outputting text, you can use a library like this one https://github.com/padolsey/prettyprint.js to output it as an HTML table.

What is the largest Safe UDP Packet Size on the Internet

Given that IPV6 has a size of 1500, I would assert that carriers would not provide separate paths for IPV4 and IPV6 (they are both IP with different types), forcing them to equipment for ipv4 that would be old, redundant, more costly to maintain and less reliable. It wouldn't make any sense. Besides, doing so might easily be considered providing preferential treatment for some traffic -- a no no under rules they probably don't care much about (unless they get caught).

So 1472 should be safe for external use (though that doesn't mean an app like DNS that doesn't know about EDNS will accept it), and if you are talking internal nets, you can more likely know your network layout in which case jumbo packet sizes apply for for non-fragmented packets so for 4096 - 4068 bytes, and for intel's cards with 9014 byte buffers, a package size of ... wait...8086 bytes, would be the max...coincidence? snicker

****UPDATE****

Various answers give maximum values allowed by 1 SW vendor or various answers assuming encapsulation. The user didn't ask for the lowest value possible (like "0" for a safe UDP size), but the largest safe packet size.

Encapsulation values for various layers can be included multiple times. Since once you've encapsulated a stream -- there is nothing prohibiting, say, a VPN layer below that and a complete duplication of encapsulation layers above that.

Since the question was about maximum safe values, I'm assuming that they are talking about the maximum safe value for a UDP packet that can be received. Since no UDP packet is guaranteed, if you receive a UDP packet, the largest safe size would be 1 packet over IPv4 or 1472 bytes.

Note -- if you are using IPv6, the maximum size would be 1452 bytes, as IPv6's header size is 40 bytes vs. IPv4's 20 byte size (and either way, one must still allow 8 bytes for the UDP header).

How do I access the $scope variable in browser's console using AngularJS?

I usually use jQuery data() function for that:

$($0).data().$scope

The $0 is currently selected item in chrome DOM inspector. $1, $2 .. and so on are previously selected items.

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

Java JTable setting Column Width

No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

Insert ellipsis (...) into HTML tag if content too wide

There's a solution for multi-line text with pure css. It's called line-clamp, but it only works in webkit browsers. There is however a way to mimic this in all modern browsers (everything more recent than IE8.) Also, it will only work on solid backgrounds because you need a background-image to hide the last words of the last line. Here's how it goes:

Given this html:

<p class="example" id="example-1">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>

Here's the CSS:

p {
    position:relative;
    line-height:1.4em;
    height:4.2em;      /* 3 times the line-height to show 3 lines */
}
p::after {
    content:"...";
    font-weight:bold;
    position:absolute;
    bottom:0;
    right:0;
    padding:0 20px 1px 45px;
    background:url(ellipsis_bg.png) repeat-y;
}

ellipsis_bg.png being an image of the same color of your background, that would be about 100px wide and have the same height as your line-height.

It's not very pretty, as your text may be cut of in the middle of a letter, but it may be useful in some cases.

Reference: http://www.css-101.org/articles/line-clamp/line-clamp_for_non_webkit-based_browsers.php

Invalid date in safari

Best way to do it is by using the following format:

new Date(year, month, day, hours, minutes, seconds, milliseconds)
var d = new Date(2018, 11, 24, 10, 33, 30, 0);

This is supported in all browsers and will not give you any issues. Please note that the months are written from 0 to 11.

Playing .mp3 and .wav in Java?

It's been a while since I used it, but JavaLayer is great for MP3 playback

Why use def main()?

"What does if __name__==“__main__”: do?" has already been answered.

Having a main() function allows you to call its functionality if you import the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.

Get Filename Without Extension in Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

PHP memcached Fatal error: Class 'Memcache' not found

The right is php_memcache.dll. In my case i was using lib compiled with vc9 instead of vc6 compiler. In apatche error logs i got something like:

PHP Startup: sqlanywhere: Unable to initialize module Module compiled with build ID=API20090626, TS,VC9 PHP compiled with build ID=API20090626, TS,VC6 These options need to match

Check if you have same log and try downloading different dll that are compiled with different compiler.

Excel VBA code to copy a specific string to clipboard

Add a reference to the Microsoft Forms 2.0 Object Library and try this code. It only works with text, not with other data types.

Dim DataObj As New MSForms.DataObject

'Put a string in the clipboard
DataObj.SetText "Hello!"
DataObj.PutInClipboard

'Get a string from the clipboard
DataObj.GetFromClipboard
Debug.Print DataObj.GetText

Here you can find more details about how to use the clipboard with VBA.

java howto ArrayList push, pop, shift, and unshift

maybe you want to take a look java.util.Stack class. it has push, pop methods. and implemented List interface.

for shift/unshift, you can reference @Jon's answer.

however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.

Exit a Script On Error

Here is the way to do it:

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE *** 
************
'

Why does Firebug say toFixed() is not a function?

In a function, use as

render: function (args) {
    if (args.value != 0)
        return (parseFloat(args.value).toFixed(2));


},

Where does pip install its packages?

By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.

Using virtualenv or --user during install will change this default location. If you use pip show make sure you are using the right user or else pip may not see the packages you are referencing.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

To throw another potential solution into the mix, I had a settings folder as well as a settings.py in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)

Python was getting confused about whether I wanted to import project/settings.py or project/settings/__init__.py. I removed the settings dir and everything now works fine.

What is the method for converting radians to degrees?

For double in c# this might be helpful:

        public static double Conv_DegreesToRadians(this double degrees)
        {
            //return degrees * (Math.PI / 180d);
            return degrees * 0.017453292519943295d;
        }
        public static double Conv_RadiansToDegrees(this double radians)
        {
            //return radians * (180d / Math.PI);
            return radians * 57.295779513082323d;
        }

Detect if PHP session exists

If you are on php 5.4+, it is cleaner to use session_status():

if (session_status() == PHP_SESSION_ACTIVE) {
  echo 'Session is active';
}
  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

excel plot against a date time x series

That was much more painful than it ought to have been.

It turns out there are two concepts, the format of the data and the format of the axis. You need to format the data series as a time, then you format the graph's display axis as date and time.

Graph your data

Highlight all columns and insert your graph

First graph your data

Format datetime cells

Select the column, right click, format cells. Select time so that the data is in time format.

Format the cells

Now format the axis

Now right click on the axis text and change it to display whatever format you want

Format axis as custom date

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

In httpd.conf, search for "ServerName". It's usually commented out by default on Mac. Just uncomment it and fill it in. Make sure you also have the name/ip combo set in /etc/hosts.

How to properly and completely close/reset a TcpClient connection?

Use word: using. A good habit of programming.

using (TcpClient tcpClient = new TcpClient())
{
     //operations
     tcpClient.Close();
}

How do I check if a string contains another string in Objective-C?

Since this seems to be a high-ranking result in Google, I want to add this:

iOS 8 and OS X 10.10 add the containsString: method to NSString. An updated version of Dave DeLong's example for those systems:

NSString *string = @"hello bla bla";
if ([string containsString:@"bla"]) {
    NSLog(@"string contains bla!");
} else {
    NSLog(@"string does not contain bla");
}

Excel VBA: function to turn activecell to bold

I use

            chartRange = xlWorkSheet.Rows[1];
            chartRange.Font.Bold = true;

to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.

You can call in VBA directly

            ActiveCell.Font.Bold = True

With this code I create a timestamp in the active cell, with bold font and yellow background

           Private Sub Worksheet_SelectionChange(ByVal Target As Range)
               ActiveCell.Value = Now()
               ActiveCell.Font.Bold = True
               ActiveCell.Interior.ColorIndex = 6
           End Sub

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.

Can't check signature: public key not found

You get that error because you don't have the public key of the person who signed the message.

gpg should have given you a message containing the ID of the key that was used to sign it. Obtain the public key from the person who encrypted the file and import it into your keyring (gpg2 --import key.asc); you should be able to verify the signature after that.

If the sender submitted its public key to a keyserver (for instance, https://pgp.mit.edu/), then you may be able to import the key directly from the keyserver:

gpg2 --keyserver https://pgp.mit.edu/ --search-keys <sender_name_or_address>

ADB No Devices Found

For my Nexus 6P downloading drivers from Google helped resolved the issue. Here is the URL with documentation. And here you can download the driver itself.

P.S. I saw some people advice to download some drivers from random places on internet. While this might help it's too dangerous in my mind to download unknown drivers from unofficial places. So the one from Google worked well for me :)

git clone through ssh

Easy way to do this issue
try this.

Step 1:

ls -al ~/.ssh

enter image description here

Step 2:

ssh-keygen 

(using enter key for default value) enter image description here Step 3: To setup config file

vim /c/Users/Willie/.ssh/config

Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa

Step 4:

git clone [email protected]:<username>/test2.git

enter image description here

Step 5:
When you finished Step 4
1.the test2.git file will be download done
2.you will get the new file(known_hosts) in the ~/.ssh
enter image description here

PS: I create the id_rsa and id_rsa.ub by meself and I deliver it to the Gitlab server. using both keys to any client-sides(windows and Linux).

jQuery UI dialog box not positioned center screen

None of the above solutions worked for me. I will present below my scenario and the final solution, just in case someone has the same problem.

Scenario: I use a custom jQuery plugin to add a scroll bar to an HTML element that is located inside the Dialog box.

I used it as

$(response).dialog({
 create: function (event, ui) {
  $(".content-topp").mCustomScrollbar();
 })
});

The solution was to move it from create to open, like this:

$(response).dialog({
 open: function (event, ui) {
  $(".content-topp").mCustomScrollbar();
  $(this).dialog('option', 'position', 'center');
 })
});

So, if you use any custom jQuery plugin that manipulates the content then call it using the open event.

Converting a string to int in Groovy

Here is the an other way. if you don't like exceptions.

def strnumber = "100"
def intValue = strnumber.isInteger() ?  (strnumber as int) : null

Visual Studio window which shows list of methods

A nice clean way to do this is to use View.SynchronizeClassView.

enter image description here

Additionally you can:

  • pin your Class view window
  • collapse the top pane (listing all the classes)

And now it feels just like the Visual Assist's feature "List Methods in Current File" (which also list members btw).

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

AngularJS - Attribute directive input value change

To watch out the runtime changes in value of a custom directive, use $observe method of attrs object, instead of putting $watch inside a custom directive. Here is the documentation for the same ... $observe docs

How can you represent inheritance in a database?

The another way to do it, is using the INHERITS component. For example:

CREATE TABLE person (
    id int ,
    name varchar(20),
    CONSTRAINT pessoa_pkey PRIMARY KEY (id)
);

CREATE TABLE natural_person (
    social_security_number varchar(11),
    CONSTRAINT pessoaf_pkey PRIMARY KEY (id)
) INHERITS (person);


CREATE TABLE juridical_person (
    tin_number varchar(14),
    CONSTRAINT pessoaj_pkey PRIMARY KEY (id)
) INHERITS (person);

Thus it's possible to define a inheritance between tables.

Count number of occurrences by month

Make column B in sheet1 the dates but where the day of the month is always the first day of the month, e.g. in B2 put =DATE(YEAR(A2),MONTH(A2),1). Then make E5 on sheet 2 contain the first date of the month you need, e.g. Date(2013,4,1). After that, putting in F5 COUNTIF(Sheet1!B2:B50, E5) will give you the count for the month specified in E5.

How to check if a file exists in Ansible?

In general you would do this with the stat module. But the command module has the creates option which makes this very simple:

- name: touch file
  command: touch /etc/file.txt
  args:
    creates: /etc/file.txt

I guess your touch command is just an example? Best practice would be to not check anything at all and let ansible do its job - with the correct module. So if you want to ensure the file exists you would use the file module:

- name: make sure file exists
  file:
    path: /etc/file.txt
    state: touch

How do I verify that an Android apk is signed with a release certificate?

Use this command : (Jarsigner is in your Java bin folder goto java->jdk->bin path in cmd prompt)

$ jarsigner -verify my_signed.apk

If the .apk is signed properly, Jarsigner prints "jar verified"

PowerShell: Create Local User Account

Another alternative is the old school NET USER commands:

NET USER username "password" /ADD

OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.

NET LOCALGROUP "group" "user" /add to set group membership.

How do you access a website running on localhost from iPhone browser

Another quick and dirty way to do this on a mac is to open up xcode (if you have it installed) and run safari on your simulator. Typing localhost here will work as well.

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.

myApp.service('serverOperations', function($http) {
        this.get_data = function(user) {
          return $http.post('http://localhost/serverOperations.php?action=get_data', user);
        };
})


myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {        
    serverOperations.get_data(user)
        .then( function(response) {
            console.log(response.data);
            }
        );
})

Replace spaces with dashes and make all letters lower-case

Just use the String replace and toLowerCase methods, for example:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the g flag on the RegExp, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp will match one or more white-space characters.

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

how to set the background color of the whole page in css

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>_x000D_
        webpage_x000D_
      </title>_x000D_
</head>_x000D_
  <body style="background-color:blue;text-align:center">_x000D_
    welcome to my page_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How do I set up a private Git repository on GitHub? Is it even possible?

Since January 7th, 2019, it is possible: unlimited free private repositories on GitHub!
... But for up to three collaborators per private repository.

Nat Friedman just announced it by twitter:

Today(!) we’re thrilled to announce unlimited free private repos for all GitHub users, and a new simplified Enterprise offering:

"New year, new GitHub: Announcing unlimited free private repos and unified Enterprise offering"

For the first time, developers can use GitHub for their private projects with up to three collaborators per repository for free.

Many developers want to use private repos to apply for a job, work on a side project, or try something out in private before releasing it publicly.
Starting today, those scenarios, and many more, are possible on GitHub at no cost.

Public repositories are still free (of course—no changes there) and include unlimited collaborators.

How to get text and a variable in a messagebox

As has been suggested, using the string.format method is nice and simple and very readable.

In vb.net the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)

becomes:

MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx

maybe call

variable.ToString()

update:

Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")

Where is the itoa function in Linux?

Reading the code of guys who do it for a living will get you a LONG WAY.

Check out how guys from MySQL did it. The source is VERY WELL COMMENTED and will teach you much more than hacked up solutions found all over the place.

MySQL's implementation of int2str

I provide the mentioned implementation here; the link is here for reference and should be used to read the full implementation.

char *
int2str(long int val, char *dst, int radix, 
        int upcase)
{
  char buffer[65];
  char *p;
  long int new_val;
  char *dig_vec= upcase ? _dig_vec_upper : _dig_vec_lower;
  ulong uval= (ulong) val;

  if (radix < 0)
  {
    if (radix < -36 || radix > -2)
      return NullS;
    if (val < 0)
    {
      *dst++ = '-';
      /* Avoid integer overflow in (-val) for LLONG_MIN (BUG#31799). */
      uval = (ulong)0 - uval;
    }
    radix = -radix;
  }
  else if (radix > 36 || radix < 2)
    return NullS;

  /*
    The slightly contorted code which follows is due to the fact that
    few machines directly support unsigned long / and %.  Certainly
    the VAX C compiler generates a subroutine call.  In the interests
    of efficiency (hollow laugh) I let this happen for the first digit
    only; after that "val" will be in range so that signed integer
    division will do.  Sorry 'bout that.  CHECK THE CODE PRODUCED BY
    YOUR C COMPILER.  The first % and / should be unsigned, the second
    % and / signed, but C compilers tend to be extraordinarily
    sensitive to minor details of style.  This works on a VAX, that's
    all I claim for it.
  */
  p = &buffer[sizeof(buffer)-1];
  *p = '\0';
  new_val= uval / (ulong) radix;
  *--p = dig_vec[(uchar) (uval- (ulong) new_val*(ulong) radix)];
  val = new_val;
  while (val != 0)
  {
    ldiv_t res;
    res=ldiv(val,radix);
    *--p = dig_vec[res.rem];
    val= res.quot;
  }
  while ((*dst++ = *p++) != 0) ;
  return dst-1;
}

Swift 3: Display Image from URL

I use AlamofireImage it works fine for me for Loading url within ImageView, which also has Placeholder option.

func setImage (){

  let image = “https : //i.imgur.com/w5rkSIj.jpg”
  if let url = URL (string: image)
  {
    //Placeholder Image which was in your Local(Assets)
    let image = UIImage (named: “PlacehoderImageName”)
    imageViewName.af_setImage (withURL: url, placeholderImage: image)
  }

}

Note:- Dont forget to Add AlamofireImage in your Pod file as well as in Import Statment

Say Example,

pod 'AlamofireImage' within Your PodFile and in ViewController import AlamofireImage

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

Pass variable to function in jquery AJAX success callback

You can also use indexValue attribute for passing multiple parameters via object:

var someData = "hello";

jQuery.ajax({
    url: "http://maps.google.com/maps/api/js?v=3",
    indexValue: {param1:someData, param2:"Other data 2", param3: "Other data 3"},
    dataType: "script"
}).done(function() {
    console.log(this.indexValue.param1);
    console.log(this.indexValue.param2);
    console.log(this.indexValue.param3);
}); 

Setting log level of message at runtime in slf4j

no, it has a number of methods, info(), debug(), warn(), etc (this replaces the priority field)

have a look at http://www.slf4j.org/api/org/slf4j/Logger.html for the full Logger api.

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

SQL Error: ORA-00936: missing expression

You did two mistakes . I think you misplace FROM and WHERE keywords.

SELECT DISTINCT Description, Date as treatmentDate
     FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL,  doothey.Item.I --Here you use "." operator to "I" alias 
  WHERE  -- WHERE should be located here. 
   P.PatientID = A.PatientID
    AND A.AccountNo = AL.AccountNo
    AND AL.ItemNo = I.ItemNo
    AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');

How do I create a new line in Javascript?

Use a <br> tag to create a line break in the document

document.write("<br>");

Here's a sample fiddle

jQuery get the image src

You may find likr

$('.class').find('tag').attr('src');

Change Volley timeout duration

Just to contribute with my approach. As already answered, RetryPolicy is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.

Something like this:

public class BaseRequest<T> extends Request<T> {

    public BaseRequest(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
        setRetryPolicy(getMyOwnDefaultRetryPolicy());
    }
}

In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

How to load images dynamically (or lazily) when users scrolls them into view

The Swiss Army knife of image lazy loading is YUI's ImageLoader.

Because there is more to this problem than simply watching the scroll position.

How do I find the data directory for a SQL Server instance?

As of Sql Server 2012, you can use the following query:

SELECT SERVERPROPERTY('INSTANCEDEFAULTDATAPATH') as [Default_data_path], SERVERPROPERTY('INSTANCEDEFAULTLOGPATH') as [Default_log_path];

(This was taken from a comment at http://technet.microsoft.com/en-us/library/ms174396.aspx, and tested.)

How to set timeout in Retrofit library?

These answers were outdated for me, so here's how it worked out.

Add OkHttp, in my case the version is 3.3.1:

compile 'com.squareup.okhttp3:okhttp:3.3.1'

Then before building your Retrofit, do this:

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .build();
return new Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

iOS: Modal ViewController with transparent background

The solution to this answer using swift would be as follows.

let vc = MyViewController()
vc.view.backgroundColor = UIColor.clear // or whatever color.
vc.modalPresentationStyle = .overCurrentContext
present(vc, animated: true, completion: nil)

What is the best way to modify a list in a 'foreach' loop?

You can't change the enumerable collection while it is being enumerated, so you will have to make your changes before or after enumerating.

The for loop is a nice alternative, but if your IEnumerable collection does not implement ICollection, it is not possible.

Either:

1) Copy collection first. Enumerate the copied collection and change the original collection during the enumeration. (@tvanfosson)

or

2) Keep a list of changes and commit them after the enumeration.

Simple calculations for working with lat/lon and km distance?

If you're using Java, Javascript or PHP, then there's a library that will do these calculations exactly, using some amusingly complicated (but still fast) trigonometry:

http://www.jstott.me.uk/jcoord/

Removing "NUL" characters

I tried to use the \x00 and it didn't work for me when using C# and Regex. I had success with the following:

//The hexidecimal 0x0 is the null character  
mystring.Contains(Convert.ToChar(0x0).ToString() );  

// This will replace the character
mystring = mystring.Replace(Convert.ToChar(0x0).ToString(), "");  

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

Python progression path - From apprentice to guru

Understand (more deeply) Python's data types and their roles with regards to memory mgmt

As some of you in the community are aware, I teach Python courses, the most popular ones being the comprehensive Intro+Intermediate course as well as an "advanced" course which introduces a variety of areas of application development.

Quite often, I get asked a question quite similar to, "Should I take your intro or advanced course? I've already been programming Python for 1-2 years, and I think the intro one is too simple for me so I'd like to jump straight to the advanced... which course would you recommend?"

To answer their question, I probe to see how strong they are in this area -- not that it's really the best way to measure whether they're ready for any advanced course, but to see how well their basic knowledge is of Python's objects and memory model, which is a cause of many Python bugs written by those who are not only beginners but those who have gone beyond that.

To do this, I point them at this simple 2-part quiz question: Ex1: x=42; y=x; x+=1; print x,y Ex2: x=[1,2,3];y=x;x[0]=4;print x,y

Many times, they are able to get the output, but the why is more difficult and much more important of an response... I would weigh the output as 20% of the answer while the "why" gets 80% credit. If they can't get the why, regardless how Python experience they have, I will always steer people to the comprehensive intro+intermediate course because I spend one lecture on objects and memory management to the point where you should be able to answer with the output and the why with sufficient confidence. (Just because you know Python's syntax after 1-2 years doesn't make you ready to move beyond a "beginner" label until you have a much better understanding as far as how Python works under the covers.)

A succeeding inquiry requiring a similar answer is even tougher, e.g.,

Example 3

x = ['foo', [1,2,3], 10.4]
y = list(x) # or x[:]
y[0] = 'fooooooo'
y[1][0] = 4
print x
print y

The next topics I recommend are to understanding reference counting well, learning what "interning" means (but not necessarily using it), learning about shallow and deep copies (as in Example 3 above), and finally, the interrelationships between the various types and constructs in the language, i.e. lists vs. tuples, dicts vs. sets, list comprehensions vs. generator expressions, iterators vs. generators, etc.; however all those other suggestions are another post for another time. Hope this helps in the meantime! :-)

ps. I agree with the other responses for getting more intimate with introspection as well as studying other projects' source code and add a strong "+1" to both suggestions!

pps. Great question BTW. I wish I was smart enough in the beginning to have asked something like this, but that was a long time ago, and now I'm trying to help others with my many years of full-time Python programming!!

PHP Get URL with Parameter

Finally found this method:

basename($_SERVER['REQUEST_URI']);

This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10).

Cron job every three days

I don't think you have what you need with:

0 0 */3 * * ## <<< WARNING!!! CAUSES UNEVEN INTERVALS AT END OF MONTH!!

Unfortunately, the */3 is setting the interval on every n day of the month and not every n days. See: explanation here. At the end of the month there is recurring issue guaranteed.

1st  at 2019-02-01 00:00:00
then at 2019-02-04 00:00:00 << 3 days, etc. OK
then at 2019-02-07 00:00:00
...
then at 2019-02-25 00:00:00
then at 2019-01-28 00:00:00
then at 2019-03-01 00:00:00 << 1 day WRONG
then at 2019-03-04 00:00:00
...

According to this article, you need to add some modulo math to the command being executed to get a TRUE "every N days". For example:

0 0 * * *  bash -c '(( $(date +\%s) / 86400 \% 3 == 0 )) && runmyjob.sh

In this example, the job will be checked daily at 12:00 AM, but will only execute when the number of days since 01-01-1970 modulo 3 is 0.

If you want it to be every 3 days from a specific date, use the following format:

0 0 * * *  bash -c '(( $(date +\%s -d "2019-01-01") / 86400 \% 3 == 0 )) && runmyjob.sh

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

How to assign from a function which returns more than one value?

Yes to your second and third questions -- that's what you need to do as you cannot have multiple 'lvalues' on the left of an assignment.

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

Clearing Magento Log Data

Login to your c-panel goto phpmyadmin using SQL run below query to clear logs

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;

Centering a canvas

Tested only on Firefox:

<script>
window.onload = window.onresize = function() {
    var C = 0.8;        // canvas width to viewport width ratio
    var W_TO_H = 2/1;   // canvas width to canvas height ratio
    var el = document.getElementById("a");

    // For IE compatibility http://www.google.com/search?q=get+viewport+size+js
    var viewportWidth = window.innerWidth;
    var viewportHeight = window.innerHeight;

    var canvasWidth = viewportWidth * C;
    var canvasHeight = canvasWidth / W_TO_H;
    el.style.position = "fixed";
    el.setAttribute("width", canvasWidth);
    el.setAttribute("height", canvasHeight);
    el.style.top = (viewportHeight - canvasHeight) / 2;
    el.style.left = (viewportWidth - canvasWidth) / 2;

    window.ctx = el.getContext("2d");
    ctx.clearRect(0,0,canvasWidth,canvasHeight);
    ctx.fillStyle = 'yellow';
    ctx.moveTo(0, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, 0);
    ctx.lineTo(canvasWidth, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, canvasHeight);
    ctx.lineTo(0, canvasHeight/2);
    ctx.fill()
}
</script>

<body>
<canvas id="a" style="background: black">
</canvas>
</body>

How do I rename the extension for a bunch of files?

Nice & simple!

find . -iname *.html  -exec mv {} "$(basename {} .html).text"  \;

How to change default language for SQL Server?

Using SQL Server Management Studio

To configure the default language option

  1. In Object Explorer, right-click a server and select Properties.
  2. Click the Misc server settings node.
  3. In the Default language for users box, choose the language in which Microsoft SQL Server should display system messages. The default language is English.

Using Transact-SQL

To configure the default language option

  1. Connect to the Database Engine.
  2. From the Standard bar, click New Query.
  3. Copy and paste the following example into the query window and click Execute.

This example shows how to use sp_configure to configure the default language option to French

USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO

The 33 languages of SQL Server

| LANGID |        ALIAS        |
|--------|---------------------|
|    0   | English             |
|    1   | German              |
|    2   | French              |
|    3   | Japanese            |
|    4   | Danish              |
|    5   | Spanish             |
|    6   | Italian             |
|    7   | Dutch               |
|    8   | Norwegian           |
|    9   | Portuguese          |
|   10   | Finnish             |
|   11   | Swedish             |
|   12   | Czech               |
|   13   | Hungarian           |
|   14   | Polish              |
|   15   | Romanian            |
|   16   | Croatian            |
|   17   | Slovak              |
|   18   | Slovenian           |
|   19   | Greek               |
|   20   | Bulgarian           |
|   21   | Russian             |
|   22   | Turkish             |
|   23   | British English     |
|   24   | Estonian            |
|   25   | Latvian             |
|   26   | Lithuanian          |
|   27   | Brazilian           |
|   28   | Traditional Chinese |
|   29   | Korean              |
|   30   | Simplified Chinese  |
|   31   | Arabic              |
|   32   | Thai                |
|   33   | Bokmål              |

What is better, adjacency lists or adjacency matrices for graph problems in C++?

It depends on what you're looking for.

With adjacency matrices you can answer fast to questions regarding if a specific edge between two vertices belongs to the graph, and you can also have quick insertions and deletions of edges. The downside is that you have to use excessive space, especially for graphs with many vertices, which is very inefficient especially if your graph is sparse.

On the other hand, with adjacency lists it is harder to check whether a given edge is in a graph, because you have to search through the appropriate list to find the edge, but they are more space efficient.

Generally though, adjacency lists are the right data structure for most applications of graphs.

How to open a new tab using Selenium WebDriver

 Actions at=new Actions(wd);
 at.moveToElement(we);
 at.contextClick(we).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

Is Python strongly typed?

i think, this simple example should you explain the diffs between strong and dynamic typing:

>>> tup = ('1', 1, .1)
>>> for item in tup:
...     type(item)
...
<type 'str'>
<type 'int'>
<type 'float'>
>>>

java:

public static void main(String[] args) {
        int i = 1;
        i = "1"; //will be error
        i = '0.1'; // will be error
    }

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

Use:

$facebook->api('/'.$facebook_uid)

instead of

$facebook->api('/me')

it works.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

What do the python file extensions, .pyc .pyd .pyo stand for?

  • .py - Regular script
  • .py3 - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
  • .pyc - compiled script (Bytecode)
  • .pyo - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
  • .pyw - Python script to run in Windowed mode, without a console; executed with pythonw.exe
  • .pyx - Cython src to be converted to C/C++
  • .pyd - Python script made as a Windows DLL
  • .pxd - Cython script which is equivalent to a C/C++ header
  • .pxi - MyPy stub
  • .pyi - Stub file (PEP 484)
  • .pyz - Python script archive (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .pywz - Python script archive for MS-Windows (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .py[cod] - wildcard notation in ".gitignore" that means the file may be ".pyc", ".pyo", or ".pyd".
  • .pth - a path configuration file; its contents are additional items (one per line) to be added to sys.path. See site module.

A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/

How to pass the -D System properties while testing on Eclipse?

Yes this is the way:

Right click on your program, select run -> run configuration then on vm argument

-Denv=EnvironmentName -Dcucumber.options="--tags @ifThereisAnyTag"

Then you can apply and close.

Play multiple CSS animations at the same time

You cannot play two animations since the attribute can be defined only once. Rather why don't you include the second animation in the first and adjust the keyframes to get the timing right?

_x000D_
_x000D_
.image {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    margin:-60px 0 0 -60px;_x000D_
    -webkit-animation:spin-scale 4s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin-scale { _x000D_
    50%{_x000D_
        transform: rotate(360deg) scale(2);_x000D_
    }_x000D_
    100% { _x000D_
        transform: rotate(720deg) scale(1);_x000D_
    } _x000D_
}
_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
_x000D_
_x000D_
_x000D_

how to access master page control from content page

You cannot use var in a field, only on local variables.

But even this won't work:

Site master = Master as Site;

Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:

Site master = null;

protected void Page_Init(object sender, EventArgs e)
{            
    master = this.Master as Site;
}

Python+OpenCV: cv2.imwrite

wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:

for i, detected_box in enumerate(detect_boxes):
    box = detected_box["box"]
    face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

What is the difference between null and System.DBNull.Value?

DataRow has a method that is called IsNull() that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.

DataRow["col"]==null will allways be false.

use

DataRow r;
if (r.IsNull("col")) ...

instead.

Assigning a function to a variable

You simply don't call the function.

>>>def x():
>>>    print(20)
>>>y = x
>>>y()
20

The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns y the value returned by x (which in this case is None).

DataTable: Hide the Show Entries dropdown but keep the Search box

You can find more information directly on this link: http://datatables.net/examples/basic_init/filter_only.html

$(document).ready(function() {
$('#example').dataTable({
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": true,
    "bInfo": false,
    "bAutoWidth": false });
});

Hope that helps !

EDIT : If you are lazy, "bLengthChange": false, is the one you need to change :)

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

Working copy XXX locked and cleanup failed in SVN

I often get such an issue. My pattern that causes cleanup problems.

  1. I open image file in viewer.
  2. I delete image file/folder.
  3. I am trying to commit/update

Closing image viewer where deleted file is opened solves the problem. Maybe other software can block cleanup the same way.

In general. I believe restarting computer may help in such cases.

Comparing two arrays & get the values which are not common

This should help, uses simple hash table.

$a1=@(1,2,3,4,5) $b1=@(1,2,3,4,5,6)


$hash= @{}

#storing elements of $a1 in hash
foreach ($i in $a1)
{$hash.Add($i, "present")}

#define blank array $c
$c = @()

#adding uncommon ones in second array to $c and removing common ones from hash
foreach($j in $b1)
{
if(!$hash.ContainsKey($j)){$c = $c+$j}
else {hash.Remove($j)}
}

#now hash is left with uncommon ones in first array, so add them to $c
foreach($k in $hash.keys)
{
$c = $c + $k
}

how to open *.sdf files?

You can use SQL Compact Query Analyzer

http://sqlcequery.codeplex.com/

SQL Compact Query Analyzer is really snappy. 3 MB download, requires an install but really snappy and works.

How to include Authorization header in cURL POST HTTP Request in PHP?

@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:

$rest = curl_exec($crl);

if ($rest === false)
{
    // throw new Exception('Curl error: ' . curl_error($crl));
    print_r('Curl error: ' . curl_error($crl));
}

curl_close($crl);
print_r($rest);

EDIT 1

To debug you can set CURLOPT_HEADER to true to check HTTP response with firebug::net or similar.

curl_setopt($crl, CURLOPT_HEADER, true);

EDIT 2

About Curl error: SSL certificate problem, verify that the CA cert is OK try adding this headers (just to debug, in a production enviroment you should keep these options in true):

curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);

How to read a text file directly from Internet using Java?

Using Apache Commons IO:

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public static String readURLToString(String url) throws IOException
{
    try (InputStream inputStream = new URL(url).openStream())
    {
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    }
}

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem

How to Identify port number of SQL server

You can also use this query

USE MASTER GO xp_readerrorlog 0, 1, N'Server is listening on' GO

Source : sqlauthority blog

How to pass props to {this.props.children}

Further to @and_rest answer, this is how I clone the children and add a class.

<div className="parent">
    {React.Children.map(this.props.children, child => React.cloneElement(child, {className:'child'}))}
</div>

How to horizontally center a floating element of a variable width?

You can use fit-content value for width.

#wrap {
  width: -moz-fit-content;
  width: -webkit-fit-content;
  width: fit-content;
  margin: auto;   
}

Note: It works only in latest browsers.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Uncaught TypeError: (intermediate value)(...) is not a function

Error Case:

var userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

Output:

TypeError: (intermediate value)(intermediate value) is not a function

Fix: You are missing a semi-colon (;) to separate the expressions

userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}; // Without a semi colon, the error is produced

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

How do you find out the caller function in JavaScript?

Just console log your error stack. You can then know how are you being called

_x000D_
_x000D_
const hello = () => {_x000D_
  console.log(new Error('I was called').stack)_x000D_
}_x000D_
_x000D_
const sello = () => {_x000D_
  hello()_x000D_
}_x000D_
_x000D_
sello()
_x000D_
_x000D_
_x000D_

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

How to determine SSL cert expiration date from a PEM encoded certificate?

Here's my bash command line to list multiple certificates in order of their expiration, most recently expiring first.

for pem in /etc/ssl/certs/*.pem; do 
   printf '%s: %s\n' \
      "$(date --date="$(openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" --iso-8601)" \
      "$pem"
done | sort

Sample output:

2015-12-16: /etc/ssl/certs/Staat_der_Nederlanden_Root_CA.pem
2016-03-22: /etc/ssl/certs/CA_Disig.pem
2016-08-14: /etc/ssl/certs/EBG_Elektronik_Sertifika_Hizmet_S.pem

Force re-download of release dependency using Maven

Go to build path... delete existing maven library u added... click add library ... click maven managed dependencies... then click maven project settings... check resolve maven dependencies check box..it'll download all maven dependencies

Disable Copy or Paste action for text box?

Best way to do this is to add a data attribute to the field (textbox) where you want to avoid the cut,copy and paste.

Just create a method for the same which is as follows :-

function ignorePaste() {

$("[data-ignorepaste]").bind("cut copy paste", function (e) {
            e.preventDefault(); //prevent the default behaviour 
        });

};

Then once when you add the above code simply add the data attribute to the field where you want to ignore cut copy paste. in our case your add a data attribute to confirm email text box as below :-

Confirm Email: <input type="textbox" id= "confirmEmail" data-ignorepaste=""/>

Call the method ignorePaste()

So in this way you will be able to use this throughout the application, all you need to do is just add the data attribute where you want to ignore cut copy paste

https://jsfiddle.net/0ac6pkbf/21/

SQL query for today's date minus two months

SELECT COUNT(1) FROM FB 
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)

Callback after all asynchronous forEach callbacks are completed

 var counter = 0;
 var listArray = [0, 1, 2, 3, 4];
 function callBack() {
     if (listArray.length === counter) {
         console.log('All Done')
     }
 };
 listArray.forEach(function(element){
     console.log(element);
     counter = counter + 1;
     callBack();
 });

Default behavior of "git push" without a branch specified

git push origin will push all changes on the local branches that have matching remote branches at origin As for git push

Works like git push <remote>, where <remote> is the current branch's remote (or origin, if no remote is configured for the current branch).

From the Examples section of the git-push man page

sqlplus statement from command line

I assume this is *nix?

Use "here document":

sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF

EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):

$ echo 'select 1 from dual;'|sqlplus -s user/pw

         1
----------
         1


$

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Both Encrypt and Decrypt with AES and DES Algoritham ,This worked for me perfectly GithubLink: Java Code For Encryption and Decryption

package decrypt;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/* Decrypt encrypted string into plain string with aes and Des algoritham*/ 

public class Decrypt {

public String decrypt(String str,String k) throws Exception {
// Decode base64 to get bytes

 Cipher  dcipher = Cipher.getInstance("AES");
 Key aesKey = new SecretKeySpec(k.getBytes(), "AES");
 dcipher.init(dcipher.DECRYPT_MODE, aesKey);
//System.out.println(aesKey);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
//System.out.println(utf8);
// Decode using utf-8
 return new String(utf8, "UTF8");
 }


  public String encrypt(String str,String k) throws Exception {
 Cipher ecipher = Cipher.getInstance("AES");
 Key aeskey = new SecretKeySpec(k.getBytes(),"AES");
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
 public String encrypt(String str,String k,String Algo) throws Exception {
 Cipher ecipher = Cipher.getInstance(Algo);
 Key aeskey = new SecretKeySpec(k.getBytes(),Algo);
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
public String decrypt(String str,String k,String Algo) throws Exception {
    // Decode base64 to get bytes

     Cipher  dcipher = Cipher.getInstance(Algo);
     Key aesKey = new SecretKeySpec(k.getBytes(), Algo);
     dcipher.init(dcipher.DECRYPT_MODE, aesKey);
    //System.out.println(aesKey);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    byte[] utf8 = dcipher.doFinal(dec);
    //System.out.println(utf8);
 // Decode using utf-8
     return new String(utf8, "UTF8");
  }

public static void main(String args []) throws Exception
{
    String original = "rakesh";
    String data = "CfPcX0G+e7TLKKMyyvrvrQ==";
    String k = "qertyuiopasdfghw"; //AES key length must be 16
    String k1 = "qertyuio";  // DES key length must be 8 
    String data1 = "rakesh";
    String data2 = "nAtvNq7uHKE=";
    String Algo= "DES";
    String Algo1= "AES";
    Decrypt decrypter = new Decrypt();
     System.out.println("Original String: " + original);

     System.out.println("encrypted String in DES: " + decrypter.encrypt(data1, 
      k1,Algo));
     System.out.println("Decrypted String in DES: " + decrypter.decrypt(data2, 
       k1,Algo));
     System.out.println("encrypted String in AES: " + decrypter.encrypt(data1, 
      k,Algo1));
     System.out.println("Decrypted String in AES: " + decrypter.decrypt(data, 
      k,Algo1));
   }
}

Using ChildActionOnly in MVC

A little late to the party, but...

The other answers do a good job of explaining what effect the [ChildActionOnly] attribute has. However, in most examples, I kept asking myself why I'd create a new action method just to render a partial view, within another view, when you could simply render @Html.Partial("_MyParialView") directly in the view. It seemed like an unnecessary layer. However, as I investigated, I found that one benefit is that the child action can create a different model and pass that to the partial view. The model needed for the partial might not be available in the model of the view in which the partial view is being rendered. Instead of modifying the model structure to get the necessary objects/properties there just to render the partial view, you can call the child action and have the action method take care of creating the model needed for the partial view.

This can come in handy, for example, in _Layout.cshtml. If you have a few properties common to all pages, one way to accomplish this is use a base view model and have all other view models inherit from it. Then, the _Layout can use the base view model and the common properties. The downside (which is subjective) is that all view models must inherit from the base view model to guarantee that those common properties are always available. The alternative is to render @Html.Action in those common places. The action method would create a separate model needed for the partial view common to all pages, which would not impact the model for the "main" view. In this alternative, the _Layout page need not have a model. It follows that all other view models need not inherit from any base view model.

I'm sure there are other reasons to use the [ChildActionOnly] attribute, but this seems like a good one to me, so I thought I'd share.

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

Rails doesnt like the using of ^ and $ for some security reasons , probably its better to use \A and \z to set the beginning and the end of the string

What is useState() in React?

useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:

import React, {useState} from react    

function HookCounter {    
  const [count, stateCount]= useState(0)    
    return(    
      <div>     
        <button onClick{( ) => setCount(count+1)}> count{count}</button>    
      </div>    
    )   
 }

useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Old thread, but just came across this in a sample:

services.AddSignalR()
            .AddAzureSignalR(options =>
        {
            options.ClaimsProvider = context => new[]
            {
                new Claim(ClaimTypes.NameIdentifier, context.Request.Query["username"])
            };
        });

How to check for an active Internet connection on iOS or macOS?

The Reachability class is OK to find out if the Internet connection is available to a device or not...

But in case of accessing an intranet resource:

Pinging the intranet server with the reachability class always returns true.

So a quick solution in this scenario would be to create a web method called pingme along with other webmethods on the service. The pingme should return something.

So I wrote the following method on common functions

-(BOOL)PingServiceServer
{
    NSURL *url=[NSURL URLWithString:@"http://www.serveraddress/service.asmx/Ping"];

    NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url];

    [urlReq setTimeoutInterval:10];

    NSURLResponse *response;

    NSError *error = nil;

    NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReq
                                                 returningResponse:&response
                                                             error:&error];
    NSLog(@"receivedData:%@",receivedData);

    if (receivedData !=nil)
    {
        return YES;
    }
    else
    {
        NSLog(@"Data is null");
        return NO;
    }
}

The above method was so useful for me, so whenever I try to send some data to the server I always check the reachability of my intranet resource using this low timeout URLRequest.

How to convert a string to lower case in Bash?

In spite of how old this question is and similar to this answer by technosaurus. I had a hard time finding a solution that was portable across most platforms (That I Use) as well as older versions of bash. I have also been frustrated with arrays, functions and use of prints, echos and temporary files to retrieve trivial variables. This works very well for me so far I thought I would share. My main testing environments are:

  1. GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
  2. GNU bash, version 3.2.57(1)-release (sparc-sun-solaris2.10)
lcs="abcdefghijklmnopqrstuvwxyz"
ucs="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
input="Change Me To All Capitals"
for (( i=0; i<"${#input}"; i++ )) ; do :
    for (( j=0; j<"${#lcs}"; j++ )) ; do :
        if [[ "${input:$i:1}" == "${lcs:$j:1}" ]] ; then
            input="${input/${input:$i:1}/${ucs:$j:1}}" 
        fi
    done
done

Simple C-style for loop to iterate through the strings. For the line below if you have not seen anything like this before this is where I learned this. In this case the line checks if the char ${input:$i:1} (lower case) exists in input and if so replaces it with the given char ${ucs:$j:1} (upper case) and stores it back into input.

input="${input/${input:$i:1}/${ucs:$j:1}}"

java comparator, how to sort by integer?

Simply changing

public int compare(Dog d, Dog d1) {
  return d.age - d1.age;
}

to

public int compare(Dog d, Dog d1) {
  return d1.age - d.age;
}

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable<Dog> {
    private String name;
    private int age;

    public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {
        // Overriding the compare method to sort the age
        public int compare(Dog d, Dog d1) {
            return d.age - d1.age;
        }
    };

    Dog(String n, int a) {
        name = n;
        age = a;
    }

    public String getDogName() {
        return name;
    }

    public int getDogAge() {
        return age;
    }

    // Overriding the compareTo method
    public int compareTo(Dog d) {
        return (this.name).compareTo(d.name);
    }

}

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator
Collections.sort(list, Dog.DESCENDING_COMPARATOR);

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2: Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3: With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator<Dog> DESCENDING_COMPARATOR = 
    Comparator.comparing(Dog::getDogAge).reversed();

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {
    return DESCENDING_COMPARATOR.compare(d, d1);
}

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

Best Way to View Generated Source of Webpage?

I was able to solve a similar issue by logging the results of the ajax call to the console. This was the html returned and I could easily see any issues that it had.

in my .done() function of my ajax call I added console.log(results) so I could see the html in the debugger console.

_x000D_
_x000D_
function GetReversals() {_x000D_
    $("#getReversalsLoadingButton").removeClass("d-none");_x000D_
    $("#getReversalsButton").addClass("d-none");_x000D_
_x000D_
    $.ajax({_x000D_
        url: '/Home/LookupReversals',_x000D_
        data: $("#LookupReversals").serialize(),_x000D_
        type: 'Post',_x000D_
        cache: false_x000D_
    }).done(function (result) {_x000D_
        $('#reversalResults').html(result);_x000D_
        console.log(result);_x000D_
    }).fail(function (jqXHR, textStatus, errorThrown) {_x000D_
        //alert("There was a problem getting results.  Please try again. " + jqXHR.responseText + " | " + jqXHR.statusText);_x000D_
        $("#reversalResults").html("<div class='text-danger'>" + jqXHR.responseText + "</div>");_x000D_
    }).always(function () {_x000D_
        $("#getReversalsLoadingButton").addClass("d-none");_x000D_
        $("#getReversalsButton").removeClass("d-none");_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

How do I run SSH commands on remote system using Java?

JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.

You can use exec.java.

LEFT OUTER JOIN in LINQ

This is a SQL syntax compare to LINQ syntax for inner and left outer joins. Left Outer Join:

http://www.ozkary.com/2011/07/linq-to-entity-inner-and-left-joins.html

"The following example does a group join between product and category. This is essentially the left join. The into expression returns data even if the category table is empty. To access the properties of the category table, we must now select from the enumerable result by adding the from cl in catList.DefaultIfEmpty() statement.

Cross field validation with Hibernate Validator (JSR 303)

I'm surprised this isn't available out of the box. Anyway, here is a possible solution.

I've created a class level validator, not the field level as described in the original question.

Here is the annotation code:

package com.moa.podium.util.constraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = MatchesValidator.class)
@Documented
public @interface Matches {

  String message() default "{com.moa.podium.util.constraints.matches}";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};

  String field();

  String verifyField();
}

And the validator itself:

package com.moa.podium.util.constraints;

import org.mvel2.MVEL;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MatchesValidator implements ConstraintValidator<Matches, Object> {

  private String field;
  private String verifyField;


  public void initialize(Matches constraintAnnotation) {
    this.field = constraintAnnotation.field();
    this.verifyField = constraintAnnotation.verifyField();
  }

  public boolean isValid(Object value, ConstraintValidatorContext context) {
    Object fieldObj = MVEL.getProperty(field, value);
    Object verifyFieldObj = MVEL.getProperty(verifyField, value);

    boolean neitherSet = (fieldObj == null) && (verifyFieldObj == null);

    if (neitherSet) {
      return true;
    }

    boolean matches = (fieldObj != null) && fieldObj.equals(verifyFieldObj);

    if (!matches) {
      context.disableDefaultConstraintViolation();
      context.buildConstraintViolationWithTemplate("message")
          .addNode(verifyField)
          .addConstraintViolation();
    }

    return matches;
  }
}

Note that I've used MVEL to inspect the properties of the object being validated. This could be replaced with the standard reflection APIs or if it is a specific class you are validating, the accessor methods themselves.

The @Matches annotation can then be used used on a bean as follows:

@Matches(field="pass", verifyField="passRepeat")
public class AccountCreateForm {

  @Size(min=6, max=50)
  private String pass;
  private String passRepeat;

  ...
}

As a disclaimer, I wrote this in the last 5 minutes, so I probably haven't ironed out all the bugs yet. I'll update the answer if anything goes wrong.

Difference between "on-heap" and "off-heap"

The heap is the place in memory where your dynamically allocated objects live. If you used new then it's on the heap. That's as opposed to stack space, which is where the function stack lives. If you have a local variable then that reference is on the stack. Java's heap is subject to garbage collection and the objects are usable directly.

EHCache's off-heap storage takes your regular object off the heap, serializes it, and stores it as bytes in a chunk of memory that EHCache manages. It's like storing it to disk but it's still in RAM. The objects are not directly usable in this state, they have to be deserialized first. Also not subject to garbage collection.

Is 'bool' a basic datatype in C++?

Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

In my case, my button's type is submit not button and I change the Click to Sumbit then every work good. Something like below,

from driver.FindElement(By.Id("btnLogin")).Click();

to driver.FindElement(By.Id("btnLogin")).Submit();

BTW, I have been tried all the answer in this post but not work for me.

Expand a random range from 1–5 to 1–7

Would be cool if someone could give me feedback on this one, I used the JUNIT without assert Pattern because it's easy and fast to get it running in Eclipse, I could also have just defined a main method. By the way, I am assuming rand5 gives values 0-4, adding 1 would make it 1-5, same with rand7... So the discussion should be on the solution, it's distribution, not on wether it goes from 0-4 or 1-5...

package random;

import java.util.Random;

import org.junit.Test;

public class RandomTest {


    @Test
    public void testName() throws Exception {
        long times = 100000000;
        int indexes[] = new int[7];
        for(int i = 0; i < times; i++) {
            int rand7 = rand7();
            indexes[rand7]++;
        }

        for(int i = 0; i < 7; i++)
            System.out.println("Value " + i + ": " + indexes[i]);
    }


    public int rand7() {
        return (rand5() + rand5() + rand5() + rand5() + rand5() + rand5() + rand5()) % 7;
    }


    public int rand5() {
        return new Random().nextInt(5);
    }


}

When I run it, I get this result:

Value 0: 14308087
Value 1: 14298303
Value 2: 14279731
Value 3: 14262533
Value 4: 14269749
Value 5: 14277560
Value 6: 14304037

This seems like a very fair distribution, doesn't it?

If I add rand5() less or more times (where the amount of times is not divisible by 7), the distribution clearly shows offsets. For instance, adding rand5() 3 times:

Value 0: 15199685
Value 1: 14402429
Value 2: 12795649
Value 3: 12796957
Value 4: 14402252
Value 5: 15202778
Value 6: 15200250

So, this would lead to the following:

public int rand(int range) {
    int randomValue = 0;
    for(int i = 0; i < range; i++) {
        randomValue += rand5();
    }
    return randomValue % range;

}

And then, I could go further:

public static final int ORIGN_RANGE = 5;
public static final int DEST_RANGE  = 7;

@Test
public void testName() throws Exception {
    long times = 100000000;
    int indexes[] = new int[DEST_RANGE];
    for(int i = 0; i < times; i++) {
        int rand7 = convertRand(DEST_RANGE, ORIGN_RANGE);
        indexes[rand7]++;
    }

    for(int i = 0; i < DEST_RANGE; i++)
        System.out.println("Value " + i + ": " + indexes[i]);
}


public int convertRand(int destRange, int originRange) {
    int randomValue = 0;
    for(int i = 0; i < destRange; i++) {
        randomValue += rand(originRange);
    }
    return randomValue % destRange;

}


public int rand(int range) {
    return new Random().nextInt(range);
}

I tried this replacing the destRange and originRange with various values (even 7 for ORIGIN and 13 for DEST), and I get this distribution:

Value 0: 7713763
Value 1: 7706552
Value 2: 7694697
Value 3: 7695319
Value 4: 7688617
Value 5: 7681691
Value 6: 7674798
Value 7: 7680348
Value 8: 7685286
Value 9: 7683943
Value 10: 7690283
Value 11: 7699142
Value 12: 7705561

What I can conclude from here is that you can change any random to anyother by suming the origin random "destination" times. This will get a kind of gaussian distribution (being the middle values more likely, and the edge values more uncommon). However, the modulus of destination seems to distribute itself evenly across this gaussian distribution... It would be great to have feedback from a mathematician...

What is cool is that the cost is 100% predictable and constant, whereas other solutions cause a small probability of infinite loop...

Swift: Display HTML data in a label or textView

Display images and text paragraphs is not possible in a UITextView or UILabel, to this, you must use a UIWebView.

Just add the item in the storyboard, link to your code, and call it to load the URL.

OBJ-C

NSString *fullURL = @"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];

Swift

let url = NSURL (string: "http://www.sourcefreeze.com");
let requestObj = NSURLRequest(URL: url!);
viewWeb.loadRequest(requestObj);

Step by step tutorial. http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

Error with multiple definitions of function

This problem happens because you are calling fun.cpp instead of fun.hpp. So c++ compiler finds func.cpp definition twice and throws this error.

Change line 3 of your main.cpp file, from #include "fun.cpp" to #include "fun.hpp" .

How to Validate on Max File Size in Laravel?

According to the documentation:

$validator = Validator::make($request->all(), [
    'file' => 'max:500000',
]);

The value is in kilobytes. I.e. max:10240 = max 10 MB.

Getting a machine's external IP address with Python

If you are not interested in hitting any url to get public ip, I think following code can help you to get public ip using python of your machine

import os
externalIP  = os.popen("ifconfig | grep 'inet' | cut -d: -f2 | awk '{print $2}' | sed -n 3p").readline()
print externalIP

sed -n 3p line varies as per the network you are using for connecting device.

I was facing same issue, I was needed public ip of iot device which is hitting my server. but public ip is totally different in ifconfig command and ip i am getting in server from request object. after this I am adding extra param into my request to send ip of device to my server.

hope this is helpful

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

Can't connect to localhost on SQL Server Express 2012 / 2016

First check SQL Server Service is Running or stopped, if it is stopped just start it, to do so..just follow the below steps.

1.Start -> Run ->Services.msc

enter image description here

  1. Go to Standard tab in services panel then search for SQl Server(SQL2014)

"SQL2014" is given By me, it may be Another Name in your case

enter image description here

that's it once you start the SQL Service, you are able to connect local database.

hope it will help someone.

How to specify the port an ASP.NET Core application is hosted on?

Go to properties/launchSettings.json and find your appname and under this, find applicationUrl. you will see, it is running localhost:5000, change it to whatever you want. and then run dotnet run...... hurrah

Windows task scheduler error 101 launch failure code 2147943785

The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job

Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).

Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.

Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Does it make sense to use Require.js with Angular.js?

Short answer is, it make sense. Recently this was discussed in ng-conf 2014. Here is the talk on this topic:

http://www.youtube.com/watch?v=4yulGISBF8w

Forward X11 failed: Network error: Connection refused

X display location : localhost:0 Worked for me :)

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

As professional testers, my friends use Spoon.net browsers section to test compatibility of site in various browsers. Hope this should help you.

Different ways of clearing lists

del list[:] 

Will delete the values of that list variable

del list

Will delete the variable itself from memory

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()

print(df)

output

   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

Assert equals between 2 Lists in Junit

Don't reinvent the wheel!

There's a Google Code library that does this for you: Hamcrest

[Hamcrest] Provides a library of matcher objects (also known as constraints or predicates) allowing 'match' rules to be defined declaratively, to be used in other frameworks. Typical scenarios include testing frameworks, mocking libraries and UI validation rules.

How does one extract each folder name from a path?

There are a few ways that a file path can be represented. You should use the System.IO.Path class to get the separators for the OS, since it can vary between UNIX and Windows. Also, most (or all if I'm not mistaken) .NET libraries accept either a '\' or a '/' as a path separator, regardless of OS. For this reason, I'd use the Path class to split your paths. Try something like the following:

string originalPath = "\\server\\folderName1\\another\ name\\something\\another folder\\";
string[] filesArray = originalPath.Split(Path.AltDirectorySeparatorChar,
                              Path.DirectorySeparatorChar);

This should work regardless of the number of folders or the names.

Configure WAMP server to send email

I tried Test Mail Server Tool and while it worked great, you still need to open the email on some client.

I found Papercut: https://papercut.codeplex.com/

For configuration it's easy as Test Mail Server Tool (pratically zero-conf), and it also serves as an email client, with views for the Message (great for HTML emails), Headers, Body (to inspect the HTML) and Raw (full unparsed email).

It also has a Sections view, to split up the different media types found in the email.

It has a super clean and friendly UI, a good log viewer and gives you notifications when you receive an email.

I find it perfect, so I just wanted to give my 2c and maybe help someone.

How can I use JavaScript in Java?

I just wanted to answer something new for this question - J2V8.

Author Ian Bull says "Rhino and Nashorn are two common JavaScript runtimes, but these did not meet our requirements in a number of areas:

Neither support ‘Primitives‘. All interactions with these platforms require wrapper classes such as Integer, Double or Boolean. Nashorn is not supported on Android. Rhino compiler optimizations are not supported on Android. Neither engines support remote debugging on Android.""

Highly Efficient Java & JavaScript Integration

Github link

Convert decimal to binary in python

For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:

  1. Get the integer and fractional part.

    from decimal import *
    a = Decimal(3.625)
    a_split = (int(a//1),a%1)
    
  2. Convert the fractional part in its binary representation. To achieve this multiply successively by 2.

    fr = a_split[1]
    str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
    

You can read the explanation here.

Replace all whitespace with a line break/paragraph mark to make a word list

You can also do it with xargs:

cat old | xargs -n1 > new

or

xargs -n1 < old > new

How do you create an asynchronous HTTP request in JAVA?

Note that java11 now offers a new HTTP api HttpClient, which supports fully asynchronous operation, using java's CompletableFuture.

It also supports a synchronous version, with calls like send, which is synchronous, and sendAsync, which is asynchronous.

Example of an async request (taken from the apidoc):

   HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://example.com/"))
        .timeout(Duration.ofMinutes(2))
        .header("Content-Type", "application/json")
        .POST(BodyPublishers.ofFile(Paths.get("file.json")))
        .build();
   client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println);

rsync error: failed to set times on "/foo/bar": Operation not permitted

I had the same problem. For me the solution is to delete the remote file and let rsync create again.

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

How do you run `apt-get` in a dockerfile behind a proxy?

As suggested by other answers, --build-arg may be the solution. In my case, I had to add --network=host in addition to the --build-arg options.

docker build -t <TARGET> --build-arg http_proxy=http://<IP:PORT> --build-arg https_proxy=http://<IP:PORT> --network=host .

Nested JSON objects - do I have to use arrays for everything?

Every object has to be named inside the parent object:

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

So you cant declare an object like this:

var obj = {property1, property2};

It has to be

var obj = {property1: 'value', property2: 'value'};

How to install package from github repo in Yarn

For ssh style urls just add ssh before the url:

yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>

Where does Java's String constant pool live, the heap or the stack?

As other answers explain Memory in Java is divided into two portions

1. Stack: One stack is created per thread and it stores stack frames which again stores local variables and if a variable is a reference type then that variable refers to a memory location in heap for the actual object.

2. Heap: All kinds of objects will be created in heap only.

Heap memory is again divided into 3 portions

1. Young Generation: Stores objects which have a short life, Young Generation itself can be divided into two categories Eden Space and Survivor Space.

2. Old Generation: Store objects which have survived many garbage collection cycles and still being referenced.

3. Permanent Generation: Stores metadata about the program e.g. runtime constant pool.

String constant pool belongs to the permanent generation area of Heap memory.

We can see the runtime constant pool for our code in the bytecode by using javap -verbose class_name which will show us method references (#Methodref), Class objects ( #Class ), string literals ( #String )

runtime-constant-pool

You can read more about it on my article How Does JVM Handle Method Overloading and Overriding Internally.

How can I convert a Unix timestamp to DateTime and vice versa?

public static class UnixTime
    {
        private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        public static DateTime UnixTimeToDateTime(double unixTimeStamp)
        {
            return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();
        }
    }

you can call UnixTime.UnixTimeToDateTime(double datetime))

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

None of the other answers worked for me.

Make sure both unzipped files are in same folder, but also right click on setup.exe, select properties, compatibility, and then put a checkmark in "Run this program in compatibility mode for..." and select Windows 7.

I successfully launched the installer without the error message on Windows 10 for the 32-bit version of Oracle 11g release 2.

From: http://www-01.ibm.com/support/docview.wss?uid=swg21960606