Programs & Examples On #Windowsphotogallery

Rounded table corners CSS only

Firstly, you'll need more than just -moz-border-radius if you want to support all browsers. You should specify all variants, including plain border-radius, as follows:

-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;

Secondly, to directly answer your question, border-radius doesn't actually display a border; it just sets how the corners look of the border, if there is one.

To turn on the border, and thus get your rounded corners, you also need the border attribute on your td and th elements.

td, th {
   border:solid black 1px;
}

You will also see the rounded corners if you have a background colour (or graphic), although of course it would need to be a different background colour to the surrounding element in order for the rounded corners to be visible without a border.

It's worth noting that some older browsers don't like putting border-radius on tables/table cells. It may be worth putting a <div> inside each cell and styling that instead. However this shouldn't affect current versions of any browsers (except IE, that doesn't support rounded corners at all - see below)

Finally, not that IE doesn't support border-radius at all (IE9 beta does, but most IE users will be on IE8 or less). If you want to hack IE to support border-radius, look at http://css3pie.com/

[EDIT]

Okay, this was bugging me, so I've done some testing.

Here's a JSFiddle example I've been playing with

It seems like the critical thing you were missing was border-collapse:separate; on the table element. This stops the cells from linking their borders together, which allows them to pick up the border radius.

Hope that helps.

How to check if "Radiobutton" is checked?

Check if they're checked with the el.checked attribute.

Docs or this Question

_x000D_
_x000D_
let radio1 = document.querySelector('.radio1');
let radio2 = document.querySelector('.radio2');
let output = document.querySelector('.output');

function update() {
  if (radio1.checked) {
    output.innerHTML = "radio1";
  }
  else {
    output.innerHTML = "radio2";
  }
}

update();
_x000D_
<div class="radios">
  <input class="radio1" type="radio" name="radios" onchange="update()" checked>
  <input class="radio2" type="radio" name="radios" onchange="update()">
</div>
<div class="output"></div>
_x000D_
_x000D_
_x000D_

How to get the path of current worksheet in VBA?

The quickest way

path = ThisWorkbook.Path & "\"

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.

import timeit

setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''

timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)

Results:

1.1214002349999777 s  # WouterOvermeire
1.1922008498571748 s  # Jeff
1.7034366211428602 s  # Kikohs

Ping a site in Python?

I develop a library that I think could help you. It is called icmplib (unrelated to any other code of the same name that can be found on the Internet) and is a pure implementation of the ICMP protocol in Python.

It is completely object oriented and has simple functions such as the classic ping, multiping and traceroute, as well as low level classes and sockets for those who want to develop applications based on the ICMP protocol.

Here are some other highlights:

  • Can be run without root privileges.
  • You can customize many parameters such as the payload of ICMP packets and the traffic class (QoS).
  • Cross-platform: tested on Linux, macOS and Windows.
  • Fast and requires few CPU / RAM resources unlike calls made with subprocess.
  • Lightweight and does not rely on any additional dependencies.

To install it (Python 3.6+ required):

pip3 install icmplib

Here is a simple example of the ping function:

host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)

if host.is_alive:
    print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')
else:
    print(f'{host.address} is dead')

Set the "privileged" parameter to False if you want to use the library without root privileges.

You can find the complete documentation on the project page: https://github.com/ValentinBELYN/icmplib

Hope you will find this library useful.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:

  1. You can use another nextLine() method just after the nextInt() to move the scanner past the newline character.
  2. You can use different Scanner objects for scanning the integer and string (You can name them scan1 and scan2).
  3. You can use the next method on the scanner object as

    scan.next();

How do I iterate over a JSON structure?

Taken from jQuery docs:

var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(arr, function() {
  $("#" + this).text("My id is " + this + ".");
  return (this != "four"); // will stop running to skip "five"
});

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});

remove space between paragraph and unordered list

One way is using the immediate selector and negative margin. This rule will select a list right after a paragraph, so it's just setting a negative margin-top.

p + ul {  
   margin-top: -XX;
}

Python: finding lowest integer

'''Functions'''

import math

#functions
def min3(x1,x2,x3):
    if x1<= x2 and x1<= x3:
        return x1
    elif x2<= x1 and x2<= x3:
        return x2
    elif x3<= x2 and x3<= x1:
          return x3
print(min3(4, 7, 5))

print(min3(4, 5, 5))

print(min3(4, 4, 4))

print(min3(-2, -6, -100))

print(min3("Z", "B", "A"))

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

How can I determine browser window size on server side C#

You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.

At its simplest

var width = $(window).width();
var height = $(window).height();

Complete method using hidden form inputs

Assuming you have: JQuery framework.

First, add these hidden form inputs to store the width and height until postback.

<asp:HiddenField ID="width" runat="server" />
<asp:HiddenField ID="height" runat="server" />

Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().

Add the following code to your .aspx file within the head element.

<script type="text/javascript">
$(document).ready(function() {

    $("#width").val() = $(window).width();
    $("#height").val() = $(window).height();    

});
</script>

Result

This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:

var TheBrowserWidth = width.Value;
var TheBrowserHeight = height.Value;

This method provides the height and width upon postback, but not on the intial page load.

Note on UpdatePanels: If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.

Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.

Update for jquery 3.1.1

I had to change the JavaScript to:

$("#width").val($(window).width());
$("#height").val($(window).height());

CSS: Background image and padding

You can achieve your results with two methods:-

First Method define position values:-

HTML

 <ul>
 <li>Hello</li>
 <li>Hello world</li>
 </ul>

CSS

    ul{
    width:100px;    
}

ul li{
    border:1px solid orange;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}


ul li:hover{
    background: yellow url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}

First Demo:- http://jsfiddle.net/QeGAd/18/

Second Method by CSS :before:after Selectors

HTML

<ul>
<li>Hello</li>
<li>Hello world</li>

CSS

    ul{
    width:100px;    
}

ul li{
    border:1px solid orange;
}

ul li:after {
    content: " ";
    padding-right: 16px;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}

ul li:hover {
    background:yellow;
}

ul li:hover:after {
    content: " ";
    padding-right: 16px;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}

Second Demo:- http://jsfiddle.net/QeGAd/17/

Python conversion between coordinates

There is a better way to write polar(), here it is:

def polar(x,y):
  `returns r, theta(degrees)`
  return math.hypot(x,y),math.degrees(math.atan2(y,x))

get the titles of all open windows

you should use the EnumWindow API.

there are plenty of examples on how to use it from C#, I found something here:

Get Application's Window Handles

Issue with EnumWindows

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

Use cases for the 'setdefault' dict method

I use setdefault() when I want a default value in an OrderedDict. There isn't a standard Python collection that does both, but there are ways to implement such a collection.

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Java foreach loop: for (Integer i : list) { ... }

Sometimes it's just better to use an iterator.

(Allegedly, "85%" of the requests for an index in the posh for loop is for implementing a String join method (which you can easily do without).)

Read file from line 2 or skip header row

If you want the first line and then you want to perform some operation on file this code will helpful.

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

SQL Server SELECT LAST N Rows

To display last 3 rows without using order by:

select * from Lms_Books_Details where Book_Code not in 
 (select top((select COUNT(*) from Lms_Books_Details ) -3 ) book_code from Lms_Books_Details) 

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

Continuation of answer above.

Had the same "plugin error" as @MehrdadBabaki. I uninstalled web compiler, deleted the AppData WebCompiler folder mentioned above, then reopened VS2019 and reinstalled web compiler.

THEN I went to the WebCompiler folder again and did npm i autoprefixer@latest npm i caniuse-lite@latest and npm i caniuse-lite browserslist@latest

Scatter plot with error bars

#some example data
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

#calculate mean, min and max for each x-value
library(plyr)
df2 <- ddply(df,.(x),function(df) c(mean=mean(df$y),min=min(df$y),max=max(df$y)))

#plot error bars
library(Hmisc)
with(df2,errbar(x,mean,max,min))
grid(nx=NA,ny=NULL)

What is a PDB file?

PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.

This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb files. So effectively pdb files are really a boon to developers while debugging a program.

Generally it is not recommended to exclude the generation of *.pdb files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.

If you still want to disable generation of *.pdb files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none from "Debug Info" drop-down box -> press OK as shown in the snapshot below.

None Debug Info setting for a C# Project

Note: This setting will have to be done separately for "Debug" and "Release" build configurations.

Java associative-array

Java doesn't have associative arrays like PHP does.

There are various solutions for what you are doing, such as using a Map, but it depends on how you want to look up the information. You can easily write a class that holds all your information and store instances of them in an ArrayList.

public class Foo{
    public String name, fname;

    public Foo(String name, String fname){
        this.name = name;
        this.fname = fname;
    }
}

And then...

List<Foo> foos = new ArrayList<Foo>();
foos.add(new Foo("demo","fdemo"));
foos.add(new Foo("test","fname"));

So you can access them like...

foos.get(0).name;
=> "demo"

Hibernate openSession() vs getCurrentSession()

If we talk about SessionFactory.openSession()

  • It always creates a new Session object.
  • You need to explicitly flush and close session objects.
  • In single threaded environment it is slower than getCurrentSession().
  • You do not need to configure any property to call this method.

And If we talk about SessionFactory.getCurrentSession()

  • It creates a new Session if not exists, else uses same session which is in current hibernate context.
  • You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

How do I dynamically change the content in an iframe using jquery?

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

What is Java EE?

Java EE is a collection of specifications for developing and deploying enterprise applications.

In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.

The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.

The 13 core technologies that make up Java EE are:

  1. JDBC
  2. JNDI
  3. EJBs
  4. RMI
  5. JSP
  6. Java servlets
  7. XML
  8. JMS
  9. Java IDL
  10. JTS
  11. JTA
  12. JavaMail
  13. JAF

The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.

When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region;

This should show you the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION

Now simply issue an:

alter table region drop foreign key region_ibfk_1;

And finally an:

alter table region drop column country_id;

And you are good to go!

Hiding table data using <div style="display:none">

you should add style="display:none" in any of <tr> that you want to hide.

undefined reference to WinMain@16 (codeblocks)

I had the same error problem using Code Blocks rev 13.12. I may be wrong here since I am less than a beginner :)

My problem was that I accidentally capitalized "M" in Main() instead of ALL lowercase = main() - once corrected, it worked!!!

I noticed that you have "int main()" instead of "main()". Is this the problem, or is it supposed to be that way?

Hope I could help...

How can I inspect element in chrome when right click is disabled?

Sure, you can open the devtools with Ctrl+Shift+I, and then click the inspect element button (square with the arrow)

Python - How do you run a .py file?

Since you seem to be on windows you can do this so python <filename.py>. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

Dictionary text file

What about /usr/share/dict/words on any Unix system? How many words are we talking about? Like OED-Unabridged?

Select where count of one field is greater than one

Use the HAVING, not WHERE clause, for aggregate result comparison.

Taking the query at face value:

SELECT * 
  FROM db.table 
HAVING COUNT(someField) > 1

Ideally, there should be a GROUP BY defined for proper valuation in the HAVING clause, but MySQL does allow hidden columns from the GROUP BY...

Is this in preparation for a unique constraint on someField? Looks like it should be...

How to find locked rows in Oracle

Oracle's locking concept is quite different from that of the other systems.

When a row in Oracle gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.

This means that locking a record in Oracle means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE on a read only tablespace.

More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.

This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.

Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.

You can obtain some special locks, like locked metadata objects (using v$locked_object), lock waits (using v$session) etc, but not the list of all locks on all objects in the database.

Make browser window blink in task Bar

this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab.

newExcitingAlerts = (function () {
    var oldTitle = document.title;
    var msg = "New!";
    var timeoutId;
    var blink = function() { document.title = document.title == msg ? ' ' : msg; };
    var clear = function() {
        clearInterval(timeoutId);
        document.title = oldTitle;
        window.onmousemove = null;
        timeoutId = null;
    };
    return function () {
        if (!timeoutId) {
            timeoutId = setInterval(blink, 1000);
            window.onmousemove = clear;
        }
    };
}());

Update: You may want to look at using HTML5 notifications.

Addressing localhost from a VirtualBox virtual machine

A combination of a few things eventually got things working on my end. Running a flask server on macosx.

In my windows VM I edited the hosts file:

  • Run notepad as administrator
  • open C:\windows\system32\drivers\etc\hosts
  • add this entry: 10.0.2.2 outer

Shutdown VM and on my Mac in VirtualBox:

  • Go to VirtualBox > preferences > Network > Host-only Networks > + to add a network vboxnet1
  • Go to My_VM > settings > Network > Adapter 1.
  • Select Enable Network Adapter and set Attached to: to Bridged Adapter.
  • Then set Advanced > Promiscuous Mode: to Allow VMs.
  • Click OK
  • Go to My_VM > settings > Network > Adapter 1.
  • Set Attached to: back to NAT.

Then I went to Adapter 2

  • Set Attached to: to Host-only Adapter and select the previous added network vboxnet1.

I started my server on my mac, running on 127.0.0.1:5000 and this was now accessible on my vm at http://10.0.2.2:5000

Man what a nightmare to test on IE on mac. How is there not a simpler way?

What is the difference between a JavaBean and a POJO?

Java beans are special type of POJOs.

Specialities listed below with reason

enter image description here

Returning first x items from array

You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

The name 'model' does not exist in current context in MVC3

Reinstalling the nuget solved it for me

PM> Install-Package Microsoft.AspNet.Razor -Version 3.2.3

How to play a sound in C#, .NET

Code bellow allows to play mp3-files and in-memory wave-files too

player.FileName = "123.mp3";
player.Play();

from http://alvas.net/alvas.audio,samples.aspx#sample6 or

Player pl = new Player();
byte[] arr = File.ReadAllBytes(@"in.wav");
pl.Play(arr);

from http://alvas.net/alvas.audio,samples.aspx#sample7

Apache2: 'AH01630: client denied by server configuration'

I actually solved this one by adding the directory access to the :80 entry.

 <Directory "c:/whatever-directory-you-use/">
    AllowOverride All
    Require all granted
</Directory>

Before everyone gets all 'security' on me, under my specific circumstances this is not a security issue.

If you are using a remote resource, I'd recommend instead make sure your CURL request goes via HTTPS / TLS, then this directory entry goes on the 443 port.

Linq Select Group By

var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();

I have converted it to int because my Price field was int and Average method return double .I hope this will help

Stopping a JavaScript function when a certain condition is met

use return for this

if(i==1) { 
    return; //stop the execution of function
}

//keep on going

EF Core add-migration Build Failed

The developer ended up un-mapping the project from TFS, deleting it, and re-mapping it. It's now working for him.

XSS prevention in JSP/Servlet web application

If you want to automatically escape all JSP variables without having to explicitly wrap each variable, you can use an EL resolver as detailed here with full source and an example (JSP 2.0 or newer), and discussed in more detail here:

For example, by using the above mentioned EL resolver, your JSP code will remain like so, but each variable will be automatically escaped by the resolver

...
<c:forEach items="${orders}" var="item">
  <p>${item.name}</p>
  <p>${item.price}</p>
  <p>${item.description}</p>
</c:forEach>
...

If you want to force escaping by default in Spring, you could consider this as well, but it doesn't escape EL expressions, just tag output, I think:

http://forum.springsource.org/showthread.php?61418-Spring-cross-site-scripting&p=205646#post205646

Note: Another approach to EL escaping that uses XSL transformations to preprocess JSP files can be found here:

http://therning.org/niklas/2007/09/preprocessing-jsp-files-to-automatically-escape-el-expressions/

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Binding an enum to a WinForms combo box, and then setting it

In Framework 4 you can use the following code:

To bind MultiColumnMode enum to combobox for example:

cbMultiColumnMode.Properties.Items.AddRange(typeof(MultiColumnMode).GetEnumNames());

and to get selected index:

MultiColumnMode multiColMode = (MultiColumnMode)cbMultiColumnMode.SelectedIndex;

note: I use DevExpress combobox in this example, you can do the same in Win Form Combobox

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

Write to CSV file and export it?

Rom, you're doing it wrong. You don't want to write files to disk so that IIS can serve them up. That adds security implications as well as increases complexity. All you really need to do is save the CSV directly to the response stream.

Here's the scenario: User wishes to download csv. User submits a form with details about the csv they want. You prepare the csv, then provide the user a URL to an aspx page which can be used to construct the csv file and write it to the response stream. The user clicks the link. The aspx page is blank; in the page codebehind you simply write the csv to the response stream and end it.

You can add the following to the (I believe this is correct) Load event:

string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");

var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
  sb.AppendLine(TransformDataLineIntoCsv(line));

HttpContext.Current.Response.Write(sb.ToString());

writing to the response stream code ganked from here.

Logo image and H1 heading on the same line

<head>
<style>
header{
    color: #f4f4f4;
    background-image: url("header-background.jpeg");    
}

header img{
    float: left;
    display: inline-block;
}

header h1{
    font-size: 40px; 
    color: #f4f4f4;
    display: inline-block;
    position: relative;
    padding: 20px 20px 0 0;
    display: inline-block;
}
</style></head>


<header>
<a href="index.html">
    <img src="./branding.png" alt="technocrat logo" height="100px" width="100px"></a>
    <a href="index.html">
    <h1><span> Technocrat</span> Blog</h1></a>
</div></header>

How can I reverse a list in Python?

The most direct translation of your requirement into Python is this for statement:

for i in xrange(len(array) - 1, -1, -1):
   print i, array[i]

This is rather cryptic but may be useful.

Disable future dates in jQuery UI Datepicker

Try This:

$('#datepicker').datepicker({
    endDate: new Date()
});

It will disable the future date.

How to log out user from web site using BASIC authentication?

Just for the record, there is a new HTTP Response Header called Clear-Site-Data. If your server reply includes a Clear-Site-Data: "cookies" header, then the authentication credentials (not only cookies) should be removed. I tested it on Chrome 77 but this warning shows on the console:

Clear-Site-Data header on 'https://localhost:9443/clear': Cleared data types:
"cookies". Clearing channel IDs and HTTP authentication cache is currently not
supported, as it breaks active network connections.

And the auth credentials aren't removed, so this doesn't works (for now) to implement basic auth logouts, but maybe in the future will. Didn't test on other browsers.

References:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

https://www.w3.org/TR/clear-site-data/

https://github.com/w3c/webappsec-clear-site-data

https://caniuse.com/#feat=mdn-http_headers_clear-site-data_cookies

jQuery Set Cursor Position in Text Area

You can directly change the prototype if setSelectionRange does not exist.

(function() {
    if (!HTMLInputElement.prototype.setSelectionRange) {
        HTMLInputElement.prototype.setSelectionRange = function(start, end) {
            if (this.createTextRange) {
                var range = this.createTextRange();
                this.collapse(true);
                this.moveEnd('character', end);
                this.moveStart('character', start);
                this.select();
            }
        }
    }
})();
document.getElementById("input_tag").setSelectionRange(6, 7);

jsFiddle link

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

good points already made here, but while there is lots of information about how rendering of margins is accomplished by the browser, the why isn't quite answered yet:

"Why is margin-top:-8px not the same as margin-bottom:8px?"

what we also could ask is:

Why doesn't a positive bottom margin 'bump up' preceding elements, whereas a positive top-margin 'bumps down' following elements?

so what we see is that there is a difference in the rendering of margins depending on the side they are applied to - top (and left) margins are different from bottom (and right) ones.

things are becoming clearer when having a (simplified) look at how styles are applied by the browser: elements are rendered top-down in the viewport, starting in the top left corner (let's stick with the vertical rendering for now, keeping in mind that the horizontal one is treated the same).

consider the following html:

<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>

analogous to their position in code, these three boxes appear stacked 'top-down' in the browser (keeping things simple, we won't consider here the order property of the css3 'flex-box' module). so, whenever styles are applied to box 3, preceding element's positions (for box 1 and 2) have already been determined, and shouldn't be altered any more for the sake of rendering speed.

now, imagine a top margin of -10px for box 3. instead of shifting up all preceding elements to gather some space, the browser will just push box 3 up, so it's rendered on top of (or underneath, depending on the z-index) any preceding elements. even if performance wasn't an issue, moving all elements up could mean shifting them out of the viewport, thus the current scrolling position would have to be altered to have everything visible again.

same applies to a bottom margin for box 3, both negative and positive: instead of influencing already evaluated elements, only a new 'starting point' for upcoming elements is determined. thus setting a positive bottom margin will push the following elements down; a negative one will push them up.

Redirecting unauthorized controller in ASP.NET MVC

You can work with the overridable HandleUnauthorizedRequest inside your custom AuthorizeAttribute

Like this:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    // Returns HTTP 401 by default - see HttpUnauthorizedResult.cs.
    filterContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary 
    {
        { "action", "YourActionName" },
        { "controller", "YourControllerName" },
        { "parameterName", "YourParameterValue" }
    });
}

You can also do something like this:

private class RedirectController : Controller
{
    public ActionResult RedirectToSomewhere()
    {
        return RedirectToAction("Action", "Controller");
    }
}

Now you can use it in your HandleUnauthorizedRequest method this way:

filterContext.Result = (new RedirectController()).RedirectToSomewhere();

ASP.NET Web API session or something?

in Global.asax add

public override void Init()
{
    this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
    base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(
        SessionStateBehavior.Required);
}

give it a shot ;)

Left align and right align within div in Bootstrap

Instead of using pull-right class, it is better to use text-right class in the column, because pull-right creates problems sometimes while resizing the page.

Display Bootstrap Modal using javascript onClick

You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation

<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals

How can I "reset" an Arduino board?

I just spent the last five hours searching for a solution to this problem (serial port COM3 already in use and grayed out serial port)...I tried everything every forum and Q&A site I could find suggested, including this one...

What finally fixed it (got rid of the last code I'd input that got stuck and uploaded simple blink function)?

Follow this link -- http://arduino.cc/en/guide/windows and follow the instructions for installing the drivers. My driver was "already up to date", but following these steps fixed the glitch. I am now a happy camper once again.

Note: Resetting the board manually with the button on the chip, or digitally through miscellaneous codes on the Internet did not work to fix this problem, because the signal was somehow blocked/confused between my Arduino Uno and the port in my laptop. Updating the drivers is like a reset for the "serial port already in use" problem.

At least so far...

Create a branch in Git from another branch

To create a branch from another branch in your local directory you can use following command.

git checkout -b <sub-branch> branch

For Example:

  • name of the new branch to be created 'XYZ'
  • name of the branch ABC under which XYZ has to be created
git checkout -b XYZ ABC

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

If anyone is having this problem when trying to run Jupyter kernel from a virtualenv, just add correct PYTHONPATH to kernel.json of your virtualenv kernel (Python 3 in example):

{
 "argv": [
  "/usr/local/Cellar/python/3.6.5/bin/python3.6",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "Python 3 (TensorFlow)",
 "language": "python",
 "env": {
     "PYTHONPATH":     "/Users/dimitrijer/git/mlai/.venv/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/lib-dynload:/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/site-packages"
}
}

Printing hexadecimal characters in C

You are probably storing the value 0xc0 in a char variable, what is probably a signed type, and your value is negative (most significant bit set). Then, when printing, it is converted to int, and to keep the semantical equivalence, the compiler pads the extra bytes with 0xff, so the negative int will have the same numerical value of your negative char. To fix this, just cast to unsigned char when printing:

printf("%x", (unsigned char)variable);

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

_x000D_
_x000D_
function pad(num) {return ("0" + num).slice(-2);}_x000D_
function time1() {_x000D_
  var today = new Date(),_x000D_
    h = today.getHours(),_x000D_
    m = today.getMinutes(),_x000D_
    s = today.getSeconds();_x000D_
    _x000D_
  h = h % 12;_x000D_
  h = h ? h : 12; // the hour '0' should be '12'_x000D_
  clk.innerHTML = h + ':' + _x000D_
    pad(m) + ':' + _x000D_
    pad(s) + ' ' + _x000D_
    (h >= 12 ? 'PM' : 'AM');_x000D_
}_x000D_
window.onload = function() {_x000D_
  var clk = document.getElementById('clk');_x000D_
  t = setInterval(time1, 500);_x000D_
}
_x000D_
<span id="clk"></span>
_x000D_
_x000D_
_x000D_

How do I get the coordinates of a mouse click on a canvas element?

Be wary while doing the coordinate conversion; there are multiple non-cross-browser values returned in a click event. Using clientX and clientY alone are not sufficient if the browser window is scrolled (verified in Firefox 3.5 and Chrome 3.0).

This quirks mode article provides a more correct function that can use either pageX or pageY or a combination of clientX with document.body.scrollLeft and clientY with document.body.scrollTop to calculate the click coordinate relative to the document origin.

UPDATE: Additionally, offsetLeft and offsetTop are relative to the padded size of the element, not the interior size. A canvas with the padding: style applied will not report the top-left of its content region as offsetLeft. There are various solutions to this problem; the simplest one may be to clear all border, padding, etc. styles on the canvas itself and instead apply them to a box containing the canvas.

How can I create an utility class?

I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

How to Set OnClick attribute with value containing function in ie8?

You could also set onclick to call your function like this:

foo.onclick = function() { callYourJSFunction(arg1, arg2); };

This way, you can pass arguments too. .....

Unresolved reference issue in PyCharm

Please check if you are using the right interpreter that you are supposed to. I was getting error "unresolved reference 'django' " to solve this I changed Project Interpreter (Changed Python 3 to Python 2.7) from project settings: Select Project, go to File -> Settings -> Project: -> Project Interpreter -> Brows and Select correct version or Interpreter (e.g /usr/bin/python2.7).

When does Git refresh the list of remote branches?

If you are using Eclipse,

  1. Open "Git Repositories"
  2. Find your Repository.
  3. Open up "Branches" then "Remote Tracking".

Git

They should all be in there. Right click and "checkout."

How to add a margin to a table row <tr>

For what is worth, I took advantage that I was already using bootstrap (4.3), because I needed to add margin, box-shadow and border-radius to my row, something I can't do with tables.

<div id="loop" class="table-responsive px-4">
<section>
    <div id="thead" class="row m-0">
        <div class="col"></div>
        <div class="col"></div>
        <div class="col"></div>
    </div>
    <div id="tbody" class="row m-0">
        <div class="col"></div>
        <div class="col"></div>
        <div class="col"></div>
    </div>
</section>
</div>

On css I added a few lines to mantain the table behavior of bootstrap

@media (max-width: 800px){
    #loop{
        section{
            min-width: 700px;
        }
    }
}

HTML/Javascript Button Click Counter

Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"

<html>
<head>
    <title>Space Clicker</title>
</head>

<body>
    <script type="text/javascript">

    var clicks = 0;
    function hello() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    </script>
    <button type="button" onclick="hello()">Click me</button>
    <p>Clicks: <a id="clicks">0</a></p>

</body></html>

How to add jQuery in JS file

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

What does the colon (:) operator do?

The colon actually exists in conjunction with ?

int minVal = (a < b) ? a : b;

is equivalent to:

int minval;
if(a < b){ minval = a;} 
else{ minval = b; }

Also in the for each loop:

for(Node n : List l){ ... }

literally:

for(Node n = l.head; n.next != null; n = n.next)

Creating pdf files at runtime in c#

iTextSharp http://itextsharp.sourceforge.net/

Complex but comprehensive.

itext7 former iTextSharp

Swift programmatically navigate to another view controller/scene

Swift 5

The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

To retain the old style you need to modify the view controller you will be presenting like this:

newViewController.modalPresentationStyle = .fullScreen

This is the same for both programmatically created and storyboard created controllers.

Swift 3

With a programmatically created Controller

If you want to navigate to Controller created Programmatically, then do this:

let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)

With a StoryBoard created Controller

If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
        self.present(newViewController, animated: true, completion: nil)

Change the Theme in Jupyter Notebook?

To install the Jupyterthemes package directly with conda, use:

conda install -c conda-forge jupyterthemes

Then, as others have pointed out, change the theme with jt -t <theme-name>

Jquery Hide table rows

this might work for you...

$('.trhideclass1').hide();

 

<tr class="trhideclass1">
  <td>Label</td>
  <td>InputFile</td>
</tr>

Start ssh-agent on login

Add this to your ~/.bashrc, then logout and back in to take effect.

if [ ! -S ~/.ssh/ssh_auth_sock ]; then
  eval `ssh-agent`
  ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
ssh-add -l > /dev/null || ssh-add

This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.

Calculating powers of integers

Google Guava has math utilities for integers. IntMath

HTML5 validation when the input type is not "submit"

Either you can change the button type to submit

<button type="submit"  onclick="submitform()" id="save">Save</button>

Or you can hide the submit button, keep another button with type="button" and have click event for that button

<form>
    <button style="display: none;" type="submit" >Hidden button</button>
    <button type="button" onclick="submitForm()">Submit</button>
</form>

JPA CascadeType.ALL does not delete orphans

I just find this solution but in my case it doesn't work:

@OneToMany(cascade = CascadeType.ALL, targetEntity = MyClass.class, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true) 

orphanRemoval = true has no effect.

Minimum rights required to run a windows service as a domain account

"BypassTraverseChecking" means that you can directly access any deep-level subdirectory even if you don't have all the intermediary access privileges to directories in between, i.e. all directories above it towards root level .

Python sys.argv lists and indexes

In a nutshell, sys.argv is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0], and the second element (first argument, if there is one) is sys.argv[1], etc.

The test len(sys.argv) >= 2 simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.

All shards failed

If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.

From ElasticSearch Blog

apache ProxyPass: how to preserve original IP address

You can get the original host from X-Forwarded-For header field.

How/When does Execute Shell mark a build as failure in Jenkins?

In my opinion, turning off the -e option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.

If you have a line in your script where failure is expected, like a grep or a find, then just add || true to the end of that line. That ensures that line will always return success.

If you need to use that exit code, you can either hoist the command into your if statement:

grep foo bar; if [ $? == 0 ]; then ...    -->   if grep foo bar; then ...

Or you can capture the return code in your || clause:

grep foo bar || ret=$?

How to show android checkbox at right side?

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/location_permissions"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="@android:color/black" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <CheckBox
                android:id="@+id/location_permission_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="8dp"
                android:onClick="onLocationPermissionClicked" />

        </RelativeLayout>
    </LinearLayout>

Git push hangs when pushing to Github?

Will usually see myself running into this problem when pushing a large quantity of files.

If you can be patient and let the files finishing uploading, you might not need to do anything at all. Good luck –

How can I run dos2unix on an entire directory?

A common use case appears to be to standardize line endings for all files committed to a Git repository:

git ls-files | xargs dos2unix

Keep in mind that certain files (e.g. *.sln, *.bat) etc are only used on Windows operating systems and should keep the CRLF ending:

git ls-files '*.sln' '*.bat' | xargs unix2dos

If necessary, use .gitattributes

Which characters need to be escaped when using Bash?

To save someone else from having to RTFM... in bash:

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.

...so if you escape those (and the quote itself, of course) you're probably okay.

If you take a more conservative 'when in doubt, escape it' approach, it should be possible to avoid getting instead characters with special meaning by not escaping identifier characters (i.e. ASCII letters, numbers, or '_'). It's very unlikely these would ever (i.e. in some weird POSIX-ish shell) have special meaning and thus need to be escaped.

JavaScript moving element in the DOM

Trivial with jQuery

$('#div1').insertAfter('#div3');
$('#div3').insertBefore('#div2');

If you want to do it repeatedly, you'll need to use different selectors since the divs will retain their ids as they are moved around.

$(function() {
    setInterval( function() {
        $('div:first').insertAfter($('div').eq(2));
        $('div').eq(1).insertBefore('div:first');
    }, 3000 );
});

Should I initialize variable within constructor or outside constructor

I think both are correct programming wise,

But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.

I think it is the "by the book" convention, but it is open for discussion.

Wikipedia

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

(\s|\(|\.|,|^)bqr(\s|,|\)|$)

Aggregate function in SQL WHERE-Clause

HAVING is like WHERE with aggregate functions, or you could use a subquery.

select EmployeeId, sum(amount)
from Sales
group by Employee
having sum(amount) > 20000

Or

select EmployeeId, sum(amount)
from Sales
group by Employee
where EmployeeId in (
    select max(EmployeeId) from Employees)

How to resize images proportionally / keeping the aspect ratio?

This should work for images with all possible proportions

$(document).ready(function() {
    $('.list img').each(function() {
        var maxWidth = 100;
        var maxHeight = 100;
        var width = $(this).width();
        var height = $(this).height();
        var ratioW = maxWidth / width;  // Width ratio
        var ratioH = maxHeight / height;  // Height ratio

        // If height ratio is bigger then we need to scale height
        if(ratioH > ratioW){
            $(this).css("width", maxWidth);
            $(this).css("height", height * ratioW);  // Scale height according to width ratio
        }
        else{ // otherwise we scale width
            $(this).css("height", maxHeight);
            $(this).css("width", height * ratioH);  // according to height ratio
        }
    });
});

Correct way to push into state array

You can use .concat method to create copy of your array with new data:

this.setState({ myArray: this.state.myArray.concat('new value') })

But beware of special behaviour of .concat method when passing arrays - [1, 2].concat(['foo', 3], 'bar') will result in [1, 2, 'foo', 3, 'bar'].

HTML 5: Is it <br>, <br/>, or <br />?

Both <br> and <br/> will do fine but I prefer <br/> because it's slightly more logical. It is logical to expect a closing tag whenever there is an opening tag. Therefore your code is slightly easier to read if you don't use an opening tag when there isn't going to be a closing tag.

All browser (except possibly some very old ones that don't matter) will display both exactly the same. However, <br> is not xHTML complient.

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

What is the difference between id and class in CSS, and when should I use them?

id:

It will identify the unique element of your entire page. No other element should be declared with the same id. The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the HTML element, and is defined with a "#".

class:

The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.

This allows you to set a particular style for many HTML elements with the same class.

The class selector uses the HTML class attribute, and is defined with a "."

How to use onSavedInstanceState example please

Store information:

static final String PLAYER_SCORE = "playerScore";
static final String PLAYER_LEVEL = "playerLevel";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(PLAYER_SCORE, mCurrentScore);
    savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel);

// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

If you don't want to restore information in your onCreate-Method:

Here are the examples: Recreating an Activity

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);

// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(PLAYER_SCORE);
mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL);
}

How do I block comment in Jupyter notebook?

I tried this on Mac OSX with Chrome 42.0.2311.90 (64-bit) and this works by using CMD + /

The version of the notebook server is 3.1.0-cbccb68 and is running on:
Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34) 
[GCC 4.2.1 (Apple Inc. build 5577)]

Could it be a browser related problem? Did you try Firefox or IE?

Multidimensional Array [][] vs [,]

double[][] are called jagged arrays , The inner dimensions aren’t specified in the declaration. Unlike a rectangular array, each inner array can be an arbitrary length. Each inner array is implicitly initialized to null rather than an empty array. Each inner array must be created manually: Reference [C# 4.0 in nutshell The definitive Reference]

for (int i = 0; i < matrix.Length; i++)
{
    matrix[i] = new int [3]; // Create inner array
    for (int j = 0; j < matrix[i].Length; j++)
        matrix[i][j] = i * 3 + j;
}

double[,] are called rectangular arrays, which are declared using commas to separate each dimension. The following piece of code declares a rectangular 3-by-3 two-dimensional array, initializing it with numbers from 0 to 8:

int [,] matrix = new int [3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
    for (int j = 0; j < matrix.GetLength(1); j++)
        matrix [i, j] = i * 3 + j;

Get current time as formatted string in Go?

All the other response are very miss-leading for somebody coming from google and looking for "timestamp in go"! YYYYMMDDhhmmss is not a "timestamp".

To get the "timestamp" of a date in go (number of seconds from january 1970), the correct function is .Unix(), and it really return an integer

What is an opaque response, and what purpose does it serve?

There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.

The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".

This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html

How to create SPF record for multiple IPs?

Try this:

v=spf1 ip4:abc.de.fgh.ij ip4:klm.no.pqr.st ~all

Is there a date format to display the day of the week in java?

SimpleDateFormat sdf=new SimpleDateFormat("EEE");

EEE stands for day of week for example Thursday is displayed as Thu.

How to set a radio button in Android

btnDisplay.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

            // get selected radio button from radioGroup
        int selectedId = radioSexGroup.getCheckedRadioButtonId();

        // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

        Toast.makeText(MyAndroidAppActivity.this,
            radioSexButton.getText(), Toast.LENGTH_SHORT).show();

    }

});

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

Pygame mouse clicking detection

I assume your game has a main loop, and all your sprites are in a list called sprites.

In your main loop, get all events, and check for the MOUSEBUTTONDOWN or MOUSEBUTTONUP event.

while ... # your main loop
  # get all events
  ev = pygame.event.get()

  # proceed events
  for event in ev:

    # handle MOUSEBUTTONUP
    if event.type == pygame.MOUSEBUTTONUP:
      pos = pygame.mouse.get_pos()

      # get a list of all sprites that are under the mouse cursor
      clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
      # do something with the clicked sprites...

So basically you have to check for a click on a sprite yourself every iteration of the mainloop. You'll want to use mouse.get_pos() and rect.collidepoint().

Pygame does not offer event driven programming, as e.g. cocos2d does.

Another way would be to check the position of the mouse cursor and the state of the pressed buttons, but this approach has some issues.

if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
  print ("You have opened a chest!")

You'll have to introduce some kind of flag if you handled this case, since otherwise this code will print "You have opened a chest!" every iteration of the main loop.

handled = False

while ... // your loop

  if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
    print ("You have opened a chest!")
    handled = pygame.mouse.get_pressed()[0]

Of course you can subclass Sprite and add a method called is_clicked like this:

class MySprite(Sprite):
  ...

  def is_clicked(self):
    return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())

So, it's better to use the first approach IMHO.

How to get the xml node value in string

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}

or you could wrap in foreach loop to print each value

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    foreach(XmlNode curr in n) {
        Console.WriteLine(curr.InnerText);
    }
}

What is more efficient? Using pow to square or just multiply it with itself?

I tested the performance difference between x*x*... vs pow(x,i) for small i using this code:

#include <cstdlib>
#include <cmath>
#include <boost/date_time/posix_time/posix_time.hpp>

inline boost::posix_time::ptime now()
{
    return boost::posix_time::microsec_clock::local_time();
}

#define TEST(num, expression) \
double test##num(double b, long loops) \
{ \
    double x = 0.0; \
\
    boost::posix_time::ptime startTime = now(); \
    for (long i=0; i<loops; ++i) \
    { \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
    } \
    boost::posix_time::time_duration elapsed = now() - startTime; \
\
    std::cout << elapsed << " "; \
\
    return x; \
}

TEST(1, b)
TEST(2, b*b)
TEST(3, b*b*b)
TEST(4, b*b*b*b)
TEST(5, b*b*b*b*b)

template <int exponent>
double testpow(double base, long loops)
{
    double x = 0.0;

    boost::posix_time::ptime startTime = now();
    for (long i=0; i<loops; ++i)
    {
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
    }
    boost::posix_time::time_duration elapsed = now() - startTime;

    std::cout << elapsed << " ";

    return x;
}

int main()
{
    using std::cout;
    long loops = 100000000l;
    double x = 0.0;
    cout << "1 ";
    x += testpow<1>(rand(), loops);
    x += test1(rand(), loops);

    cout << "\n2 ";
    x += testpow<2>(rand(), loops);
    x += test2(rand(), loops);

    cout << "\n3 ";
    x += testpow<3>(rand(), loops);
    x += test3(rand(), loops);

    cout << "\n4 ";
    x += testpow<4>(rand(), loops);
    x += test4(rand(), loops);

    cout << "\n5 ";
    x += testpow<5>(rand(), loops);
    x += test5(rand(), loops);
    cout << "\n" << x << "\n";
}

Results are:

1 00:00:01.126008 00:00:01.128338 
2 00:00:01.125832 00:00:01.127227 
3 00:00:01.125563 00:00:01.126590 
4 00:00:01.126289 00:00:01.126086 
5 00:00:01.126570 00:00:01.125930 
2.45829e+54

Note that I accumulate the result of every pow calculation to make sure the compiler doesn't optimize it away.

If I use the std::pow(double, double) version, and loops = 1000000l, I get:

1 00:00:00.011339 00:00:00.011262 
2 00:00:00.011259 00:00:00.011254 
3 00:00:00.975658 00:00:00.011254 
4 00:00:00.976427 00:00:00.011254 
5 00:00:00.973029 00:00:00.011254 
2.45829e+52

This is on an Intel Core Duo running Ubuntu 9.10 64bit. Compiled using gcc 4.4.1 with -o2 optimization.

So in C, yes x*x*x will be faster than pow(x, 3), because there is no pow(double, int) overload. In C++, it will be the roughly same. (Assuming the methodology in my testing is correct.)


This is in response to the comment made by An Markm:

Even if a using namespace std directive was issued, if the second parameter to pow is an int, then the std::pow(double, int) overload from <cmath> will be called instead of ::pow(double, double) from <math.h>.

This test code confirms that behavior:

#include <iostream>

namespace foo
{

    double bar(double x, int i)
    {
        std::cout << "foo::bar\n";
        return x*i;
    }


}

double bar(double x, double y)
{
    std::cout << "::bar\n";
    return x*y;
}

using namespace foo;

int main()
{
    double a = bar(1.2, 3); // Prints "foo::bar"
    std::cout << a << "\n";
    return 0;
}

How do I compile a .cpp file on Linux?

The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.

Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

You should simply apply the following transformation to your input data array.

input_data = input_data.reshape((-1, image_side1, image_side2, channels))

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Combine Powershell into a batch file and use the meta variables to assign each:

@echo off
for /f "tokens=1-6 delims=-" %%a in ('PowerShell -Command "& {Get-Date -format "yyyy-MM-dd-HH-mm-ss"}"') do (
    echo year: %%a
    echo month: %%b
    echo day: %%c
    echo hour: %%d
    echo minute: %%e
    echo second: %%f
)

You can also change the the format if you prefer name of the month MMM or MMMM and 12 hour to 24 hour formats hh or HH

How to grep and replace

Here is what I would do:

find /path/to/dir -type f -iname "*filename*" -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'

this will look for all files containing filename in the file's name under the /path/to/dir, than for every file found, search for the line with searchstring and replace old with new.

Though if you want to omit looking for a specific file with a filename string in the file's name, than simply do:

find /path/to/dir -type f -print0 | xargs -0 sed -i '/searchstring/s/old/new/g'

This will do the same thing above, but to all files found under /path/to/dir.

How to download fetch response in react as file

I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was

onClick = () => {
  // do something to compute or go fetch
  // the url we need from the server
  const url = goComputeOrFetchURL();

  // window.location forces the browser to prompt the user if they want to download it
  window.location = url
}

render() {
  return (
    <Button onClick={ this.onClick } />
  );
}

How can I put a database under git (version control)?

I'm starting to think of a really simple solution, don't know why I didn't think of it before!!

  • Duplicate the database, (both the schema and the data).
  • In the branch for the new-major-changes, simply change the project configuration to use the new duplicate database.

This way I can switch branches without worrying about database schema changes.

EDIT:

By duplicate, I mean create another database with a different name (like my_db_2); not doing a dump or anything like that.

Java java.sql.SQLException: Invalid column index on preparing statement

As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....

The ? and the OR needs to be seperated by a space character. Do it wherever needed in the query string.

Maintain the aspect ratio of a div with CSS

While most answers are very cool, most of them require to have an image already sized correctly... Other solutions only work for a width and do not care of the height available, but sometimes you want to fit the content in a certain height too.

I've tried to couple them together to bring a fully portable and re-sizable solution... The trick is to use to auto scaling of an image but use an inline svg element instead of using a pre-rendered image or any form of second HTTP request...

_x000D_
_x000D_
div.holder{_x000D_
  background-color:red;_x000D_
  display:inline-block;_x000D_
  height:100px;_x000D_
  width:400px;_x000D_
}_x000D_
svg, img{_x000D_
  background-color:blue;_x000D_
  display:block;_x000D_
  height:auto;_x000D_
  width:auto;_x000D_
  max-width:100%;_x000D_
  max-height:100%;_x000D_
}_x000D_
.content_sizer{_x000D_
  position:relative;_x000D_
  display:inline-block;_x000D_
  height:100%;_x000D_
}_x000D_
.content{_x000D_
  position:absolute;_x000D_
  top:0;_x000D_
  bottom:0;_x000D_
  left:0;_x000D_
  right:0;_x000D_
  background-color:rgba(155,255,0,0.5);_x000D_
}
_x000D_
<div class="holder">_x000D_
  <div class="content_sizer">_x000D_
    <svg width=10000 height=5000 />_x000D_
    <div class="content">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Notice that I have used big values in the width and height attributes of the SVG, as it needs to be bigger than the maximum expected size as it can only shrink. The example makes the div's ratio 10:5

Notepad++ - How can I replace blank lines

As of NP++ V6.2.3 (nor sure about older versions) simply:

  1. Go menu -> Edit -> Line operations
  2. Choose "Remove Empty Lines" or "Remove Empty Lines (Containing white spaces)" according to your needs.

Hope this helps to achieve goal in simple and yet fast way:)

Returning binary file from controller in ASP.NET Web API

While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :

  • In the request, set header "Accept: application/octet-stream".
  • Server-side, add a media type formatter to support this mime type.

Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).

You can add this formatter into your global config :

HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));

WebApi should now use BinaryMediaTypeFormatter if the request specifies the correct Accept header.

I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").

Summernote image upload

UPLOAD IMAGES WITH PROGRESS BAR

Thought I'd extend upon user3451783's answer and provide one with an HTML5 progress bar. I found that it was very annoying uploading photos without knowing if anything was happening at all.

HTML

<progress></progress>

<div id="summernote"></div>

JS

// initialise editor

$('#summernote').summernote({
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
});

// send the file

function sendFile(file, editor, welEditable) {
        data = new FormData();
        data.append("file", file);
        $.ajax({
            data: data,
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                return myXhr;
            },
            url: root + '/assets/scripts/php/app/uploadEditorImages.php',
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                editor.insertImage(welEditable, url);
            }
        });
}

// update progress bar

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded, max:e.total});
        // reset progress on complete
        if (e.loaded == e.total) {
            $('progress').attr('value','0.0');
        }
    }
}

Round float to x decimals?

Use the built-in function round():

In [23]: round(66.66666666666,4)
Out[23]: 66.6667

In [24]: round(1.29578293,6)
Out[24]: 1.295783

help on round():

round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.

Entity Framework Queryable async

There is a massive difference in the example you have posted, the first version:

var urls = await context.Urls.ToListAsync();

This is bad, it basically does select * from table, returns all results into memory and then applies the where against that in memory collection rather than doing select * from table where... against the database.

The second method will not actually hit the database until a query is applied to the IQueryable (probably via a linq .Where().Select() style operation which will only return the db values which match the query.

If your examples were comparable, the async version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async functionality.

However the major difference (and benefit) is that the async version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

Is there a C# case insensitive equals operator?

or

if (StringA.Equals(StringB, StringComparison.CurrentCultureIgnoreCase)) {

but you need to be sure that StringA is not null. So probably better tu use:

string.Equals(StringA , StringB, StringComparison.CurrentCultureIgnoreCase);

as John suggested

EDIT: corrected the bug

What is [Serializable] and when should I use it?

Some practical uses for the [Serializable] attribute:

  • Saving object state using binary serialisation; you can very easily 'save' entire object instances in your application to a file or network stream and then recreate them by deserialising - check out the BinaryFormatter class in System.Runtime.Serialization.Formatters.Binary
  • Writing classes whose object instances can be stored on the clipboard using Clipboard.SetData() - nonserialisable classes cannot be placed on the clipboard.
  • Writing classes which are compatible with .NET Remoting; generally, any class instance you pass between application domains (except those which extend from MarshalByRefObject) must be serialisable.

These are the most common usage cases that I have come across.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

NSArray + remove item from array

NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:

[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];

SOAP or REST for Web Services?

REST is an architecture invented by Roy Fielding and described in his dissertation Architectural Styles and the Design of Network-based Software Architectures. Roy is also the main author of HTTP - the protocol that defines document transfer over the World Wide Web. HTTP is a RESTful protocol. When developers talk about "using REST Web services" it is probably more accurate to say "using HTTP."

SOAP is a XML-based protocol that tunnels inside an HTTP request/response, so even if you use SOAP, you are using REST too. There is some debate over whether SOAP adds any significant functionality to basic HTTP.

Before authoring a Web service, I would recommend studying HTTP. Odds are your requirements can be implemented with functionality already defined in the spec, so other protocols won't be needed.

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

"X does not name a type" error in C++

You must declare the prototype it before using it:

class User;

class MyMessageBox
{
public:
 void sendMessage(Message *msg, User *recvr);
 Message receiveMessage();
 vector<Message> *dataMessageList;
};

class User
{
public:
 MyMessageBox dataMsgBox;
};

edit: Swapped the types

How to copy a row from one SQL Server table to another

SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >

Define a struct inside a class in C++

The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.

The syntax for this is as follows:

class Container {

    ...

    struct Inner; // Declare, but not define, the struct.

    ...

};

struct Container::Inner {
   /* Define the struct here. */
};

You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.

Python Brute Force algorithm

Use itertools.product, combined with itertools.chain to put the various lengths together:

from itertools import chain, product
def bruteforce(charset, maxlength):
    return (''.join(candidate)
        for candidate in chain.from_iterable(product(charset, repeat=i)
        for i in range(1, maxlength + 1)))

Demonstration:

>>> list(bruteforce('abcde', 2))
['a', 'b', 'c', 'd', 'e', 'aa', 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db', 'dc', 'dd', 'de', 'ea', 'eb', 'ec', 'ed', 'ee']

This will efficiently produce progressively larger words with the input sets, up to length maxlength.

Do not attempt to produce an in-memory list of 26 characters up to length 10; instead, iterate over the results produced:

for attempt in bruteforce(string.ascii_lowercase, 10):
    # match it against your password, or whatever
    if matched:
        break

jQuery AJAX form data serialize using PHP

<form method="post" name="myForm" id="myForm">

replace with above form tag remove action from form tag. and set url : "check.php" in ajax in your case first it goes to jQuery ajax then submit again the form. that's why it's creating issue.

i know i'm too late for this reply but i think it would help.

Parser Error when deploy ASP.NET application

In my case, There were new code branch and old code branch was deployed locally in IIS. So it was pointing to old branch code that was not available. So i had deployed my code to IIS with new branch and it is working now.

Exception: Serialization of 'Closure' is not allowed

Apparently anonymous functions cannot be serialized.

Example

$function = function () {
    return "ABC";
};
serialize($function); // would throw error

From your code you are using Closure:

$callback = function () // <---------------------- Issue
{
    return 'ZendMail_' . microtime(true) . '.tmp';
};

Solution 1 : Replace with a normal function

Example

function emailCallback() {
    return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;

Solution 2 : Indirect method call by array variable

If you look at http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html

   public function __construct($options = null)
   63     {
   64         if ($options instanceof Zend_Config) {
   65             $options = $options->toArray();
   66         } elseif (!is_array($options)) {
   67             $options = array();
   68         }
   69 
   70         // Making sure we have some defaults to work with
   71         if (!isset($options['path'])) {
   72             $options['path'] = sys_get_temp_dir();
   73         }
   74         if (!isset($options['callback'])) {
   75             $options['callback'] = array($this, 'defaultCallback'); <- here
   76         }
   77 
   78         $this->setOptions($options);
   79     }

You can use the same approach to send the callback

$callback = array($this,"aMethodInYourClass");

How to Join to first row

EDIT: nevermind, Quassnoi has a better answer.

For SQL2K, something like this:

SELECT 
  Orders.OrderNumber
, LineItems.Quantity
, LineItems.Description
FROM (  
  SELECT 
    Orders.OrderID
  , Orders.OrderNumber
  , FirstLineItemID = (
      SELECT TOP 1 LineItemID
      FROM LineItems
      WHERE LineItems.OrderID = Orders.OrderID
      ORDER BY LineItemID -- or whatever else
      )
  FROM Orders
  ) Orders
JOIN LineItems 
  ON LineItems.OrderID = Orders.OrderID 
 AND LineItems.LineItemID = Orders.FirstLineItemID

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Old post, but I'd say the cleanest approach would be to add a class to the surrounding div and a button class on each button so your CSS rule becomes useful for more use cases:

_x000D_
_x000D_
/* Added to highlight spacing */_x000D_
.is-grouped {   _x000D_
    display: inline-block;_x000D_
    background-color: yellow;_x000D_
}_x000D_
_x000D_
.is-grouped > .button:not(:last-child) {_x000D_
    margin-right: 10px;_x000D_
}
_x000D_
Spacing shown in yellow<br><br>_x000D_
_x000D_
<div class='is-grouped'>_x000D_
    <button class='button'>Save</button>_x000D_
    <button class='button'>Save As...</button>_x000D_
    <button class='button'>Delete</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Beautiful way to remove GET-variables with PHP?

Another solution... I find this function more elegant, it will also remove the trailing '?' if the key to remove is the only one in the query string.

/**
 * Remove a query string parameter from an URL.
 *
 * @param string $url
 * @param string $varname
 *
 * @return string
 */
function removeQueryStringParameter($url, $varname)
{
    $parsedUrl = parse_url($url);
    $query = array();

    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $query);
        unset($query[$varname]);
    }

    $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
    $query = !empty($query) ? '?'. http_build_query($query) : '';

    return $parsedUrl['scheme']. '://'. $parsedUrl['host']. $path. $query;
}

Tests:

$urls = array(
    'http://www.example.com?test=test',
    'http://www.example.com?bar=foo&test=test2&foo2=dooh',
    'http://www.example.com',
    'http://www.example.com?foo=bar',
    'http://www.example.com/test/no-empty-path/?foo=bar&test=test5',
    'https://www.example.com/test/test.test?test=test6',
);

foreach ($urls as $url) {
    echo $url. '<br/>';
    echo removeQueryStringParameter($url, 'test'). '<br/><br/>';
}

Will output:

http://www.example.com?test=test
http://www.example.com

http://www.example.com?bar=foo&test=test2&foo2=dooh
http://www.example.com?bar=foo&foo2=dooh

http://www.example.com
http://www.example.com

http://www.example.com?foo=bar
http://www.example.com?foo=bar

http://www.example.com/test/no-empty-path/?foo=bar&test=test5
http://www.example.com/test/no-empty-path/?foo=bar

https://www.example.com/test/test.test?test=test6
https://www.example.com/test/test.test

» Run these tests on 3v4l

How to update Ruby to 1.9.x on Mac?

This command actually works

\curl -L https://get.rvm.io | bash -s stable --ruby

How to import multiple csv files in a single load?

Ex1:

Reading a single CSV file. Provide complete file path:

 val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\tmp\\cars1.csv")

Ex2:

Reading multiple CSV files passing names:

val df=spark.read.option("header","true").csv("C:spark\\sample_data\\tmp\\cars1.csv", "C:spark\\sample_data\\tmp\\cars2.csv")

Ex3:

Reading multiple CSV files passing list of names:

val paths = List("C:spark\\sample_data\\tmp\\cars1.csv", "C:spark\\sample_data\\tmp\\cars2.csv")
val df = spark.read.option("header", "true").csv(paths: _*)

Ex4:

Reading multiple CSV files in a folder ignoring other files:

val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\tmp\\*.csv")

Ex5:

Reading multiple CSV files from multiple folders:

val folders = List("C:spark\\sample_data\\tmp", "C:spark\\sample_data\\tmp1")
val df = spark.read.option("header", "true").csv(folders: _*)

How to check Elasticsearch cluster health?

To check on elasticsearch cluster health you need to use

curl localhost:9200/_cat/health

More on the cat APIs here.

I usually use elasticsearch-head plugin to visualize that.

You can find it's github project here.

It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head and then you can open localhost:9200/_plugin/head/ in your web brower.

You should have something that looks like this :

enter image description here

How to add "required" attribute to mvc razor viewmodel text input editor

I needed the "required" HTML5 atribute, so I did something like this:

<%: Html.TextBoxFor(model => model.Name, new { @required = true })%>

Kotlin - Property initialization using "by lazy" vs. "lateinit"

If you use an unchangable variable, then it is better to initialize with by lazy { ... } or val. In this case you can be sure that it will always be initialized when needed and at most 1 time.

If you want a non-null variable, that can change it's value, use lateinit var. In Android development you can later initialize it in such events like onCreate, onResume. Be aware, that if you call REST request and access this variable, it may lead to an exception UninitializedPropertyAccessException: lateinit property yourVariable has not been initialized, because the request can execute faster than that variable could initialize.

Calculate time difference in Windows batch file

Fixed Gynnad's leading 0 Issue. I fixed it with the two Lines

SET STARTTIME=%STARTTIME: =0%
SET ENDTIME=%ENDTIME: =0%

Full Script ( CalculateTime.cmd ):

@ECHO OFF

:: F U N C T I O N S

:__START_TIME_MEASURE
SET STARTTIME=%TIME%
SET STARTTIME=%STARTTIME: =0%
EXIT /B 0

:__STOP_TIME_MEASURE
SET ENDTIME=%TIME%
SET ENDTIME=%ENDTIME: =0%
SET /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
SET /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
SET /A DURATION=%ENDTIME%-%STARTTIME%
IF %DURATION% == 0 SET TIMEDIFF=00:00:00,00 && EXIT /B 0
IF %ENDTIME% LSS %STARTTIME% SET /A DURATION=%STARTTIME%-%ENDTIME%
SET /A DURATIONH=%DURATION% / 360000
SET /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
SET /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
SET /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)
IF %DURATIONH% LSS 10 SET DURATIONH=0%DURATIONH%
IF %DURATIONM% LSS 10 SET DURATIONM=0%DURATIONM%
IF %DURATIONS% LSS 10 SET DURATIONS=0%DURATIONS%
IF %DURATIONHS% LSS 10 SET DURATIONHS=0%DURATIONHS%
SET TIMEDIFF=%DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%
EXIT /B 0

:: U S A G E

:: Start Measuring
CALL :__START_TIME_MEASURE

:: Print Message on Screen without Linefeed
ECHO|SET /P=Execute Job... 

:: Some Time pending Jobs here
:: '> NUL 2>&1' Dont show any Messages or Errors on Screen
MyJob.exe > NUL 2>&1

:: Stop Measuring
CALL :__STOP_TIME_MEASURE

:: Finish the Message 'Execute Job...' and print measured Time
ECHO [Done] (%TIMEDIFF%)

:: Possible Result
:: Execute Job... [Done] (00:02:12,31)
:: Between 'Execute Job... ' and '[Done] (00:02:12,31)' the Job will be executed

git: fatal: Could not read from remote repository

In your .git/config file

[remote "YOUR_APP_NAME"]
    url = [email protected]:YOUR_APP_NAME.git
    fetch = +refs/heads/*:refs/remotes/YOUR_APP_NAME/*

And simply

git push YOUR_APP_NAME master:master 

return, return None, and no return at all?

They each return the same singleton None -- There is no functional difference.

I think that it is reasonably idiomatic to leave off the return statement unless you need it to break out of the function early (in which case a bare return is more common), or return something other than None. It also makes sense and seems to be idiomatic to write return None when it is in a function that has another path that returns something other than None. Writing return None out explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).

Often in Python, functions which return None are used like void functions in C -- Their purpose is generally to operate on the input arguments in place (unless you're using global data (shudders)). Returning None usually makes it more explicit that the arguments were mutated. This makes it a little more clear why it makes sense to leave off the return statement from a "language conventions" standpoint.

That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

jQuery: How to detect window width on the fly?

I dont know if this useful for you when you resize your page:

$(window).resize(function() {
       if(screen.width == window.innerWidth){
           alert("you are on normal page with 100% zoom");
       } else if(screen.width > window.innerWidth){
           alert("you have zoomed in the page i.e more than 100%");
       } else {
           alert("you have zoomed out i.e less than 100%");
       }
    });

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

Understanding the Rails Authenticity Token

Methods Where authenticity_token is required

authenticity_token is required in case of idempotent methods like post, put and delete, Because Idempotent methods are affecting to data.

Why It is Required

It is required to prevent from evil actions. authenticity_token is stored in session, whenever a form is created on web pages for creating or updating to resources then a authenticity token is stored in hidden field and it sent with form on server. Before executing action user sent authenticity_token is cross checked with authenticity_token stored in session. If authenticity_token is same then process is continue otherwise it does not perform actions.

Singleton: How should it be used

Below is the better approach for implementing a thread safe singleton pattern with deallocating the memory in destructor itself. But I think the destructor should be an optional because singleton instance will be automatically destroyed when the program terminates:

#include<iostream>
#include<mutex>

using namespace std;
std::mutex mtx;

class MySingleton{
private:
    static MySingleton * singletonInstance;
    MySingleton();
    ~MySingleton();
public:
    static MySingleton* GetInstance();
    MySingleton(const MySingleton&) = delete;
    const MySingleton& operator=(const MySingleton&) = delete;
    MySingleton(MySingleton&& other) noexcept = delete;
    MySingleton& operator=(MySingleton&& other) noexcept = delete;
};

MySingleton* MySingleton::singletonInstance = nullptr;
MySingleton::MySingleton(){ };
MySingleton::~MySingleton(){
    delete singletonInstance;
};

MySingleton* MySingleton::GetInstance(){
    if (singletonInstance == NULL){
        std::lock_guard<std::mutex> lock(mtx);
        if (singletonInstance == NULL)
            singletonInstance = new MySingleton();
    }
    return singletonInstance;
}

Regarding the situations where we need to use singleton classes can be- If we want to maintain the state of the instance throughout the execution of the program If we are involved in writing into execution log of an application where only one instance of the file need to be used....and so on. It will be appreciable if anybody can suggest optimisation in my above code.

Adding a default value in dropdownlist after binding with database

You can add it programmatically or in the markup, but if you add it programmatically, rather than Add the item, you should Insert it as position zero so that it is the first item:

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");

The default item is expected to be the first item in the list. If you just Add it, it will be on the bottom and will not be selected by default.

How to clear basic authentication details in chrome

I'm using Chrome 75. What I've found is that restarting Chrome doesn't work. But restarting Chrome AND opening the developer tools does work. I don't have any explanation why this should be.

How to discard uncommitted changes in SourceTree?

On the unstaged file, click on the three dots on the right side. Once you click it, a popover menu will appear where you can then Discard file.

Redis command to get all available keys?

KEYS pattern

Available since 1.0.0.

Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.

Returns all keys matching pattern.

Warning : This command is not recommended to use because it may ruin performance when it is executed against large databases instead of KEYS you can use SCAN or SETS.

Example of KEYS command to use :

redis> MSET firstname Jack lastname Stuntman age 35
"OK"
redis> KEYS *name*
1) "lastname"
2) "firstname"
redis> KEYS a??
1) "age"
redis> KEYS *
1) "lastname"
2) "age"
3) "firstname"

How to change background Opacity when bootstrap modal is open

What worked for me, I clear the opacity in .modal.backdrop.in

.modal-backdrop.in{
    filter:alpha(opacity=50);
    opacity:.5
    }

change it to

.modal-backdrop.in{
   }

How do I remove the height style from a DIV using jQuery?

$('div#someDiv').removeAttr("height");

Android Studio - Importing external Library/Jar

So,

Steps to follow in order to import a JAR sucesfully to your project using Android Studio 0.1.1:

  • Download the library.jar file and copy it to your /libs/ folder inside your application project.
  • Open the build.gradle file and edit your dependencies to include the new .jar file:

compile files('libs/android-support-v4.jar', 'libs/GoogleAdMobAdsSdk-6.4.1.jar')

  • File -> Close Project
  • Open a command prompt on your project's root location, i.e 'C:\Users\Username\AndroidStudioProjects\MyApplicationProject\'
  • On the command prompt, type gradlew clean, wait till it's done.
  • Reopen your application project in Android Studio.
  • Test run your application and it should work succesfully.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.

Here's some sample code:

#import <MediaPlayer/MediaPlayer.h>

@interface ViewController () {
    MPMoviePlayerController *moviePlayerController;
}

@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Instantiate a movie player controller and add it to your view
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];    
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    [moviePlayerController.view setFrame:self.movieView.bounds];  // player's frame must match parent's
    [self.movieView addSubview:moviePlayerController.view];

    // Configure the movie player controller
    moviePlayerController.controlStyle = MPMovieControlStyleNone;        
    [moviePlayerController prepareToPlay];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Start the movie
    [moviePlayerController play];
}

@end

Automate scp file transfer using a shell script

why don't you try this?

password="your password"
username="username"
Ip="<IP>"
sshpass -p "$password" scp /<PATH>/final.txt $username@$Ip:/root/<PATH>

How to get the first element of the List or Set?

I'm surprised that nobody suggested guava solution yet:

com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)

or if you expect single element:

com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)

JAVA_HOME does not point to the JDK

It looks like you are currently pointing JAVA_HOME to /usr/lib/jvm/java-6-openjdk/jre which appears to be a JRE not a JDK. Try setting JAVA_HOME to /usr/lib/jvm/java-6-openjdk.

The JRE does not contain the Java compiler, only the JDK (Java Developer Kit) contains it.

The type is defined in an assembly that is not referenced, how to find the cause?

For me, this was caused by the project both directly and indirectly (through another dependency) referencing two different builds of Bouncy Castle that had different assembly names. One of the Bouncy Castle builds was the NuGet package, the other one was a debug build of the source downloaded from GitHub. Both were nominally version 1.8.1, but the project settings of the GitHub code set the assembly name to BouncyCastle whereas the NuGet package had the assembly name BouncyCastle.Crypto. Changing the project settings, thus aligning the assembly names, fixed the problem.

Object creation on the stack/heap?

C++ offers three different ways to create objects:

  1. Stack-based such as temporary objects
  2. Heap-based by using new
  3. Static memory allocation such as global variables and namespace-scope objects

Consider your case,

Object* o;
o = new Object();

and:

Object* o = new Object();

Both forms are the same. This means that a pointer variable o is created on the stack (assume your variables does not belong to the 3 category above) and it points to a memory in the heap, which contains the object.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

I just checked with www.browserscope.org and with IE9 and Chrome 24 you can have 6 concurrent connections to a single domain, and up to 17 to multiple ones.

Declare and Initialize String Array in VBA

In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:

Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")

This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.

Converting a float to a string without rounding it

Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.

Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:

http://docs.python.org/library/decimal.html

Among other things you can explicitly specify the precision that you wish to obtain (from the docs):

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

A simple example from my prompt (python 2.6):

>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29

Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.

Hope this helps, Francesco

Event when window.location.href changes

Well there is 2 ways to change the location.href. Either you can write location.href = "y.html", which reloads the page or can use the history API which does not reload the page. I experimented with the first a lot recently.

If you open a child window and capture the load of the child page from the parent window, then different browsers behave very differently. The only thing that is common, that they remove the old document and add a new one, so for example adding readystatechange or load event handlers to the old document does not have any effect. Most of the browsers remove the event handlers from the window object too, the only exception is Firefox. In Chrome with Karma runner and in Firefox you can capture the new document in the loading readyState if you use unload + next tick. So you can add for example a load event handler or a readystatechange event handler or just log that the browser is loading a page with a new URI. In Chrome with manual testing (probably GreaseMonkey too) and in Opera, PhantomJS, IE10, IE11 you cannot capture the new document in the loading state. In those browsers the unload + next tick calls the callback a few hundred msecs later than the load event of the page fires. The delay is typically 100 to 300 msecs, but opera simetime makes a 750 msec delay for next tick, which is scary. So if you want a consistent result in all browsers, then you do what you want to after the load event, but there is no guarantee the location won't be overridden before that.

var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");


var callBacks = [];
var uglyHax = function (){
    var done = function (){
        uglyHax();
        callBacks.forEach(function (cb){
            cb();
        });
    };
    win.addEventListener("unload", function unloadListener(){
        win.removeEventListener("unload", unloadListener); // Firefox remembers, other browsers don't
        setTimeout(function (){
            // IE10, IE11, Opera, PhantomJS, Chrome has a complete new document at this point
            // Chrome on Karma, Firefox has a loading new document at this point
            win.document.readyState; // IE10 and IE11 sometimes fails if I don't access it twice, idk. how or why
            if (win.document.readyState === "complete")
                done();
            else
                win.addEventListener("load", function (){
                    setTimeout(done, 0);
                });
        }, 0);
    });
};
uglyHax();


callBacks.push(function (){
    console.log("cb", win.location.href, win.document.readyState);
    if (win.location.href !== "http://localhost:4444/y.html")
        win.location.href = "http://localhost:4444/y.html";
    else
        console.log("done");
});
win.location.href = "http://localhost:4444/x.html";

If you run your script only in Firefox, then you can use a simplified version and capture the document in a loading state, so for example a script on the loaded page cannot navigate away before you log the URI change:

var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");


var callBacks = [];
win.addEventListener("unload", function unloadListener(){
    setTimeout(function (){
        callBacks.forEach(function (cb){
            cb();
        });
    }, 0);
});


callBacks.push(function (){
    console.log("cb", win.location.href, win.document.readyState);
    // be aware that the page is in loading readyState, 
    // so if you rewrite the location here, the actual page will be never loaded, just the new one
    if (win.location.href !== "http://localhost:4444/y.html")
        win.location.href = "http://localhost:4444/y.html";
    else
        console.log("done");
});
win.location.href = "http://localhost:4444/x.html";

If we are talking about single page applications which change the hash part of the URI, or use the history API, then you can use the hashchange and the popstate events of the window respectively. Those can capture even if you move in history back and forward until you stay on the same page. The document does not changes by those and the page is not really reloaded.

JWT (JSON Web Token) automatic prolongation of expiration

An alternative solution for invalidating JWTs, without any additional secure storage on the backend, is to implement a new jwt_version integer column on the users table. If the user wishes to log out or expire existing tokens, they simply increment the jwt_version field.

When generating a new JWT, encode the jwt_version into the JWT payload, optionally incrementing the value beforehand if the new JWT should replace all others.

When validating the JWT, the jwt_version field is compared alongside the user_id and authorisation is granted only if it matches.

How to redirect all HTTP requests to HTTPS

Do everything that is explained above for redirection. Just add "HTTP Strict Transport Security" to your header. This will avoid man in the middle attack.

Edit your apache configuration file (/etc/apache2/sites-enabled/website.conf and /etc/apache2/httpd.conf for example) and add the following to your VirtualHost:

# Optionally load the headers module:
LoadModule headers_module modules/mod_headers.so

<VirtualHost 67.89.123.45:443>
    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
</VirtualHost>

https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

setting min date in jquery datepicker

basically if you already specify the year range there is no need to use mindate and maxdate if only year is required

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Comparing two vectors in an if statement

all is one option:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

But you may have to watch out for recycling:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

The documentation for length says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all.

Remove the last character from a string

You can use substr:

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'

How to declare a global variable in C++

You declare the variable as extern in a common header:

//globals.h
extern int x;

And define it in an implementation file.

//globals.cpp
int x = 1337;

You can then include the header everywhere you need access to it.

I suggest you also wrap the variable inside a namespace.

JWT refresh token flow

Below are the steps to do revoke your JWT access token:

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
  5. Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
  6. Once the refresh token is expired, the User will be logged out.

Please let me know if you need more details, I can share the code (Java + Spring boot) as well.

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

How to set background color of HTML element using css properties in JavaScript

Javascript:

document.getElementById("ID").style.background = "colorName"; //JS ID

document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class

Jquery:

$('#ID/.className').css("background","colorName") // One style

$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style

How to convert enum names to string in c

I found a C preprocessor trick that is doing the same job without declaring a dedicated array string (Source: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/c_preprocessor_applications_en).

Sequential enums

Following the invention of Stefan Ram, sequential enums (without explicitely stating the index, e.g. enum {foo=-1, foo1 = 1}) can be realized like this genius trick:

#include <stdio.h>

#define NAMES C(RED)C(GREEN)C(BLUE)
#define C(x) x,
enum color { NAMES TOP };
#undef C

#define C(x) #x,    
const char * const color_name[] = { NAMES };

This gives the following result:

int main( void )  { 
    printf( "The color is %s.\n", color_name[ RED ]);  
    printf( "There are %d colors.\n", TOP ); 
}

The color is RED.
There are 3 colors.

Non-Sequential enums

Since I wanted to map error codes definitions to are array string, so that I can append the raw error definition to the error code (e.g. "The error is 3 (LC_FT_DEVICE_NOT_OPENED)."), I extended the code in that way that you can easily determine the required index for the respective enum values:

#define LOOPN(n,a) LOOP##n(a)
#define LOOPF ,
#define LOOP2(a) a LOOPF a LOOPF
#define LOOP3(a) a LOOPF a LOOPF a LOOPF
#define LOOP4(a) a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP5(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP6(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP7(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP8(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP9(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF


#define LC_ERRORS_NAMES \
    Cn(LC_RESPONSE_PLUGIN_OK, -10) \
    Cw(8) \
    Cn(LC_RESPONSE_GENERIC_ERROR, -1) \
    Cn(LC_FT_OK, 0) \
    Ci(LC_FT_INVALID_HANDLE) \
    Ci(LC_FT_DEVICE_NOT_FOUND) \
    Ci(LC_FT_DEVICE_NOT_OPENED) \
    Ci(LC_FT_IO_ERROR) \
    Ci(LC_FT_INSUFFICIENT_RESOURCES) \
    Ci(LC_FT_INVALID_PARAMETER) \
    Ci(LC_FT_INVALID_BAUD_RATE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_ERASE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_WRITE) \
    Ci(LC_FT_FAILED_TO_WRITE_DEVICE) \
    Ci(LC_FT_EEPROM_READ_FAILED) \
    Ci(LC_FT_EEPROM_WRITE_FAILED) \
    Ci(LC_FT_EEPROM_ERASE_FAILED) \
    Ci(LC_FT_EEPROM_NOT_PRESENT) \
    Ci(LC_FT_EEPROM_NOT_PROGRAMMED) \
    Ci(LC_FT_INVALID_ARGS) \
    Ci(LC_FT_NOT_SUPPORTED) \
    Ci(LC_FT_OTHER_ERROR) \
    Ci(LC_FT_DEVICE_LIST_NOT_READY)


#define Cn(x,y) x=y,
#define Ci(x) x,
#define Cw(x)
enum LC_errors { LC_ERRORS_NAMES TOP };
#undef Cn
#undef Ci
#undef Cw
#define Cn(x,y) #x,
#define Ci(x) #x,
#define Cw(x) LOOPN(x,"")
static const char* __LC_errors__strings[] = { LC_ERRORS_NAMES };
static const char** LC_errors__strings = &__LC_errors__strings[10];

In this example, the C preprocessor will generate the following code:

enum LC_errors { LC_RESPONSE_PLUGIN_OK=-10,  LC_RESPONSE_GENERIC_ERROR=-1, LC_FT_OK=0, LC_FT_INVALID_HANDLE, LC_FT_DEVICE_NOT_FOUND, LC_FT_DEVICE_NOT_OPENED, LC_FT_IO_ERROR, LC_FT_INSUFFICIENT_RESOURCES, LC_FT_INVALID_PARAMETER, LC_FT_INVALID_BAUD_RATE, LC_FT_DEVICE_NOT_OPENED_FOR_ERASE, LC_FT_DEVICE_NOT_OPENED_FOR_WRITE, LC_FT_FAILED_TO_WRITE_DEVICE, LC_FT_EEPROM_READ_FAILED, LC_FT_EEPROM_WRITE_FAILED, LC_FT_EEPROM_ERASE_FAILED, LC_FT_EEPROM_NOT_PRESENT, LC_FT_EEPROM_NOT_PROGRAMMED, LC_FT_INVALID_ARGS, LC_FT_NOT_SUPPORTED, LC_FT_OTHER_ERROR, LC_FT_DEVICE_LIST_NOT_READY, TOP };

static const char* __LC_errors__strings[] = { "LC_RESPONSE_PLUGIN_OK", "" , "" , "" , "" , "" , "" , "" , "" "LC_RESPONSE_GENERIC_ERROR", "LC_FT_OK", "LC_FT_INVALID_HANDLE", "LC_FT_DEVICE_NOT_FOUND", "LC_FT_DEVICE_NOT_OPENED", "LC_FT_IO_ERROR", "LC_FT_INSUFFICIENT_RESOURCES", "LC_FT_INVALID_PARAMETER", "LC_FT_INVALID_BAUD_RATE", "LC_FT_DEVICE_NOT_OPENED_FOR_ERASE", "LC_FT_DEVICE_NOT_OPENED_FOR_WRITE", "LC_FT_FAILED_TO_WRITE_DEVICE", "LC_FT_EEPROM_READ_FAILED", "LC_FT_EEPROM_WRITE_FAILED", "LC_FT_EEPROM_ERASE_FAILED", "LC_FT_EEPROM_NOT_PRESENT", "LC_FT_EEPROM_NOT_PROGRAMMED", "LC_FT_INVALID_ARGS", "LC_FT_NOT_SUPPORTED", "LC_FT_OTHER_ERROR", "LC_FT_DEVICE_LIST_NOT_READY", };

This results to the following implementation capabilities:

LC_errors__strings[-1] ==> LC_errors__strings[LC_RESPONSE_GENERIC_ERROR] ==> "LC_RESPONSE_GENERIC_ERROR"

Parse strings to double with comma and point

You can check if the string contains a decimal point using

string s="";

        if (s.Contains(','))
        { 
        //treat as double how you wish
        }

and then treat that as a decimal, otherwise just pass the non-double value along.

How to remove class from all elements jquery

This just removes the highlight class from everything that has the edgetoedge class:

$(".edgetoedge").removeClass("highlight");

I think you want this:

$(".edgetoedge .highlight").removeClass("highlight");

The .edgetoedge .highlight selector will choose everything that is a child of something with the edgetoedge class and has the highlight class.

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

Regex match one of two words

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)

How do you convert an entire directory with ffmpeg?

little php script to do it:

#!/usr/bin/env php
<?php
declare(strict_types = 1);
if ($argc !== 2) {
    fprintf ( STDERR, "usage: %s dir\n", $argv [0] );
    die ( 1 );
}
$dir = rtrim ( $argv [1], DIRECTORY_SEPARATOR );
if (! is_readable ( $dir )) {
    fprintf ( STDERR, "supplied path is not readable! (try running as an administrator?)" );
    die(1);
}
if (! is_dir ( $dir )) {
    fprintf ( STDERR, "supplied path is not a directory!" );
    die(1);
}
$files = glob ( $dir . DIRECTORY_SEPARATOR . '*.avi' );
foreach ( $files as $file ) {
    system ( "ffmpeg -i " . escapeshellarg ( $file ) . ' ' . escapeshellarg ( $file . '.mp4' ) );
}

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Booting from CD to rescue the installation and editing /etc/selinux/config: changed SELINUX from enforcing to permissive. Rebooted and system booted

/etc/selinux/config before change:

SELINUX=enforcing and SELINUXTYPE=permissive

/etc/selinux/config after change: SELINUX=permissive and SELINUXTYPE=permissive

Null check in an enhanced for loop

Use ArrayUtils.nullToEmpty from the commons-lang library for Arrays

for( Object o : ArrayUtils.nullToEmpty(list) ) {
   // do whatever 
}

This functionality exists in the commons-lang library, which is included in most Java projects.

// ArrayUtils.nullToEmpty source code 
public static Object[] nullToEmpty(final Object[] array) {
    if (isEmpty(array)) {
        return EMPTY_OBJECT_ARRAY;
    }
    return array;
}

// ArrayUtils.isEmpty source code
public static boolean isEmpty(final Object[] array) {
    return array == null || array.length == 0;
}

This is the same as the answer given by @OscarRyz, but for the sake of the DRY mantra, I believe it is worth noting. See the commons-lang project page. Here is the nullToEmpty API documentation and source

Maven entry to include commons-lang in your project if it is not already.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

Unfortunately, commons-lang doesn't provide this functionality for List types. In this case you would have to use a helper method as previously mentioned.

public static <E> List<E> nullToEmpty(List<E> list)
{
    if(list == null || list.isEmpty())
    {
        return Collections.emptyList();
    }
    return list;
}

Adding images or videos to iPhone Simulator

I just needed some random images for testing, so this is how I did it.

I have the simplest solution in the world. Just open Safari in the simulator, go to Google images (or your own web or Dropbox URL), view an image, hold down the mouse button for 2 seconds, and you'll see "Save Image" - it will save right into the Photos library. Rinse and repeat.