Programs & Examples On #Lookupfield

Sqlite or MySql? How to decide?

SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.

You should definitely go with MySQL or PostgreSQL.

If it is for a single-person project, SQLite will be easier to setup though.

Complexities of binary tree traversals

In-order, Pre-order, and Post-order traversals are Depth-First traversals.

For a Graph, the complexity of a Depth First Traversal is O(n + m), where n is the number of nodes, and m is the number of edges.

Since a Binary Tree is also a Graph, the same applies here. The complexity of each of these Depth-first traversals is O(n+m).

Since the number of edges that can originate from a node is limited to 2 in the case of a Binary Tree, the maximum number of total edges in a Binary Tree is n-1, where n is the total number of nodes.

The complexity then becomes O(n + n-1), which is O(n).

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

How to Validate Google reCaptcha on Form Submit

While using Google reCaptcha with reCaptcha DLL file, we can validate it in C# as follows :

 RecaptchaControl1.Validate();
        bool _Varify = RecaptchaControl1.IsValid;
        if (_Varify)
        {
// Pice of code after validation.
}

Its works for me.

How to close current tab in a browser window?

Try this

<a href="javascript:window.open('','_self').close();">close</a>

Why doesn't file_get_contents work?

If it is a local file, you have to wrap it in htmlspecialchars like so:

    $myfile = htmlspecialchars(file_get_contents($file_name));

Then it works

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

There are three ways to solve this issue.

  1. Ignore Precompiled Headers #1
    Steps: Project > Properties > Configuration Properties > C/C++ > Command Line > in the Additional Options box add /Y-. (Screenshot of Property Pages) > Ok > Remove #include "stdafx.h"
  2. Ignore Precompiled Headers #2
    Steps: File > New > Project > ... > In the Application Wizard Window click Next > Uncheck the Precompiled Header box > Finish > Remove #include "stdafx.h"
  3. Reinstall Visual Studio
    This also worked for me, because I realized that maybe there was something wrong with my Windows SDK. I was using Windows 10, but with Windows SDK 8.1. You may have this problem as well.
    Steps: Open Visual Studio Installer > Click on the three-lined Menu Bar > Uninstall > Restart your computer > Open Visual Studio Installer > Install what you want, but make sure you install only the latest Windows SDK 10, not multiple ones nor the 8.1.

    The first time I installed Visual Studio, I would get an error stating that I needed to install Windows SDK 8.1. So I did, through Visual Studio Installer's Modify option. Perhaps this was a problem because I was installed it after Visual Studio was already installed, or because I needed SDK 10 instead. Just to be safe I did a complete reinstall.

What’s the difference between Response.Write() andResponse.Output.Write()?

See this:

The difference between Response.Write() and Response.Output.Write() in ASP.NET. The short answer is that the latter gives you String.Format-style output and the former doesn't. The long answer follows.

In ASP.NET the Response object is of type HttpResponse and when you say Response.Write you're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse.

Response.Write then calls .Write() on it's internal TextWriter object:

public void Write(object obj){ this._writer.Write(obj);} 

HttpResponse also has a Property called Output that is of type, yes, TextWriter, so:

public TextWriter get_Output(){ return this._writer; } 

Which means you can do the Response whatever a TextWriter will let you. Now, TextWriters support a Write() method aka String.Format, so you can do this:

Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);

But internally, of course, this is happening:

public virtual void Write(string format, params object[] arg)
{ 
this.Write(string.Format(format, arg)); 
}

How to update Android Studio automatically?

For this task, I recommend using Android Studio IDE and choose the automatic installation program, and not the compressed file.

  1. On the top menu, select Help -> Check for Update...
  2. Upon the updates dialog below, select Updates link to configure your IDE settings.

Platform and Plugin Updates

  1. For checking updates, my suggestion is to select the Dev channel. I

don't recommend Beta or Canary

channel which is the unstable version and they are not automatic installation, instead a zip file is provided in that case.

Updates dialog

  1. When finished with the configuration, select Update and Restart for downloading the installation EXE.
  2. Run the installation.

Warning: Among different version of Android Studio, the steps may be different. But hopefully you get the idea, as I try to be clear on my intentions.

Extra info: If you want, check for Android Studio updates @ Android Tools Project Site - Recent Builds. This web page seems to be more accurate than other Android pages about tool updates.

What is the best IDE for PHP?

PHPEclipse is as close to Eclipse java power as it could get. Eclipse PDT is much weaker (last time I checked).

How to use a PHP class from another file?

Use include("class.classname.php");

And class should use <?php //code ?> not <? //code ?>

How do I run a program from command prompt as a different user and as an admin

Runas doesn't magically run commands as an administrator, it runs them as whatever account you provide credentials for. If it's not an administrator account, runas doesn't care.

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files.

import d6tstack
c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx')
c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv']

See d6tstack Excel examples

Why is the minidlna database not being refreshed?

I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.

ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).

I'm still trying to find a way around this. If anyone has any input, it's most welcome.

Why is there no ForEach extension method on IEnumerable?

You can use select when you want to return something. If you don't, you can use ToList first, because you probably don't want to modify anything in the collection.

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

As a supplement to the question and above answers there is also an important difference between plt.subplots() and plt.subplot(), notice the missing 's' at the end.

One can use plt.subplots() to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.

# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

Whereas, you can use plt.subplot() if you want to add the subplots separately. It returns only the axis of one subplot.

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

However, plt.subplots() is preferred because it gives you easier options to directly customize your whole figure

# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

Shared axes whereas, with plt.subplot(), one will have to specify individually for each axis which can become cumbersome.

Detect application heap size in Android

Runtime rt = Runtime.getRuntime();
rt.maxMemory()

value is b

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.getMemoryClass()

value is MB

Add a new line to a text file in MS-DOS

You can easily append to the end of a file, by using the redirection char twice (>>).


This will copy source.txt to destination.txt, overwriting destination in the process:

type source.txt > destination.txt

This will copy source.txt to destination.txt, appending to destination in the process:

type source.txt >> destination.txt

How to loop through files matching wildcard in batch file

Echoing f.in and f.out will seperate the concept of what to loop and what not to loop when used in a for /f loop.

::Get the files seperated
echo f.in>files_to_pass_through.txt
echo f.out>>files_to_pass_through.txt

for /F %%a in (files_to_pass_through.txt) do (
for /R %%b in (*.*) do (
if "%%a" NEQ "%%b" (
echo %%b>>dont_pass_through_these.txt
)
)
)
::I'm assuming the base name is the whole string "f".
::If I'm right then all the files begin with "f".
::So all you have to do is display "f". right?
::But that would be too easy.
::Let's do this the right way.
for /f %%C in (dont_pass_through_these.txt)
::displays the filename and not the extention
echo %~nC
)

Although you didn't ask, a good way to pass commands into f.in and f.out would be to...

for /F %%D "tokens=*" in (dont_pass_through_these.txt) do (
for /F %%E in (%%D) do (
start /wait %%E
)
)

A link to all the Windows XP commands:link

I apologize if I did not answer this correctly. The question was very hard for me to read.

How can I check if my Element ID has focus?

Write below code in script and also add jQuery library

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')
            }
        });
    }

Thank you...

convert HTML ( having Javascript ) to PDF using JavaScript

With Docmosis or JODReports you could feed your HTML and Javascript to the document render process which could produce PDF or doc or other formats. The conversion underneath is performed by OpenOffice so results will be dependent on the OpenOffice import filters. You can try manually by saving your web page to a file, then loading with OpenOffice - if that looks good enough, then these tools will be able to give you the same result as a PDF.

Error when creating a new text file with python?

You can use open(name, 'a')

However, when you enter filename, use inverted commas on both sides, otherwise ".txt"cannot be added to filename

psql: FATAL: Peer authentication failed for user "dev"

Try:

psql -U user_name  -h 127.0.0.1 -d db_name

where

  • -U is the database user name
  • -h is the hostname/IP of the local server, thus avoiding Unix domain sockets
  • -d is the database name to connect to

This is then evaluated as a "network" connection by Postgresql rather than a Unix domain socket connection, thus not evaluated as a "local" connect as you might see in pg_hba.conf:

local   all             all                                     peer

How do you validate a URL with a regular expression in Python?

Nowadays, in 90% of case if you working with URL in Python you probably use python-requests. Hence the question here - why not reuse URL validation from requests?

from requests.models import PreparedRequest
import requests.exceptions


def check_url(url):
    prepared_request = PreparedRequest()
    try:
        prepared_request.prepare_url(url, None)
        return prepared_request.url
    except requests.exceptions.MissingSchema, e:
        raise SomeException

Features:

  • Don't reinvent the wheel
  • DRY
  • Work offline
  • Minimal resource

Importing variables from another file?

first.py:

a=5

second.py:

import first
print(first.a)

The result will be 5.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

How to get the number of threads in a Java process

    public class MainClass {

        public static void main(String args[]) {

          Thread t = Thread.currentThread();
          t.setName("My Thread");

          t.setPriority(1);

          System.out.println("current thread: " + t);

          int active = Thread.activeCount();
          System.out.println("currently active threads: " + active);
          Thread all[] = new Thread[active];
          Thread.enumerate(all);

          for (int i = 0; i < active; i++) {
             System.out.println(i + ": " + all[i]);
          }
       }
   }

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

Update 2016:

Modern browser behave much better. All you should need to do is to set the image width to 100% (demo)

.container img {
   width: 100%;
}

Since you don't know the aspect ratio, you'll have to use some scripting. Here is how I would do it with jQuery (demo):

CSS

.container {
    width: 40%;
    height: 40%;
    background: #444;
    margin: 0 auto;
}
.container img.wide {
    max-width: 100%;
    max-height: 100%;
    height: auto;
}
.container img.tall {
    max-height: 100%;
    max-width: 100%;
    width: auto;
}?

HTML

<div class="container">
 <img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>
<br />
<br />
<div class="container">
 <img src="http://i47.tinypic.com/i1bek8.jpg" />
</div>

Script

$(window).load(function(){
 $('.container').find('img').each(function(){
  var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
  $(this).addClass(imgClass);
 })
})

How to find sum of multiple columns in a table in SQL Server 2005?

Another example using COALESCE. http://sqlmag.com/t-sql/coalesce-vs-isnull

SELECT (COALESCE(SUM(val1),0) + COALESCE(SUM(val2), 0)
+ COALESCE(SUM(val3), 0) + COALESCE(SUM(val4), 0)) AS 'TOTAL'
FROM Emp

Create an instance of a class from a string

For instance, if you store values of various types in a database field (stored as string) and have another field with the type name (i.e., String, bool, int, MyClass), then from that field data, you could, conceivably, create a class of any type using the above code, and populate it with the value from the first field. This of course depends on the type you are storing having a method to parse strings into the correct type. I've used this many times to store user preference settings in a database.

How do I select an element that has a certain class?

h2.myClass refers to all h2 with class="myClass".

.myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

If you want the h2 in your HTML to appear blue, change the CSS to the following:

.myClass h2 {
    color: blue;
}

If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

ORA-01843 not a valid month- Comparing Dates

ALTER session set NLS_LANGUAGE=’AMERICAN’;

Converting a string to a date in JavaScript

You can using regex to parse string to detail time then create date or any return format like :

//example : let dateString = "2018-08-17 01:02:03.4"

function strToDate(dateString){
    let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
  , [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
  return dateObject;
}
alert(strToDate(dateString));

In JavaScript can I make a "click" event fire programmatically for a file input element?

I know this is old, and all these solutions are hacks around browser security precautions with real value.

That said, as of today, fileInput.click() works in current Chrome (36.0.1985.125 m) and current Firefox ESR (24.7.0), but not in current IE (11.0.9600.17207). Overlaying a file field with opacity 0 on top of a button works, but I wanted a link element as the visible trigger, and hover underlining doesn't quite work in any browser. It flashes on then disappears, probably the browser thinking through whether hover styling actually applies or not.

But I did find a solution that works in all those browsers. I won't claim to have tested every version of every browser, or that I know it'll continue to work forever, but it appears to meet my needs now.

It's simple: Position the file input field offscreen (position: absolute; top: -5000px), put a label element around it, and trigger the click on the label, instead of the file field itself.

Note that the link does need to be scripted to call the click method of the label, it doesn't do that automatically, like when you click on text inside a label element. Apparently the link element captures the click, and it doesn't make it through to the label.

Note also that this doesn't provide a way to show the currently selected file, since the field is offscreen. I wanted to submit immediately when a file was selected, so that's not a problem for me, but you'll need a somewhat different approach if your situation is different.

Use -notlike to filter out multiple strings in PowerShell

$listOfUsernames = @("user1", "user2", "etc", "and so on")
Get-EventLog -LogName Security | 
    where { $_.Username -notmatch (
        '(' + [string]::Join(')|(', $listOfUsernames) + ')') }

It's a little crazy I'll grant you, and it fails to escape the usernames (in the unprobable case a username uses a Regex escape character like '\' or '(' ), but it works.

As "slipsec" mentioned above, use -notcontains if possible.

assign headers based on existing row in dataframe in R

A new answer that uses dplyr and tidyr:

Extracts the desired column names and converts to a list

library(tidyverse)

col_names <- raw_dta %>% 
  slice(2) %>%
  pivot_longer(
    cols = "X2":"X10", # until last named column
    names_to = "old_names",
    values_to = "new_names") %>% 
  pull(new_names)

Removes the incorrect rows and adds the correct column names

dta <- raw_dta %>% 
  slice(-1, -2) %>% # Removes the rows containing new and original names
  set_names(., nm = col_names)

android adb turn on wifi via adb

No need to edit any database directly, there is a command for it :)

svc wifi [enable|disable]

Rails: Check output of path helper from console

you can also

include Rails.application.routes.url_helpers

from inside a console sessions to access the helpers:

url_for controller: :users, only_path: true
users_path
# => '/users'

or

Rails.application.routes.url_helpers.users_path

SQLite Query in Android to count rows

int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();

What is the best way to get the count/length/size of an iterator?

Using Guava library:

int size = Iterators.size(iterator);

Internally it just iterates over all elements so its just for convenience.

Mouseover or hover vue.js

To show child or sibling elements it's possible with CSS only. If you use :hover before combinators (+, ~, >, space). Then the style applies not to hovered element.

HTML

<body>
  <div class="trigger">
    Hover here.
  </div>
  <div class="hidden">
    This message shows up.
  </div>
</body>

CSS

.hidden { display: none; }
.trigger:hover + .hidden { display: inline; }

How to ensure that there is a delay before a service is started in systemd?

You can create a .timer systemd unit file to control the execution of your .service unit file.

So for example, to wait for 1 minute after boot-up before starting your foo.service, create a foo.timer file in the same directory with the contents:

[Timer]
OnBootSec=1min

It is important that the service is disabled (so it doesn't start at boot), and the timer enabled, for all this to work (thanks to user tride for this):

systemctl disable foo.service
systemctl enable foo.timer

You can find quite a few more options and all information needed here: https://wiki.archlinux.org/index.php/Systemd/Timers

Access denied for root user in MySQL command-line

By default there is no password is set for root user in XAMPP.

You can set password for root user of MySQL.

Navigate to

localhost:80/security/index.php

and set password for root user.

Note:Please change the port number in above url if your Apache in on different port.

Open XAMPP control panel Click "Shell" button

Command prompt window will open now in that window type

mysql -u root -p;

It will ask for password type the password which you have set for root user.

There you go ur logged in as root user :D Now do what u want to do :P

Jquery Hide table rows

This should do the trick.

$(textInput).closest("tr").hide();

PHP mail function doesn't complete sending of e-mail

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info: <?php phpinfo(); ?>. Open this page, and look for sendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only -t -i, then edit your server's php.ini and add the following line: sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHP mail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch from mail() to PHPMailer with SMTP, after all.

How do I get the first element from an IEnumerable<T> in .net?

Well, you didn't specify which version of .Net you're using.

Assuming you have 3.5, another way is the ElementAt method:

var e = enumerable.ElementAt(0);

Is there a way to make text unselectable on an HTML page?

For an example of why it might be desirable to suppress selection, see SIMILE TImeline, which uses drag-and-drop to explore the timeline, during which accidental vertical mouse movement causes the labels to be highlighted unexpectedly, which looks weird.

java: How can I do dynamic casting of a variable from one type to another?

You'll need to write sort of ObjectConverter for this. This is doable if you have both the object which you want to convert and you know the target class to which you'd like to convert to. In this particular case you can get the target class by Field#getDeclaringClass().

You can find here an example of such an ObjectConverter. It should give you the base idea. If you want more conversion possibilities, just add more methods to it with the desired argument and return type.

Clear and refresh jQuery Chosen dropdown list

$("#idofBtn").click(function(){
        $('#idofdropdown').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#idofdropdown').append(newOption);
        $('#idofdropdown').trigger("chosen:updated");
    });

DateTime group by date and hour

Using MySQL I usually do it that way:

SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;

Or in the same idea, if you need to output the date/hour:

SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM  your_table 
GROUP BY my_date
order by your_date_column desc;

If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

Null vs. False vs. 0 in PHP

null is null. false is false. Sad but true.

there's not much consistency in PHP (though it is improving on latest releases, there's too much backward compatibility). Despite the design wishing some consistency (outlined in the selected answer here), it all get confusing when you consider method returns that use false/null in not-so-easy to reason ways.

You will often see null being used when they are already using false for something. e.g. filter_input(). They return false if the variable fails the filter, and null if the variable does not exists (does not existing means it also failed the filter?)

Methods returning false/null/string/etc interchangeably is a hack when the author care about the type of failure, for example, with filter_input() you can check for ===false or ===null if you care why the validation failed. But if you don't it might be a pitfall as one might forget to add the check for ===null if they only remembered to write the test case for ===false. And most php unit test/coverage tools will not call your attention for the missing, untested code path!

Lastly, here's some fun with type juggling. not even including arrays or objects.

var_dump( 0<0 );        #bool(false)
var_dump( 1<0 );        #bool(false)
var_dump( -1<0 );       #bool(true)
var_dump( false<0 );    #bool(false)
var_dump( null<0 );     #bool(false)
var_dump( ''<0 );       #bool(false)
var_dump( 'a'<0 );      #bool(false)
echo "\n";
var_dump( !0 );        #bool(true)
var_dump( !1 );        #bool(false)
var_dump( !-1 );       #bool(false)
var_dump( !false );    #bool(true)
var_dump( !null );     #bool(true)
var_dump( !'' );       #bool(true)
var_dump( !'a' );      #bool(false)
echo "\n";
var_dump( false == 0 );        #bool(true)
var_dump( false == 1 );        #bool(false)
var_dump( false == -1 );       #bool(false)
var_dump( false == false );    #bool(true)
var_dump( false == null );     #bool(true)
var_dump( false == '' );       #bool(true)
var_dump( false == 'a' );      #bool(false)
echo "\n";
var_dump( null == 0 );        #bool(true)
var_dump( null == 1 );        #bool(false)
var_dump( null == -1 );       #bool(false)
var_dump( null == false );    #bool(true)
var_dump( null == null );     #bool(true)
var_dump( null == '' );       #bool(true)
var_dump( null == 'a' );      #bool(false)
echo "\n";
$a=0; var_dump( empty($a) );        #bool(true)
$a=1; var_dump( empty($a) );        #bool(false)
$a=-1; var_dump( empty($a) );       #bool(false)
$a=false; var_dump( empty($a) );    #bool(true)
$a=null; var_dump( empty($a) );     #bool(true)
$a=''; var_dump( empty($a) );       #bool(true)
$a='a'; var_dump( empty($a));      # bool(false)
echo "\n"; #new block suggested by @thehpi
var_dump( null < -1 ); #bool(true)
var_dump( null < 0 ); #bool(false)
var_dump( null < 1 ); #bool(true)
var_dump( -1 > true ); #bool(false)
var_dump( 0 > true ); #bool(false)
var_dump( 1 > true ); #bool(true)
var_dump( -1 > false ); #bool(true)
var_dump( 0 > false ); #bool(false)
var_dump( 1 > true ); #bool(true)

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

Resource interpreted as Document but transferred with MIME type application/zip

I solved the problem by adding target="_blank" to the link. With this, chrome opens a new tab and loads the PDF without warning even in responsive mode.

Select rows with same id but different value in another column

This ought to do it:

SELECT *
FROM YourTable
WHERE ARIDNR IN (
    SELECT ARIDNR
    FROM YourTable
    GROUP BY ARIDNR
    HAVING COUNT(*) > 1
)

The idea is to use the inner query to identify the records which have a ARIDNR value that occurs 1+ times in the data, then get all columns from the same table based on that set of values.

How can I link to a specific glibc version?

You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.

One option is to statically link your binary. This is probably the easiest option.

You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.

According to the http://www.trevorpounds.com blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the blog post.

The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
{
    const char* unresolved = "/lib64";
    char resolved[PATH_MAX+1];

    if(!realpath(unresolved, resolved))
        { return 1; }

    printf("%s\n", resolved);

    return 0;
}

A non well formed numeric value encountered

Because you are passing a string as the second argument to the date function, which should be an integer.

string date ( string $format [, int $timestamp = time() ] )

Try strtotime which will Parse about any English textual datetime description into a Unix timestamp (integer):

date("d", strtotime($_GET['start_date']));

How to refer to Excel objects in Access VBA?

First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.

After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:

Dim xlApp as Excel.Application

Let's say you added an Excel Workbook Object in your Form and named it xLObject.

Here is how you Access a Sheet of this Object and change a Range

Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"

(I copied the above from my answer to this question)

Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)

How to calculate a mod b in Python?

A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0

Calculate median in c#

Is there a function in the .net Math library?

No.

It's not hard to write your own though. The naive algorithm sorts the array and picks the middle (or the average of the two middle) elements. However, this algorithm is O(n log n) while its possible to solve this problem in O(n) time. You want to look at selection algorithms to get such an algorithm.

How can I check if an InputStream is empty without reading from it?

If the InputStream you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:

input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
    //stream not empty
} else {
    //stream empty
} 

If you don't control what kind of InputStream you're using, you can use the markSupported() method to check whether mark/reset will work on the stream, and fall back to the available() method or the java.io.PushbackInputStream method otherwise.

How to tag docker image with docker-compose

Original answer Nov 20 '15:

No option for a specific tag as of Today. Docker compose just does its magic and assigns a tag like you are seeing. You can always have some script call docker tag <image> <tag> after you call docker-compose.

Now there's an option as described above or here

build: ./dir
image: webapp:tag

Substitute a comma with a line break in a cell

For some reason, none of the above worked for me. This DID however:

  1. Selected the range of cells I needed to replace.
  2. Go to Home > Find & Select > Replace or Ctrl + H
  3. Find what: ,
  4. Replace with: CTRL + SHIFT + J
  5. Click Replace All

Somehow CTRL + SHIFT + J is registered as a linebreak.

How do you get a string from a MemoryStream?

byte[] array = Encoding.ASCII.GetBytes("MyTest1 - MyTest2");
MemoryStream streamItem = new MemoryStream(array);

// convert to string
StreamReader reader = new StreamReader(streamItem);
string text = reader.ReadToEnd();

Find the last element of an array while using a foreach loop in PHP

So, if your array has unique array values, then determining last iteration is trivial:

foreach($array as $element) {
    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

As you see, this works if last element is appearing just once in array, otherwise you get a false alarm. In it is not, you have to compare the keys (which are unique for sure).

foreach($array as $key => $element) {
    end($array);
    if ($key === key($array))
        echo 'LAST ELEMENT!';
}

Also note the strict coparision operator, which is quite important in this case.

Use JavaScript to place cursor at end of text in text input element

input = $('input'); 
input.focus().val(input.val()+'.'); 
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}

How can I change the value of the elements in a vector?

Well, you could always run a transform over the vector:

std::transform(v.begin(), v.end(), v.begin(), [mean](int i) -> int { return i - mean; });

You could always also devise an iterator adapter that returns the result of an operation applied to the dereference of its component iterator when it's dereferenced. Then you could just copy the vector to the output stream:

std::copy(adapter(v.begin(), [mean](int i) -> { return i - mean; }), v.end(), std::ostream_iterator<int>(cout, "\n"));

Or, you could use a for loop...but that's kind of boring.

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

How to create separate AngularJS controller files?

Using the angular.module API with an array at the end will tell angular to create a new module:

myApp.js

// It is like saying "create a new module"
angular.module('myApp.controllers', []); // Notice the empty array at the end here

Using it without the array is actually a getter function. So to seperate your controllers, you can do:

Ctrl1.js

// It is just like saying "get this module and create a controller"
angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

During your javascript imports, just make sure myApp.js is after AngularJS but before any controllers / services / etc...otherwise angular won't be able to initialize your controllers.

gnuplot : plotting data from multiple input files in a single graph

You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.

e.g.

filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines

and

filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines

How can I match a string with a regex in Bash?

if [[ $STR == *pattern* ]]
then
    echo "It is the string!"
else
    echo "It's not him!"
fi

Works for me! GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Is the ternary operator faster than an "if" condition in Java

It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.

In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.

Open popup and refresh parent page on close popup

You can access parent window using 'window.opener', so, write something like the following in the child window:

<script>
    window.onunload = refreshParent;
    function refreshParent() {
        window.opener.location.reload();
    }
</script>

How store a range from excel into a Range variable?

Define what GetData is. At the moment it is not defined.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR

Getting Current date, time , day in laravel

use DateTime;

$now = new DateTime();

PHP and MySQL Select a Single Value

Try this

$value = mysql_result($result, 0);

Get dates from a week number in T-SQL

SELECT DATECOL - DATEPART(weekday, DATECOL), DATECOL - DATEPART(weekday, DATECOL) + 7

How to sort List<Integer>?

Use Collections class API to sort.

Collections.sort(list);

Read Excel File in Python

Although I almost always just use pandas for this, my current little tool is being packaged into an executable and including pandas is overkill. So I created a version of poida's solution that resulted in a list of named tuples. His code with this change would look like this:

from xlrd import open_workbook
from collections import namedtuple
from pprint import pprint

wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
OneRow = namedtuple('OneRow', ' '.join(FORMAT))
all_rows = []

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == headerRow[x].value]

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        all_rows.append(OneRow(*currentRowValues))

pprint(all_rows)

Converting Varchar Value to Integer/Decimal Value in SQL Server

Table structure...very basic:

create table tabla(ID int, Stuff varchar (50));

insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');

Query:

SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla

Or, try this:

SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla

Working on SQLServer 2008

How to get just one file from another branch

git checkout branch_name file_name

Example:

git checkout master App.java

This will not work if your branch name has a period in it.

git checkout "fix.june" alive.html
error: pathspec 'fix.june' did not match any file(s) known to git.

Google Maps API 3 - Custom marker color for default (dot) marker

In Internet Explorer, this solution does not work in ssl.

One can see the error in console as:

SEC7111: HTTPS security is compromised by this,

Workaround : As one of the user here suggested replace chart.apis.google.com to chart.googleapis.com for the URL path to avoid SSL error.

How to send an email from JavaScript

There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure. They have not yet started the service though.

C programming: Dereferencing pointer to incomplete type error

How did you actually define the structure? If

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

is to be taken as type definition, it's missing a typedef. When written as above, you actually define a variable called stasher_file, whose type is some anonymous struct type.

Try

typedef struct { ... } stasher_file;

(or, as already mentioned by others):

struct stasher_file { ... };

The latter actually matches your use of the type. The first form would require that you remove the struct before variable declarations.

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

systemd

sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

sysvinit

sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

Disable developer mode extensions pop up in Chrome

(In reply to Antony Hatchkins)

This is the current, literally official way to set Chrome policies: https://support.google.com/chrome/a/answer/187202?hl=en

The Windows and Linux templates, as well as common policy documentation for all operating systems, can be found here: https://dl.google.com/dl/edgedl/chrome/policy/policy_templates.zip (Zip file of Google Chrome templates and documentation)

Instructions for Windows (with my additions):

Open the ADM or ADMX template you downloaded:

  • Extract "chrome.adm" in the language of your choice from the "policy_templates.zip" downloaded earlier (e.g. "policy_templates.zip\windows\adm\en-US\chrome.adm").
  • Navigate to Start > Run: gpedit.msc.
  • Navigate to Local Computer Policy > Computer / User Configuration > Administrative Templates.
  • Right-click Administrative Templates, and select Add/Remove Templates.
  • Add the "chrome.adm" template via the dialog.
  • Once complete, Classic Administrative Templates (ADM) / Google / Google Chrome folder will appear under Administrative Templates.
  • No matter whether you add the template under Computer Configuration or User Configuration, the settings will appear in both places, so you can configure Chrome at a machine or a user level.

Once you're done with this, continue from step 5 of Antony Hatchkins' answer. After you have added the extension ID(s), you can check that the policy is working in Chrome by opening chrome://policy (search for ExtensionInstallWhitelist).

SQL Views - no variables?

Using functions as spencer7593 mentioned is a correct approach for dynamic data. For static data, a more performant approach which is consistent with SQL data design (versus the anti-pattern of writting massive procedural code in sprocs) is to create a separate table with the static values and join to it. This is extremely beneficial from a performace perspective since the SQL Engine can build effective execution plans around a JOIN, and you have the potential to add indexes as well if needed.

The disadvantage of using functions (or any inline calculated values) is the callout happens for every potential row returned, which is costly. Why? Because SQL has to first create a full dataset with the calculated values and then apply the WHERE clause to that dataset.

Nine times out of ten you should not need dynamically calculated cell values in your queries. Its much better to figure out what you will need, then design a data model that supports it, and populate that data model with semi-dynamic data (via batch jobs for instance) and use the SQL Engine to do the heavy lifting via standard SQL.

How to convert list of key-value tuples into dictionary?

>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}

HTML text-overflow ellipsis detection

Try this JS function, passing the span element as argument:

function isEllipsisActive(e) {
     return (e.offsetWidth < e.scrollWidth);
}

How do I get first element rather than using [0] in jQuery?

$("#grid_GridHeader:first") works as well.

How to sort Map values by key in Java?

Assuming TreeMap is not good for you (and assuming you can't use generics):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

How to get a index value from foreach loop in jstl

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

If you're behind a proxy, you should use X-Forwarded-For: http://en.wikipedia.org/wiki/X-Forwarded-For

It is an IETF draft standard with wide support:

The X-Forwarded-For field is supported by most proxy servers, including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache, IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks, Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP, Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo Networks' Maestro, Web Adjuster and Websense Web Security Gateway.

If not, here are a couple other common headers I've seen:

Import existing Gradle Git project into Eclipse

I have gone through this question earlier but did not found complete gui based solution.Today I got a GUI based solution provided by spring.

In short we need to do only that much:

1.Install plugin in eclipse from update site: site link

2.Import project as gradle and browse the .gradle file..that's it.

Complete documentation is here

How to use Git Revert

Use git revert like so:

git revert <insert bad commit hash here>

git revert creates a new commit with the changes that are rolled back. git reset erases your git history instead of making a new commit.

The steps after are the same as any other commit.

How to Access Hive via Python?

Below python program should work to access hive tables from python:

import commands

cmd = "hive -S -e 'SELECT * FROM db_name.table_name LIMIT 1;' "

status, output = commands.getstatusoutput(cmd)

if status == 0:
   print output
else:
   print "error"

Wildcards in a Windows hosts file

I don't think that it is possible.

You anyway have to modify the apache virtualroot entries every time you add a new site and location, so it's not a big work to syncronise the new name to the Windows vhost file.

Update: please check the next answer and the comments on this answer. This answer is 6 years old and not correct anymore.

Python: find position of element in array

For your first question, find the position of some value in a list x using index(), like so:

x.index(value)

For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:

value = 1 
x = [1,2,3,4,5,6,2,1,4,5,6]

chunk_a = x[:int(len(x)/2)] # get the first half of x 
chunk_b = x[int(len(x)/2):] # get the rest half of x

print(chunk_a.index(value))
print(chunk_b.index(value))

Hope that helps!

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

What tools do you use to test your public REST API?

I use http://hurl.it/

Ha. Sorry, I mis-read your post. I've used cucumber to test it before. It worked out nicely.

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [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):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

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

When would you use the Builder Pattern?

For a multi-threaded problem, we needed a complex object to be built up for each thread. The object represented the data being processed, and could change depending on the user input.

Could we use a factory instead? Yes

Why didn't we? Builder makes more sense I guess.

Factories are used for creating different types of objects that are the same basic type (implement the same interface or base class).

Builders build the same type of object over and over, but the construction is dynamic so it can be changed at runtime.

How to start/stop/restart a thread in Java?

It is impossible to terminate a thread unless the code running in that thread checks for and allows termination.

You said: "Sadly I must kill/restart it ... I don't have complete control over the contents of the thread and for my situation it requires a restart"

If the contents of the thread does not allow for termination of its exectuion then you can not terminate that thread.

In your post you said: "My first attempt was with ExecutorService but I can't seem to find a way for it restart a task. When I use .shutdownnow()..."

If you look at the source of "shutdownnow" it just runs through and interrupts the currently running threads. This will not stop their execution unless the code in those threads checks to see if it has been ineterrupted and, if so, stops execution itself. So shutdownnow is probably not doing what you think.

Let me illustrate what I mean when I say that the contents of the thread must allow for that thread to be terminated:

myExecutor.execute(new Runnable() {
 public void run() {
  while (true) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

That thread will continue to run forever, even though shutdownnow was called, because it never checks to see if it has been terminated or not. This thread, however, will shut down:

myExecutor.execute(new Runnable() {
 public void run() {
  while (!Thread.interrupted()) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

Since this thread checks to see whether or not it has been interrupted / shut down / terminated.

So if you want a thread that you can shut down, you need to make sure it checks to see if it has been interrupted. If you want a thread that you can "shut down" and "restart" you can make a runnable that can take new tasks as was mentioned before.

Why can you not shut down a running thread? Well I actually lied, you can call "yourThread.stop()" but why is this a bad idea? The thread could be in a synchronized (or other critical section, but we will limit ourselves to setions guarded by the syncrhonized key word here) section of code when you stop it. synch blocks are supposed to be executed in their entirity and only by one thread before being accessed by some other thread. If you stop a thread in the middle of a synch block, the protection put into place by the synch block is invalidated and your program will get into an unknown state. Developers make put stuff in synch blocks to keep things in synch, if you use threadInstance.stop() you destroy the meaning of synchronize, what the developer of that code was trying to accomplish and how the developer of that code expected his synchronized blocks to behave.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

In my case I wanted to manually add urlrewrite rule and couldn't see the obvious error (I missed <rules> tag):

wrong code:

    <rewrite>
      <rule name="some rule" stopProcessing="true">
        <match url="some-pattenr/(.*)" />        
        <action type="Redirect" url="/some-ne-pattenr/{R:1}" />
      </rule>
    </rewrite>    

  </system.webServer>
</configuration>

proper code (with rules tag):

    <rewrite>
      <rules>
        <rule name="some rule" stopProcessing="true">
          <match url="some-pattenr/(.*)" />        
          <action type="Redirect" url="/some-ne-pattenr/{R:1}" />
        </rule>
      </rules>
    </rewrite>

  </system.webServer>
</configuration>

Eclipse gives “Java was started but returned exit code 13”

When I uninstalled Java 8 it worked fine.

JavaScript null check

In your case use data==null (which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)

_x000D_
_x000D_
function test(data) {_x000D_
    if (data != null) {_x000D_
        console.log('Data: ', data);_x000D_
    }_x000D_
}_x000D_
_x000D_
test();          // the data=undefined_x000D_
test(null);      // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
_x000D_
_x000D_

Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Displaying Image in Java

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DisplayImage {

    public static void main(String avg[]) throws IOException
    {
        DisplayImage abc=new DisplayImage();
    }

    public DisplayImage() throws IOException
    {
        BufferedImage img=ImageIO.read(new File("f://images.jpg"));
        ImageIcon icon=new ImageIcon(img);
        JFrame frame=new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(200,300);
        JLabel lbl=new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

Various ways to remove local Git changes

I think git has one thing that isn't clearly documented. I think it was actually neglected.

git checkout .

Man, you saved my day. I always have things I want to try using the modified code. But the things sometimes end up messing the modified code, add new untracked files etc. So what I want to do is, stage what I want, do the messy stuff, then cleanup quickly and commit if I'm happy.

There's git clean -fd works well for untracked files.

Then git reset simply removes staged, but git checkout is kinda too cumbersome. Specifying file one by one or using directories isn't always ideal. Sometimes the changed files I want to get rid of are within directories I want to keep. I wished for this one command that just removes unstaged changes and here you're. Thanks.

But I think they should just have git checkout without any options, remove all unstaged changes and not touch the the staged. It's kinda modular and intuitive. More like what git reset does. git clean should also do the same.

StringUtils.isBlank() vs String.isEmpty()

StringUtils isEmpty = String isEmpty checks + checks for null.

StringUtils isBlank = StringUtils isEmpty checks + checks if the text contains only whitespace character(s).

Useful links for further investigation:

Today`s date in an excel macro

Here's an example that puts the Now() value in column A.

Sub move()
    Dim i As Integer
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim nextRow As Long
    Dim copyRange As Range
    Dim destRange As Range

    Application.ScreenUpdating = False

        Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
        Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
        Set copyRange = sh1.Range("A1:A5")

        i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4

        Set destRange = sh2.Range("B" & i)

        destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
        destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")

        copyRange.Clear

    Application.ScreenUpdating = True

End Sub

There are better ways of getting the last row in column B than using a While loop, plenty of examples around here. Some are better than others but depend on what you're doing and what your worksheet structure looks like. I used one here which assumes that column B is ALL empty except the rows/records you're moving. If that's not the case, or if B1:B3 have some values in them, you'd need to modify or use another method. Or you could just use your loop, but I'd search for alternatives :)

How to use Tomcat 8 in Eclipse?

In addition to @Jason's answer I had to do a bit more to get my app to run.

How to convert a GUID to a string in C#?

Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens

Recommendation for compressing JPG files with ImageMagick

@JavisPerez -- Is there any way to compress that image to 150kb at least? Is that possible? What ImageMagick options can I use?

See the following links where there is an option in ImageMagick to specify the desired output file size for writing to JPG files.

http://www.imagemagick.org/Usage/formats/#jpg_write http://www.imagemagick.org/script/command-line-options.php#define

-define jpeg:extent={size} As of IM v6.5.8-2 you can specify a maximum output filesize for the JPEG image. The size is specified with a suffix. For example "400kb".

convert image.jpg -define jpeg:extent=150kb result.jpg

You will lose some quality by decompressing and recompressing in addition to any loss due to lowering -quality value from the input.

Difference between jQuery’s .hide() and setting CSS to display: none

.hide() stores the previous display property just before setting it to none, so if it wasn't the standard display property for the element you're a bit safer, .show() will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.

How can VBA connect to MySQL database in Excel?

This piece of vba worked for me:

Sub connect()
    Dim Password As String
    Dim SQLStr As String
    'OMIT Dim Cn statement
    Dim Server_Name As String
    Dim User_ID As String
    Dim Database_Name As String
    'OMIT Dim rs statement

    Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
    Server_Name = Range("b2").Value
    Database_name = Range("b3").Value ' Name of database
    User_ID = Range("b4").Value 'id user or username
    Password = Range("b5").Value 'Password

    SQLStr = "SELECT * FROM ComputingNotesTable"

    Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
    Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _ 
            Server_Name & ";Database=" & Database_Name & _
            ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic

    Dim myArray()

    myArray = rs.GetRows()

    kolumner = UBound(myArray, 1)
    rader = UBound(myArray, 2)

    For K = 0 To kolumner ' Using For loop data are displayed
        Range("a5").Offset(0, K).Value = rs.Fields(K).Name
        For R = 0 To rader
           Range("A5").Offset(R + 1, K).Value = myArray(K, R)
        Next
    Next

    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
End Sub

Using `date` command to get previous, current and next month

The problem is that date takes your request quite literally and tries to use a date of 31st September (being 31st October minus one month) and then because that doesn't exist it moves to the next day which does. The date documentation (from info date) has the following advice:

The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:

 $ date -R
 Thu, 31 Jul 2003 13:02:39 -0700
 $ date --date='-1 month' +'Last month was %B?'
 Last month was July?
 $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
 Last month was June!

CORS Access-Control-Allow-Headers wildcard being ignored?

I found that Access-Control-Allow-Headers: * should be set ONLY for OPTIONS request. If you return it for POST request then browser cancel the request (at least for chrome)

The following PHP code works for me

// Allow CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Headers: *");
}

I found similar questions with some misleading response:

  • Server thread says that this is 2 years bug of chrome: Access-Control-Allow-Headers does not match with localhost. It's wrong: I can use CORS to my local server with Post normally
  • Access-Control-Allow-Headers does accept wildcards. It's also wrong, wildcard works for me (I tested only with Chrome)

This take me half day to figure out the issue.

Happy coding

How change default SVN username and password to commit changes?

In TortiseSVN settings

right-click menu >> settings >> Saved data >> Authentication data [Clear]

The side effect is that it clears out all authentication data and you have to re-enter your own username/password.

how to prevent css inherit

If the inner object is inheriting properties you don't want, you can always set them to what you do want (ie - the properties are cascading, and so you can overwrite them at the lower level).

e.g.

.li-a {
    font-weight: bold;
    color: red;
}

.li-b {
    color: blue;
}

In this case, "li-b" will still be bold even though you don't want it to be. To make it not bold you can do:

.li-b {
    font-weight: normal;
    color: blue;
}

phpmailer error "Could not instantiate mail function"

I was having this issue while sending files with regional characters in their names like: VeryRegiónal file - name.pdf.

The solution was to clear filename before attaching it to the email.

How to assign a select result to a variable?

I just had the same problem and...

declare @userId uniqueidentifier
set @userId = (select top 1 UserId from aspnet_Users)

or even shorter:

declare @userId uniqueidentifier
SELECT TOP 1 @userId = UserId FROM aspnet_Users

Load properties file in JAR?

For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):

To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is ${basedir}/src/test/resources. At this point you would have a project directory structure that would look like the following:

my-app
|-- pom.xml
`-- src
    |-- main
    |   |-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `-- resources
    |       `-- META-INF
    |           |-- application.properties
    `-- test
        |-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `-- resources
            `-- test.properties

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...

SQL Server 2008 R2 can't connect to local database in Management Studio

If your instance is called SQLEXPRESS, then you need to use .\SQLEXPRESS or (local)\SQLEXPRESS or yourMachineName\SQLEXPRESS as your server name - if you have a named instance, you need to specify that name of the instance in your server name.

"Continue" (to next iteration) on VBScript

Implement the iteration as a recursive function.

Function Iterate( i , N )
  If i == N Then
      Exit Function
  End If
  [Code]
  If Condition1 Then
     Call Iterate( i+1, N );
     Exit Function
  End If

  [Code]
  If Condition2 Then
     Call Iterate( i+1, N );
     Exit Function
  End If
  Call Iterate( i+1, N );
End Function

Start with a call to Iterate( 1, N )

toggle show/hide div with button?

Here's a plain Javascript way of doing toggle:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">

split string only on first instance of specified character

Here's one RegExp that does the trick.

'good_luck_buddy' . split(/^.*?_/)[1] 

First it forces the match to start from the start with the '^'. Then it matches any number of characters which are not '_', in other words all characters before the first '_'.

The '?' means a minimal number of chars that make the whole pattern match are matched by the '.*?' because it is followed by '_', which is then included in the match as its last character.

Therefore this split() uses such a matching part as its 'splitter' and removes it from the results. So it removes everything up till and including the first '_' and gives you the rest as the 2nd element of the result. The first element is "" representing the part before the matched part. It is "" because the match starts from the beginning.

There are other RegExps that work as well like /_(.*)/ given by Chandu in a previous answer.

The /^.*?_/ has the benefit that you can understand what it does without having to know about the special role capturing groups play with replace().

..The underlying connection was closed: An unexpected error occurred on a receive

My Hosting server block requesting URL And code site getting the same error Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

enter image description here

After a lot of time spent and apply the following step to resolve this issue

  1. Added line before the call web URL

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

  2. still issue not resolve then I upgrade .net version to 4.7.2 but I think it's optional

  3. Last change I have checked my hosting server security level which causes to TLS handshaking for this used "https://www.ssllabs.com/ssltest/index.html" site
    and also check to request URL security level then I find the difference is requested URL have to enable a weak level Cipher Suites you can see in the below image

enter image description here

Now here are my hosting server supporting Cipher Suites

enter image description here

here is called if you have control over requesting URL host server then you can sync this both server Cipher Suites. but in my case, it's not possible so I have applied the following script in Windows PowerShell on my hosting server for enabling required weak level Cipher Suites.

Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_GCM_SHA384"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_GCM_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"

after applying the above script my hosting server Cipher Suites level look like

enter image description here

Then my issue resolved.

Note: server security level downgrade is not a recommended option.

How to make a PHP SOAP call using the SoapClient class

First initialize webservices:

$client = new SoapClient("http://example.com/webservices?wsdl");

Then set and pass the parameters:

$params = array (
    "arg0" => $contactid,
    "arg1" => $desc,
    "arg2" => $contactname
);

$response = $client->__soapCall('methodname', array($params));

Note that the method name is available in WSDL as operation name, e.g.:

<operation name="methodname">

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

How to convert string to boolean in typescript Angular 4

You can use that:

let s: string = "true";
let b: boolean = Boolean(s);

SQL: capitalize first letter only

Create the below function

Alter FUNCTION InitialCap(@String VARCHAR(8000))
                  RETURNS VARCHAR(8000)
                 AS
 BEGIN 

                   DECLARE @Position INT;

SELECT @String   = STUFF(LOWER(@String),1,1,UPPER(LEFT(@String,1))) COLLATE Latin1_General_Bin,
                    @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);

                    WHILE @Position > 0
                    SELECT @String   = STUFF(@String,@Position,2,UPPER(SUBSTRING(@String,@Position,2))) COLLATE Latin1_General_Bin,
                    @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);

                     RETURN @String;
  END ;

Then call it like

select dbo.InitialCap(columnname) from yourtable

How to send email via Django?

You could use "Test Mail Server Tool" to test email sending on your machine or localhost. Google and Download "Test Mail Server Tool" and set it up.

Then in your settings.py:

EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25

From shell:

from django.core.mail import send_mail
send_mail('subject','message','sender email',['receipient email'],    fail_silently=False)

Bundling data files with PyInstaller (--onefile)

Using the excellent answer from Max and This post about adding extra data files like images or sound & my own research/testing, I've figured out what I believe is the easiest way to add such files.

If you would like to see a live example, my repository is here on GitHub.

Note: this is for compiling using the --onefile or -F command with pyinstaller.

My environment is as follows.


Solving the problem in 2 steps

To solve the issue we need to specifically tell Pyinstaller that we have extra files that need to be "bundled" with the application.

We also need to be using a 'relative' path, so the application can run properly when it's running as a Python Script or a Frozen EXE.

With that being said we need a function that allows us to have relative paths. Using the function that Max Posted we can easily solve the relative pathing.

def img_resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

We would use the above function like this so the application icon shows up when the app is running as either a Script OR Frozen EXE.

icon_path = img_resource_path("app/img/app_icon.ico")
root.wm_iconbitmap(icon_path)

The next step is that we need to instruct Pyinstaller on where to find the extra files when it's compiling so that when the application is run, they get created in the temp directory.

We can solve this issue two ways as shown in the documentation, but I personally prefer managing my own .spec file so that's how we're going to do it.

First, you must already have a .spec file. In my case, I was able to create what I needed by running pyinstaller with extra args, you can find extra args here. Because of this, my spec file may look a little different than yours but I'm posting all of it for reference after I explain the important bits.

added_files is essentially a List containing Tuple's, in my case I'm only wanting to add a SINGLE image, but you can add multiple ico's, png's or jpg's using ('app/img/*.ico', 'app/img') You may also create another tuple like soadded_files = [ (), (), ()] to have multiple imports

The first part of the tuple defines what file or what type of file's you would like to add as well as where to find them. Think of this as CTRL+C

The second part of the tuple tells Pyinstaller, to make the path 'app/img/' and place the files in that directory RELATIVE to whatever temp directory gets created when you run the .exe. Think of this as CTRL+V

Under a = Analysis([main..., I've set datas=added_files, originally it used to be datas=[] but we want out the list of imports to be, well, imported so we pass in our custom imports.

You don't need to do this unless you want a specific icon for the EXE, at the bottom of the spec file I'm telling Pyinstaller to set my application icon for the exe with the option icon='app\\img\\app_icon.ico'.

added_files = [
    ('app/img/app_icon.ico','app/img/')
]
a = Analysis(['main.py'],
             pathex=['D:\\Github Repos\\Processes-Killer\\Process Killer'],
             binaries=[],
             datas=added_files,
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='Process Killer',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True , uac_admin=True, icon='app\\img\\app_icon.ico')

Compiling to EXE

I'm very lazy; I don't like typing things more than I have to. I've created a .bat file that I can just click. You don't have to do this, this code will run in a command prompt shell just fine without it.

Since the .spec file contains all of our compiling settings & args (aka options) we just have to give that .spec file to Pyinstaller.

pyinstaller.exe "Process Killer.spec"

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

tomcat - CATALINA_BASE and CATALINA_HOME variables

Pointing CATALINA_BASE to a different directory from CATALINA_HOME allows you to separate the configuration directory from the binaries directory.

By default, CATALINA_BASE (configurations) and CATALINA_HOME (binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.

It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.

Update 2018

There is an easier way to set CATALINA_BASE now with the makebase utility. I have posted a tutorial that covers this subject at http://blog.rasia.io/blog/how-to-easily-setup-lucee-in-tomcat.html along with a video tutorial at https://youtu.be/nuugoG5c-7M

Original answer continued below

To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE environment variable. You will have to put some files in that directory:

  • Copy the conf directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.
  • Create a logs directory if conf/logging.properties points to ${catalina.base}/logs, and ensure that Tomcat has read/write permissions to it.
  • Create a temp directory if you are not overriding the default of $CATALINA_TMPDIR which points to ${CATALINA_BASE}/temp, and ensure that Tomcat has write permissions to it.
  • Create a work directory which defaults to ${CATALINA_BASE}/work, and ensure that Tomcat has write permissions to it.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Yes, it's possible, the syntax is curl [protocol://]<host>[:port], for example:

curl example.com:1234

If you're using Bash, you can also use pseudo-device /dev files to open a TCP connection, e.g.:

exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.

See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).

Import and Export Excel - What is the best library?

You can use Microsoft.Jet.OLEDB.4.0

How can I protect my .NET assemblies from decompilation?

If someone has to steal your code, it likely means your business model is not working. What do I mean by that? For example, I buy your product and then I ask for support. You're too busy or believe my request is not valid and a waste of your time. I decode your product in order to support my relative business. Your product becomes more valuable to me and I prioritize my time in a way to resolve the business model for leveraging your product. I recode and re-brand your product and then go out and make the money that you decided to leave on the table. There are reasons for protecting code, but most likely you are looking at the problem from the wrong perspective. Of course you are. You're the "coder", and I'm the business man. ;-) Cheers!

ps. I'm also a developer. i.e. "coder"

How can I check the extension of a file?

one easy way could be:

import os

if os.path.splitext(file)[1] == ".mp3":
    # do something

os.path.splitext(file) will return a tuple with two values (the filename without extension + just the extension). The second index ([1]) will therefor give you just the extension. The cool thing is, that this way you can also access the filename pretty easily, if needed!

Filter by process/PID in Wireshark

Just in case you are looking for an alternate way and the environment you use is Windows, Microsoft's Network Monitor 3.3 is a good choice. It has the process name column. You easily add it to a filter using the context menu and apply the filter.. As usual the GUI is very intuitive...

Multidimensional Lists in C#

It's old but thought I'd add my two cents... Not sure if it will work but try using a KeyValuePair:

 List<KeyValuePair<?, ?>> LinkList = new List<KeyValuePair<?, ?>>();
 LinkList.Add(new KeyValuePair<?, ?>(Object, Object));

You'll end up with something like this:

 LinkList[0] = <Object, Object>
 LinkList[1] = <Object, Object>
 LinkList[2] = <Object, Object>

and so on...

How to zip a file using cmd line?

ZIP FILE via Cross-platform Java without manifest and META-INF folder:

jar -cMf {yourfile.zip} {yourfolder}

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

React PropTypes : Allow different types of PropTypes for one prop

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

How to uninstall a package installed with pip install --user

I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here's the history and the fix:

pip uninstall opencv-python # -- the original step. failed.

ImportError: DLL load failed: The specified module could not be found.

I did this into my python3.6 environment and got this error.

python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.

Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.

finally, this fixed it:

pip uninstall opencv-python

(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.

>>>import cv2
>>>

working!

How to remove a character at the end of each line in unix

This Perl code removes commas at the end of the line:

perl -pe 's/,$//' file > file.nocomma

This variation still works if there is whitespace after the comma:

perl -lpe 's/,\s*$//' file > file.nocomma

This variation edits the file in-place:

perl -i -lpe 's/,\s*$//' file

This variation edits the file in-place, and makes a backup file.bak:

perl -i.bak -lpe 's/,\s*$//' file

Convert a String to int?

So basically you want to convert a String into an Integer right! here is what I mostly use and that is also mentioned in official documentation..

fn main() {

    let char = "23";
    let char : i32 = char.trim().parse().unwrap();
    println!("{}", char + 1);

}

This works for both String and &str Hope this will help too.

Loading PictureBox Image from resource file with path (Part 3)

It depends on your file path. For me, the current directory was [project]\bin\Debug, so I had to move to the parent folder twice.

Image image = Image.FromFile(@"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;

To find your current directory, you can make a dummy label called label2 and write this:

this.label2.Text = System.IO.Directory.GetCurrentDirectory();

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You cannot append to an existing xlsx file with xlsxwriter.

There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close() which will then write all of the information to your xlsx file.

Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...

i.e.

cells = []
for row in range(sheet.nrows):
    cells.append([])
    for col in range(sheet.ncols):
        cells[row].append(workbook.cell(row, col).value)

You don't need arrays, though. For example, this works perfectly fine:

import xlrd
import xlsxwriter

from os.path import expanduser
home = expanduser("~")

# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
    for col in range(20):
        sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()

# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()

# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))

# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
    newSheet = wb.add_worksheet(sheet.name)
    for row in range(sheet.nrows):
        for col in range(sheet.ncols):
            newSheet.write(row, col, sheet.cell(row, col).value)

for row in range(10, 20): # write NEW data
    for col in range(20):
        newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes

However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()).

Best way to include CSS? Why use @import?

I think @import is most useful when writing code for multiple devices. Include a conditional statement to only include the style for the device in question, then only one sheet gets loaded. You can still use the link tag to add any common style elements.

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

test attribute in JSTL <c:if> tag

All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"

<c:if test="true">Hello world!</c:if>

The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.

Error in setting JAVA_HOME

JAVA_HOME = C:\Program Files\Java\jdk(JDK version number)

Example: C:\Program Files\Java\jdk-10

And then restart you command prompt it works.

SQL select join: is it possible to prefix all columns as 'prefix.*'?

What I do is use Excel to concatenate the procedure. For instance, first I select * and get all of the columns, paste them in Excel. Then write out the code I need to surround the column. Say i needed to ad prev to a bunch of columns. I'd have my fields in the a column and "as prev_" in column B and my fields again in column c. In column d i'd have a column.

Then use concatanate in column e and merge them together, making sure to include spaces. Then cut and paste this into your sql code. I've also used this method to make case statements for the same field and other longer codes i need to do for each field in a multihundred field table.

Stretch image to fit full container width bootstrap

Here's what worked for me. Note: Adding the image within a row introduces some space so I've intentionally used only a div to encapsulate the image.

<div class="container-fluid w-100 h-auto m-0 p-0">  

    <img src="someimg.jpg" class="img-fluid w-100 h-auto p-0 m-0" alt="Patience">           

</div>

Check to see if cURL is installed locally?

cURL is disabled for most hosting control panels for security reasons, but it's required for a lot of php applications. It's not unusual for a client to request it. Since the risk of enabling cURL is minimal, you are probably better off enabling it than losing a customer. It's simply a utility that helps php scripts fetch things using standard Internet URLs.

To enable cURL, you will remove curl_exec from the "disabled list" in the control panel php advanced settings. You will also find a disabled list in the various php.ini files; look in /etc/php.ini and other paths that might exist for your control panel. You will need to restart Apache to make the change take effect.

service httpd restart

To confirm whether cURL is enabled or disabled, create a file somewhere in your system and paste the following contents.

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

Save the file as testcurl.php and then run it as a php script.

php testcurl.php

If cURL is disabled you will see this error.

Fatal error: Call to undefined function curl_version() in testcurl.php on line 2

If cURL is enabled you will see a long list of attributes, like this.

array(9) {
["version_number"]=>
int(461570)
["age"]=>
int(1)
["features"]=>
int(540)
["ssl_version_number"]=>
int(9465919)
["version"]=>
string(6) "7.11.2"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(15) " OpenSSL/0.9.7c"
["libz_version"]=>
string(5) "1.1.4"
["protocols"]=>
array(9) {
[0]=>
string(3) "ftp"
[1]=>
string(6) "gopher"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(4) "http"
[6]=>
string(4) "file"
[7]=>
string(5) "https"
[8]=>
string(4) "ftps"
}
}

Using bootstrap with bower

assuming you have npm installed and bower installed globally

  1. navigate to your project
  2. bower init (this will generate the bower.json file in your directory)
  3. (then keep clicking yes)...
  4. to set the path where bootstrap will be installed:
    manually create a .bowerrc file next to the bower.json file and add the following to it:

    { "directory" : "public/components" }

  5. bower install bootstrap --save

Note: to install other components:

 bower search {component-name-here}

Align Div at bottom on main Div

Give your parent div position: relative, then give your child div position: absolute, this will absolute position the div inside of its parent, then you can give the child bottom: 0px;

See example here:

http://jsfiddle.net/PGMqs/1/

Appending a line to a file only if it does not already exist

If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>. A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"

How to Handle Button Click Events in jQuery?

Works for me

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

$("#btn").click(function() {
    alert("email")
});

</script>

Can I update a component's props in React.js?

if you use recompose, use mapProps to make new props derived from incoming props

Edit for example:

import { compose, mapProps } from 'recompose';

const SomeComponent = ({ url, onComplete }) => (
  {url ? (
    <View />
  ) : null}
)

export default compose(
  mapProps(({ url, storeUrl, history, ...props }) => ({
    ...props,
    onClose: () => {
      history.goBack();
    },
    url: url || storeUrl,
  })),
)(SomeComponent);

Redirect from asp.net web api post action

    [HttpGet]
    public RedirectResult Get()
    {
        return RedirectPermanent("https://www.google.com");
    }

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

I had a tab character instead of spaces. Replacing the tab '\t' fixed the problem.

Cut and paste the whole doc into an editor like Notepad++ and display all characters.

Where can I download an offline installer of Cygwin?

If all you want is the UNIX command line tools I'd suggest not installing Cygwin. Cygwin wants to turn your Windows PC into a UNIX Workstation which is why it likes to install all its packages.

Have a look at GnuWin32 instead. It's Windows ports of the command line tools and nothing else. Here is the installer for the GnuWin32 diff.exe. There are offline installers for all the common tools.

(You asked for offline installers but in case you ever want one later there is a tool which will download and install everything for you.)

Method 2: make an offline install zip file for cygwin.

Don't mess with saving packages because the installed directory for cygwin can be canned in a zip file and expanded whenever you need it on any computer.

  1. Download Cygwin installer

  2. pick packages you want installed from gui.

  3. hit install and wait a really long time for everything to download.

  4. zip up the C:\Cygwin folder. Now you have your offline zip file for installing cygwin on any machine.

  5. Unzip this file on whatever computer you like. set cmd.exe paths appropriately to point to cygwin bin directory under windows control panel.

AttributeError: Module Pip has no attribute 'main'

Edit file: C:\Users\kpate\hw6\python-zulip-api\zulip_bots\setup.py in line 108

to

rcode = pip.main(['install', '-r', req_path, '--quiet'])

do

rcode = getattr(pip, '_main', pip.main)(['install', '-r', req_path, '--quiet'])´

substring index range

0: U

1: n

2: i

3: v

4: e

5: r

6: s

7: i

8: t

9: y

Start index is inclusive

End index is exclusive

Javadoc link

Vue.js toggle class on click

If you need more than 1 class

You can do this:

<i id="icon" 
  v-bind:class="{ 'fa fa-star': showStar }"
  v-on:click="showStar = !showStar"
  >
</i> 

data: {
  showStar: true
}

Notice the single quotes ' around the classes!

Thanks to everyone else's solutions.

Common Header / Footer with static HTML

There are three ways to do what you want

Server Script

This includes something like php, asp, jsp.... But you said no to that

Server Side Includes

Your server is serving up the pages so why not take advantage of the built in server side includes? Each server has its own way to do this, take advantage of it.

Client Side Include

This solutions has you calling back to the server after page has already been loaded on the client.

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

set dropdown value by text using jquery

$("#HowYouKnow").val("GOOGLE");

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.

Important note

Your code has a typo in your if statement in not exists(select...) part. Inner select statement has only one where condition while UserName condition is excluded from the not exists due to invalid brace completion. In any case you cave too many closing braces.

I assume this based on the fact that you're using two where conditions in update statement later on in your code.

Let's continue to my answer...

SQL Server 2008+ support MERGE statement

MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).

declare @clockDate date = '08/10/2012';
declare @userName = 'test';

merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
    update
    set BreakOut = getdate()
when not matched then
    insert (ClockDate, UserName, BreakOut)
    values (getdate(), source.UserName, getdate());

Put spacing between divs in a horizontal row?

You can set left margins for li tags in percents and set the same negative left margin on parent:

_x000D_
_x000D_
ul {margin-left:-5%;}_x000D_
li {width:20%;margin-left:5%;float:left;}
_x000D_
<ul>_x000D_
  <li>A_x000D_
  <li>B_x000D_
  <li>C_x000D_
  <li>D_x000D_
</ul>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/UZHbS/

Restart container within pod

All the above answers have mentioned deleting the pod...but if you have many pods of the same service then it would be tedious to delete each one of them...

Therefore, I propose the following solution, restart:

  • 1) Set scale to zero :

     kubectl scale deployment <<name>> --replicas=0 -n service 
    

    The above command will terminate all your pods with the name <<name>>

  • 2) To start the pod again, set the replicas to more than 0

    kubectl scale deployment <<name>> --replicas=2 -n service
    

    The above command will start your pods again with 2 replicas.

Is there a NumPy function to return the first index of something in an array?

To index on any criteria, you can so something like the following:

In [1]: from numpy import *
In [2]: x = arange(125).reshape((5,5,5))
In [3]: y = indices(x.shape)
In [4]: locs = y[:,x >= 120] # put whatever you want in place of x >= 120
In [5]: pts = hsplit(locs, len(locs[0]))
In [6]: for pt in pts:
   .....:         print(', '.join(str(p[0]) for p in pt))
4, 4, 0
4, 4, 1
4, 4, 2
4, 4, 3
4, 4, 4

And here's a quick function to do what list.index() does, except doesn't raise an exception if it's not found. Beware -- this is probably very slow on large arrays. You can probably monkey patch this on to arrays if you'd rather use it as a method.

def ndindex(ndarray, item):
    if len(ndarray.shape) == 1:
        try:
            return [ndarray.tolist().index(item)]
        except:
            pass
    else:
        for i, subarray in enumerate(ndarray):
            try:
                return [i] + ndindex(subarray, item)
            except:
                pass

In [1]: ndindex(x, 103)
Out[1]: [4, 0, 3]

How to list the certificates stored in a PKCS12 keystore with keytool?

What is missing in the question and all the answers is that you might need the passphrase to read public data from the PKCS#12 (.pfx) keystore. If you need a passphrase or not depends on how the PKCS#12 file was created. You can check the ASN1 structure of the file (by running it through a ASN1 parser, openssl or certutil can do this too), if the PKCS#7 data (e.g. OID prefix 1.2.840.113549.1.7) is listed as 'encrypted' or with a cipher-spec or if the location of the data in the asn1 tree is below an encrypted node, you won't be able to read it without knowledge of the passphrase. It means your 'openssl pkcs12' command will fail with errors (output depends on the version). For those wondering why you might be interested in the certificate of a PKCS#12 without knowledge of the passphrase. Imagine you have many keystores and many phassphrases and you are really bad at keeping them organized and you don't want to test all combinations, the certificate inside the file could help you find out which password it might be. Or you are developing software to migrate/renew a keystore and you need to decide in advance which procedure to initiate based on the contained certicate without user interaction. So the latter examples work without passphrase depending on the PKCS#12 structure.

Just wanted to add that, because I didn't find an answer myself and spend a lot of time to figure it out.

How to "select distinct" across multiple data frame columns in pandas?

You can take the sets of the columns and just subtract the smaller set from the larger set:

distinct_values = set(df['a'])-set(df['b'])

Pip - Fatal error in launcher: Unable to create process using '"'

I got the same error when installed both python2 and python3 on my Windows 7.

You can use python3 -m pip install xxxxxx to install your package.

Or, fix it completely:

  1. Try to run python3 -m pip install --upgrade pip in cmd.

  2. If failed in step 1, try python3  -m pip install --upgrade --force-reinstall pip

What is cURL in PHP?

CURL in PHP:

Summary:

The curl_exec command in PHP is a bridge to use curl from console. curl_exec makes it easy to quickly and easily do GET/POST requests, receive responses from other servers like JSON and download files.

Warning, Danger:

curl is evil and dangerous if used improperly because it is all about getting data from out there in the internet. Someone can get between your curl and the other server and inject a rm -rf / into your response, and then why am I dropped to a console and ls -l doesn't even work anymore? Because you mis underestimated the dangerous power of curl. Don't trust anything that comes back from curl to be safe, even if you are talking to your own servers. You could be pulling back malware to relieve fools of their wealth.

Examples:

These were done on Ubuntu 12.10

  1. Basic curl from the commandline:

    el@apollo:/home/el$ curl http://i.imgur.com/4rBHtSm.gif > mycat.gif
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100  492k  100  492k    0     0  1077k      0 --:--:-- --:--:-- --:--:-- 1240k
    

    Then you can open up your gif in firefox:

    firefox mycat.gif
    

    Glorious cats evolving Toxoplasma gondii to cause women to keep cats around and men likewise to keep the women around.

  2. cURL example get request to hit google.com, echo to the commandline:

    This is done through the phpsh terminal:

    php> $ch = curl_init();
    
    php> curl_setopt($ch, CURLOPT_URL, 'http://www.google.com');
    
    php> curl_exec($ch);
    

    Which prints and dumps a mess of condensed html and javascript (from google) to the console.

  3. cURL example put the response text into a variable:

    This is done through the phpsh terminal:

    php> $ch = curl_init();
    
    php> curl_setopt($ch, CURLOPT_URL, 'http://i.imgur.com/wtQ6yZR.gif');
    
    php> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    php> $contents = curl_exec($ch);
    
    php> echo $contents;
    

    The variable now contains the binary which is an animated gif of a cat, possibilities are infinite.

  4. Do a curl from within a PHP file:

    Put this code in a file called myphp.php:

    <?php
      $curl_handle=curl_init();
      curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com');
      curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
      curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
      $buffer = curl_exec($curl_handle);
      curl_close($curl_handle);
      if (empty($buffer)){
          print "Nothing returned from url.<p>";
      }
      else{
          print $buffer;
      }
    ?>
    

    Then run it via commandline:

    php < myphp.php
    

    You ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen.

    You can do GET and POST requests with curl, all you do is specify the parameters as defined here: Using curl to automate HTTP jobs

Reminder of danger:

Be careful dumping curl output around, if any of it gets interpreted and executed, your box is owned and your credit card info will be sold to third parties and you'll get a mysterious $900 charge from an Alabama one-man flooring company that's a front for overseas credit card fraud crime ring.

Summarizing multiple columns with dplyr?

You can simply pass more arguments to summarise:

df %>% group_by(grp) %>% summarise(mean(a), mean(b), mean(c), mean(d))

Source: local data frame [3 x 5]

  grp  mean(a)  mean(b)  mean(c) mean(d)
1   1 2.500000 3.500000 2.000000     3.0
2   2 3.800000 3.200000 3.200000     2.8
3   3 3.666667 3.333333 2.333333     3.0

How to check for a valid URL in Java?

validator package:

There seems to be a nice package by Yonatan Matalon called UrlUtil. Quoting its API:

isValidWebPageAddress(java.lang.String address, boolean validateSyntax, 
                      boolean validateExistance) 
Checks if the given address is a valid web page address.

Sun's approach - check the network address

Sun's Java site offers connect attempt as a solution for validating URLs.

Other regex code snippets:

There are regex validation attempts at Oracle's site and weberdev.com.

How to get last month/year in java?

You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0

    Calendar c = Calendar.getInstance();
    c.set(2011, 2, 1);
    c.add(Calendar.MONTH, -1);
    int month = c.get(Calendar.MONTH) + 1;
    assertEquals(1, month);

What is the default lifetime of a session?

But watch out, on most xampp/ampp/...-setups and some linux destributions it's 0, which means the file will never get deleted until you do it within your script (or dirty via shell)

PHP.INI:

; Lifetime in seconds of cookie or, if 0, until browser is restarted.
; http://php.net/session.cookie-lifetime
session.cookie_lifetime = 0

How do I compile the asm generated by GCC?

Yes, You can use gcc to compile your asm code. Use -c for compilation like this:

gcc -c file.S -o file.o

This will give object code file named file.o. To invoke linker perform following after above command:

gcc file.o -o file

MsgBox "" vs MsgBox() in VBScript

To my knowledge these are the rules for calling subroutines and functions in VBScript:

  • When calling a subroutine or a function where you discard the return value don't use parenthesis
  • When calling a function where you assign or use the return value enclose the arguments in parenthesis
  • When calling a subroutine using the Call keyword enclose the arguments in parenthesis

Since you probably wont be using the Call keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.

Here are some examples:

  • WScript.Echo 1, "two", 3.3 - calling a subroutine

  • WScript.Echo(1, "two", 3.3) - syntax error

  • Call WScript.Echo(1, "two", 3.3) - keyword Call requires parenthesis

  • MsgBox "Error" - calling a function "like" a subroutine

  • result = MsgBox("Continue?", 4) - calling a function where the return value is used

  • WScript.Echo (1 + 2)*3, ("two"), (((3.3))) - calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)

  • WScript.Echo(1) - apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1) and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines

  • I'm not sure how to interpret your example, Randomize(). Randomize is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.

I'm quite sure that these syntactic rules applies across different versions of operating systems.

How can I convert JSON to a HashMap using Gson?

This code works:

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());

How do I create delegates in Objective-C?

Let's start with an example , if we buy a product online ,it goes through process like shipping/delivery handled by different teams.So if shipping gets completed ,shipping team should notify delivery team & it should be one to one communication as broadcasting this information would be overhead for other people / vendor might want to pass this information only to required people.

So if we think in terms of our app, an event can be an online order & different teams can be like multiple views.

Here is code consider ShippingView as Shipping team & DeliveryView as delivery team :

//Declare the protocol with functions having info which needs to be communicated
protocol ShippingDelegate : class {
    func productShipped(productID : String)
}
//shippingView which shows shipping status of products
class ShippingView : UIView
{

    weak var delegate:ShippingDelegate?
    var productID : String

    @IBAction func checkShippingStatus(sender: UIButton)
    {
        // if product is shipped
        delegate?.productShipped(productID: productID)
    }
}
//Delivery view which shows delivery status & tracking info
class DeliveryView: UIView,ShippingDelegate
{
    func productShipped(productID : String)
    {
        // update status on view & perform delivery
    }
}

//Main page on app which has both views & shows updated info on product whole status
class ProductViewController : UIViewController
{
    var shippingView : ShippingView
    var deliveryView : DeliveryView

    override func viewDidLoad() {
        super.viewDidLoad()
        // as we want to update shipping info on delivery view, so assign delegate to delivery object
        // whenever shipping status gets updated it will call productShipped method in DeliveryView & update UI.
        shippingView.delegate = deliveryView
        //
    }
}

Java 8 NullPointerException in Collectors.toMap

For completeness, I'm posting a version of the toMapOfNullables with a mergeFunction param:

public static <T, K, U> Collector<T, ?, Map<K, U>> toMapOfNullables(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction) {
    return Collectors.collectingAndThen(Collectors.toList(), list -> {
        Map<K, U> result = new HashMap<>();
        for(T item : list) {
            K key = keyMapper.apply(item);
            U newValue = valueMapper.apply(item);
            U value = result.containsKey(key) ? mergeFunction.apply(result.get(key), newValue) : newValue;
            result.put(key, value);
        }
        return result;
    });
}

Resize a picture to fit a JLabel

Or u can do it this way. The function u put the below 6 lines will throw an IOException. And will take your JLabel as a parameter.

BufferedImage bi=new BufferedImage(label.width(),label.height(),BufferedImage.TYPE_INT_RGB);

Graphics2D g=bi.createGraphics();

Image img=ImageIO.read(new File("path of your image"));

g.drawImage(img, 0, 0, label.width(), label.height(), null);

g.dispose();

return bi;