Programs & Examples On #Cs193p

CS193P is an iOS programming course offered at Stanford University. The latest Fall 2017 session videos, lecture slides and assignments are available on iTunes U, and have become a popular way of learning to program for the platform. Sample code that is provided in class is available from http://cs193p.stanford.edu/

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

What happened with me was the Type of class was not UIViewController for the script attached to my view controller. It was for a UITabController..... I had mistakenly quickly created the wrong type of class.... So make sure the class if the correct type.. Hope this helps someone. I was in a rush and made this mistake.

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

EditText request focus

Programatically:

edittext.requestFocus();

Through xml:

<EditText...>
    <requestFocus />
</EditText>

Or call onClick method manually.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Others here have suggested a couple multi-record syntaxes. Expounding upon that, I suggest you insert into a temp table first, and insert your main table from there.

The reason for this is loading the data from a query can take longer, and you may end up locking the table or pages longer than is necessary, which slows down other queries running against that table.

-- Make a temp table with the needed columns
select top 0 *
into #temp
from MyTable (nolock)

-- load data into it at your leisure (nobody else is waiting for this table or these pages)
insert #temp (ID, Name)
values (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')

-- Now that all the data is in SQL, copy it over to the real table. This runs much faster in most cases.
insert MyTable (ID, Name)
select ID, Name
from #temp

-- cleanup
drop table #temp

Also, your IDs should probably be identity(1,1) and you probably shouldn't be inserting them, in the vast majority of circumstances. Let SQL decide that stuff for you.

Java replace all square brackets in a string

use regex [\\[\\]] -

String str = "[Chrissman-@1]";
String[] temp = str.replaceAll("[\\[\\]]", "").split("-@");
System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]);

output -

Nickname: Chrissman | Power: 1

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

Changing the browser zoom level

I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:

<!-- Trigger -->
<ul id="zoom_triggers">
    <li><a id="zoom_in">zoom in</a></li>
    <li><a id="zoom_out">zoom out</a></li>
    <li><a id="zoom_reset">reset zoom</a></li>
</ul>

<script>
    jQuery(document).ready(function($)
    {
        // Set initial zoom level
        var zoom_level=100;

        // Click events
        $('#zoom_in').click(function() { zoom_page(10, $(this)) });
        $('#zoom_out').click(function() { zoom_page(-10, $(this)) });
        $('#zoom_reset').click(function() { zoom_page(0, $(this)) });

        // Zoom function
        function zoom_page(step, trigger)
        {
            // Zoom just to steps in or out
            if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;

            // Set / reset zoom
            if(step==0) zoom_level=100;
            else zoom_level=zoom_level+step;

            // Set page zoom via CSS
            $('body').css({
                transform: 'scale('+(zoom_level/100)+')', // set zoom
                transformOrigin: '50% 0' // set transform scale base
            });

            // Adjust page to zoom width
            if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
            else $('body').css({ width: '100%' });

            // Activate / deaktivate trigger (use CSS to make them look different)
            if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
            else trigger.parents('ul').find('.disabled').removeClass('disabled');
            if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
            else $('#zoom_reset').addClass('disabled');
        }
    });
</script>

Get property value from string using reflection

The method to call has changed in .NET Standard (as of 1.6). Also we can use C# 6's null conditional operator.

using System.Reflection; 
public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetRuntimeProperty(propName)?.GetValue(src);
}

HTML input textbox with a width of 100% overflows table cells

I solved the problem by applying box-sizing:border-box; to the table cells themselves, besides doing the same with the input and the wrapper.

Difference between Destroy and Delete

When you invoke destroy or destroy_all on an ActiveRecord object, the ActiveRecord 'destruction' process is initiated, it analyzes the class you're deleting, it determines what it should do for dependencies, runs through validations, etc.

When you invoke delete or delete_all on an object, ActiveRecord merely tries to run the DELETE FROM tablename WHERE conditions query against the db, performing no other ActiveRecord-level tasks.

MySQL - Rows to Columns

If you could use MariaDB there is a very very easy solution.

Since MariaDB-10.02 there has been added a new storage engine called CONNECT that can help us to convert the results of another query or table into a pivot table, just like what you want: You can have a look at the docs.

First of all install the connect storage engine.

Now the pivot column of our table is itemname and the data for each item is located in itemvalue column, so we can have the result pivot table using this query:

create table pivot_table
engine=connect table_type=pivot tabname=history
option_list='PivotCol=itemname,FncCol=itemvalue';

Now we can select what we want from the pivot_table:

select * from pivot_table

More details here

Set Icon Image in Java

Use Default toolkit for this

frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));

add onclick function to a submit button

<button type="submit" name="uname" value="uname" onclick="browserlink(ex.google.com,home.html etc)or myfunction();"> submit</button>

if you want to open a page on the click of a button in HTML without any scripting language then you can use above code.

Multiple types were found that match the controller named 'Home'

There might be another case with Areas even you have followed all steps in routing in Areas(like giving Namespaces in global routing table), which is:

You might not have wrapped your Global Controller(s) in 'namespace' you provided in routing.

Eg:

Done this:

public class HomeController : Controller
{

Instead of:

namespace GivenNamespace.Controllers
{
   public class HomeController : Controller
   {

Paramiko's SSHClient with SFTP

paramiko.SFTPClient

Sample Usage:

import paramiko
paramiko.util.log_to_file("paramiko.log")

# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))

# Auth    
username,password = "bar","foo"
transport.connect(None,username,password)

# Go!    
sftp = paramiko.SFTPClient.from_transport(transport)

# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)

# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)

# Close
if sftp: sftp.close()
if transport: transport.close()

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Convert seconds value to hours minutes seconds?

I know this is pretty old but in java 8:

LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)

Is a GUID unique 100% of the time?

The simple answer is yes.

Raymond Chen wrote a great article on GUIDs and why substrings of GUIDs are not guaranteed unique. The article goes in to some depth as to the way GUIDs are generated and the data they use to ensure uniqueness, which should go to some length in explaining why they are :-)

Error: Cannot find module 'webpack'

Run below commands in Terminal:

npm install --save-dev webpack

npm install --save-dev webpack-dev-server

How do I set the proxy to be used by the JVM

reading an XML file and needs to download its schema

If you are counting on retrieving schemas or DTDs over the internet, you're building a slow, chatty, fragile application. What happens when that remote server hosting the file takes planned or unplanned downtime? Your app breaks. Is that OK?

See http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.files

URL's for schemas and the like are best thought of as unique identifiers. Not as requests to actually access that file remotely. Do some google searching on "XML catalog". An XML catalog allows you to host such resources locally, resolving the slowness, chattiness and fragility.

It's basically a permanently cached copy of the remote content. And that's OK, since the remote content will never change. If there's ever an update, it'd be at a different URL. Making the actual retrieval of the resource over the internet especially silly.

Uint8Array to string in Javascript

I am using this Typescript snippet:

function UInt8ArrayToString(uInt8Array: Uint8Array): string
{
    var s: string = "[";
    for(var i: number = 0; i < uInt8Array.byteLength; i++)
    {
        if( i > 0 )
            s += ", ";
        s += uInt8Array[i];
    }
    s += "]";
    return s;
}

Remove the type annotations if you need the JavaScript version. Hope this helps!

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Correct way to use Modernizr to detect IE?

CSS tricks have a good solution to target IE 11:

http://css-tricks.com/ie-10-specific-styles/

The .NET and Trident/7.0 are unique to IE so can be used to detect IE version 11.

The code then adds the User Agent string to the html tag with the attribute 'data-useragent', so IE 11 can be targeted specifically...

How do you remove columns from a data.frame?

Just addressing the edit.

@nzcoops, you do not need the column names in a comma delimited character vector. You are thinking about this the wrong way round. When you do

vec <- c("col1", "col2", "col3")

you are creating a character vector. The , just separates arguments taken by the c() function when you define that vector. names() and similar functions return a character vector of names.

> dat <- data.frame(col1 = 1:3, col2 = 1:3, col3 = 1:3)
> dat
  col1 col2 col3
1    1    1    1
2    2    2    2
3    3    3    3
> names(dat)
[1] "col1" "col2" "col3"

It is far easier and less error prone to select from the elements of names(dat) than to process its output to a comma separated string you can cut and paste from.

Say we want columns col1 and col2, subset names(dat), retaining only the ones we want:

> names(dat)[c(1,3)]
[1] "col1" "col3"
> dat[, names(dat)[c(1,3)]]
  col1 col3
1    1    1
2    2    2
3    3    3

You can kind of do what you want, but R will always print the vector the screen in quotes ":

> paste('"', names(dat), '"', sep = "", collapse = ", ")
[1] "\"col1\", \"col2\", \"col3\""
> paste("'", names(dat), "'", sep = "", collapse = ", ")
[1] "'col1', 'col2', 'col3'"

so the latter may be more useful. However, now you have to cut and past from that string. Far better to work with objects that return what you want and use standard subsetting routines to keep what you need.

How to display two digits after decimal point in SQL Server

select cast(your_float_column as decimal(10,2))
from your_table

decimal(10,2) means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Activity class is the basic class. (The original) It supports Fragment management (Since API 11). Is not recommended anymore its pure use because its specializations are far better.

ActionBarActivity was in a moment the replacement to the Activity class because it made easy to handle the ActionBar in an app.

AppCompatActivity is the new way to go because the ActionBar is not encouraged anymore and you should use Toolbar instead (that's currently the ActionBar replacement). AppCompatActivity inherits from FragmentActivity so if you need to handle Fragments you can (via the Fragment Manager). AppCompatActivity is for ANY API, not only 16+ (who said that?). You can use it by adding compile 'com.android.support:appcompat-v7:24:2.0' in your Gradle file. I use it in API 10 and it works perfect.

password-check directive in angularjs

The following is my take on the problem. This directive would compare against a form value instead of the scope.

'use strict';
(function () {
    angular.module('....').directive('equals', function ($timeout) {
        return {
            restrict: 'A',
            require: ['^form', 'ngModel'],
            scope: false,
            link: function ($scope, elem, attrs, controllers) {
                var validationKey = 'equals';
                var form = controllers[0];
                var ngModel = controllers[1];

                if (!ngModel) {
                    return;
                }

                //run after view has rendered
                $timeout(function(){
                    $scope.$watch(attrs.ngModel, validate);

                    $scope.$watch(form[attrs.equals], validate);
                }, 0);

                var validate = function () {
                    var value1 = ngModel.$viewValue;
                    var value2 = form[attrs.equals].$viewValue;
                    var validity = !value1 || !value2 || value1 === value2;
                    ngModel.$setValidity(validationKey, validity);
                    form[attrs.equals].$setValidity(validationKey,validity);
                };
            }
        };
    });
})();

in the HTML one now refers to the actual form instead of the scoped value:

<form name="myForm">
  <input type="text" name="value1" equals="value2">
  <input type="text" name="value2" equals="value1">
  <div ng-show="myForm.$invalid">The form is invalid!</div>
</form>

Python popen command. Wait until the command is finished

You can you use subprocess to achieve this.

import subprocess

#This command could have multiple commands separated by a new line \n
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt"

p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True)

(output, err) = p.communicate()  

#This makes the wait possible
p_status = p.wait()

#This will give you the output of the command being executed
print "Command output: " + output

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Generally This exception is thrown from Oracle when query result (which is stored in an Object in your case), can not be cast to the desired object. for example when result is a

List<T>

and you're putting the result into a single T object.

In case of casting to long error, besides it is recommended to use wrapper classes so that all of your columns act the same, I guess a problem in transaction or query itself would cause this issue.

Comparing two java.util.Dates to see if they are in the same day

private boolean isSameDay(Date date1, Date date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);
        boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
        boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
        boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
        return (sameDay && sameMonth && sameYear);
    }

How to change Angular CLI favicon

I was playing around with this for a little while. Turns out that the favicon is apparently handled by a node module called @scematics (at least in Angular5).

You can change your favicon in this folder:

[YourProjectName]\node_modules\@schematics\angular\application\files\__sourcedir__

In that folder there should be a favicon.ico, that's the one that is loaded. Im pretty shure this doesnt apply to everyone but it worked out for me.

Hope this helped. Happy coding! :D

assign value using linq

using Linq would be:

 listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";

UPDATE

This can be simplified to be...

 listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";

UPDATE

For multiple items (condition is met by multiple items):

 listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");

Get values from label using jQuery

var label = $('#current_month');
var month = label.val('month');
var year = label.val('year');
var text = label.text();
alert(text);

<label year="2010" month="6" id="current_month"> June &nbsp;2010</label>

fork: retry: Resource temporarily unavailable

This is commonly caused by running out of file descriptors.

There is the systems total file descriptor limit, what do you get from the command:

sysctl fs.file-nr

This returns counts of file descriptors:

<in_use> <unused_but_allocated> <maximum>

To find out what a users file descriptor limit is run the commands:

sudo su - <username>
ulimit -Hn

To find out how many file descriptors are in use by a user run the command:

sudo lsof -u <username> 2>/dev/null | wc -l

So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.

fs.file-max = 204708

Can git undo a checkout of unstaged files

If you work with a terminal/cmd prompt open, and used any git commands that would have showed the unstaged changes (diff, add -p, checkout -p, etc.), and haven't closed the terminal/cmd prompt since, you'll find the unstaged changes are still available if you scroll up to where you ran those aforementioned git commands.

How to draw polygons on an HTML5 canvas?

Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.

Here is a full article on how it works and more.

// Defines a path for any regular polygon with the specified number of sides and radius, 
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
  if (sides < 3) return;
  var a = (Math.PI * 2)/sides;
  a = anticlockwise?-a:a;
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(startAngle);
  ctx.moveTo(radius,0);
  for (var i = 1; i < sides; i++) {
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
  }
  ctx.closePath();
  ctx.restore();
}

// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();

How do I find out my root MySQL password?

MySQL 5.5 on Ubuntu 14.04 required slightly different commands as recommended here. In a nutshell:

sudo /etc/init.d/mysql stop
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root

And then from the MySQL prompt

FLUSH PRIVILEGES;
SET PASSWORD FOR root@'localhost' = PASSWORD('password');
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;

And the cited source offers an alternate method as well.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How to get form values in Symfony2 controller

None of the above worked for me. This works for me:

$username = $form["username"]->getData();
$password = $form["password"]->getData();

I hope it helps.

How to convert Strings to and from UTF8 byte arrays in Java

String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");

Finding element's position relative to the document

If you don't mind using jQuery, then you can use offset() function. Refer to documentation if you want to read up more about this function.

How can I map True/False to 1/0 in a Pandas DataFrame?

Just multiply your Dataframe by 1 (int)

[1]: data = pd.DataFrame([[True, False, True], [False, False, True]])
[2]: print data
          0      1     2
     0   True  False  True
     1   False False  True

[3]: print data*1
         0  1  2
     0   1  0  1
     1   0  0  1

React JS onClick event handler

Use ECMA2015. Arrow functions make "this" a lot more intuitive.

import React from 'react';


class TestApp extends React.Component {
   getComponent(e, index) {
       $(e.target).css({
           'background-color': '#ccc'
       });
   }
   render() {
       return (
           <div>
             <ul>
               <li onClick={(e) => this.getComponent(e, 1)}>Component 1</li>
               <li onClick={(e) => this.getComponent(e, 2)}>Component 2</li>
               <li onClick={(e) => this.getComponent(e, 3)}>Component 3</li>
             </ul>
           </div>
       );
   }
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));`

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

Remove Blank option from Select Option with AngularJS

Also check whether you have any falsy value or not. Angularjs will insert an empty option if you do have falsy value. I struggled for 2 days just due to falsy value. I hope it will be helpful for someone.

I had options as [0, 1] and initially I was set the model to 0 due to that it was inserted empty option. Workaround for this was ["0" , "1"].

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

JavaScript set object key by variable

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var key = "name";_x000D_
    var person = {[key]:"John"};_x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var person = {};_x000D_
    var key = "name";_x000D_
    _x000D_
    person[key] /* this is same as person.name */ = "John";_x000D_
    _x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

angular ng-repeat in reverse

I found something like this, but instead of array i use objects.

Here is my solution for objects:

Add custom filter:

app.filter('orderObjectBy', function() {
    return function(items, field, reverse){

        var strRef = function (object, reference) {
            function arr_deref(o, ref, i) {
                return !ref ? o : (o[ref.slice(0, i ? -1 : ref.length)]);
            }
            function dot_deref(o, ref) {
                return !ref ? o : ref.split('[').reduce(arr_deref, o);
            }
            return reference.split('.').reduce(dot_deref, object);
        };

        var filtered = [];

        angular.forEach(items, function(item) {
           filtered.push(item);
        });
        filtered.sort(function (a, b) {
           return (strRef(a, field) > strRef(a, field) ? 1 : -1);
        });
        if(reverse) filtered.reverse();
        return filtered;
    };
});

Which can then be used like

<div ng-repeat="(key, value) in items | orderObjectBy:'field.any.deep':true">

If you need old browser support, you will need to define the reduce function (this is only available in ECMA-262 mozilla.org)

// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback /*, initialValue*/) {
'use strict';
  if (this == null) {
    throw new TypeError('Array.prototype.reduce called on null or undefined');
  }
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function');
  }
  var t = Object(this), len = t.length >>> 0, k = 0, value;
  if (arguments.length == 2) {
    value = arguments[1];
  } else {
    while (k < len && !(k in t)) {
      k++; 
    }
    if (k >= len) {
      throw new TypeError('Reduce of empty array with no initial value');
    }
    value = t[k++];
  }
  for (; k < len; k++) {
    if (k in t) {
      value = callback(value, t[k], k, t);
    }
  }
  return value;
};
}

Need to find a max of three numbers in java

You should know more about java.lang.Math.max:

  1. java.lang.Math.max(arg1,arg2) only accepts 2 arguments but you are writing 3 arguments in your code.
  2. The 2 arguments should be double,int,long and float but your are writing String arguments in Math.max function. You need to parse them in the required type.

You code will produce compile time error because of above mismatches.

Try following updated code, that will solve your purpose:

import java.lang.Math;
import java.util.Scanner;
public class max {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please input 3 integers: ");
        int x = Integer.parseInt(keyboard.nextLine());
        int y = Integer.parseInt(keyboard.nextLine());
        int z = Integer.parseInt(keyboard.nextLine());
        int max = Math.max(x,y);
        if(max>y){ //suppose x is max then compare x with z to find max number
            max = Math.max(x,z);    
        }
        else{ //if y is max then compare y with z to find max number
            max = Math.max(y,z);    
        }
        System.out.println("The max of three is: " + max);
    }
} 

Get values from other sheet using VBA

Maybe you can use the script i am using to retrieve a certain cell value from another sheet back to a specific sheet.

Sub reviewRow()
Application.ScreenUpdating = False
Results = MsgBox("Do you want to View selected row?", vbYesNo, "")
If Results = vbYes And Range("C10") > 1 Then
i = Range("C10") //this is where i put the row number that i want to retrieve or review that can be changed as needed
Worksheets("Sheet1").Range("C6") = Worksheets("Sheet2").Range("C" & i) //sheet names can be changed as necessary
End if
Application.ScreenUpdating = True
End Sub

You can make a form using this and personalize it as needed.

Linux command to list all available commands and aliases

You can always to the following:

1. Hold the $PATH environment variable value.
2. Split by ":"
3. For earch entry: 
    ls * $entry 
4. grep your command in that output.

The shell will execute command only if they are listed in the path env var anyway.

How to set seekbar min and max value

    private static final int MIN_METERS = 100;
    private static final int JUMP_BY = 50;

    metersText.setText(meters+"");
    metersBar.setProgress((meters-MIN_METERS));
    metersBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
            progress = progress + MIN_METERS;
            progress = progress / JUMP_BY;
            progress = progress * JUMP_BY;
            metersText.setText((progress)+"");
        }
    });
}

Angularjs prevent form submission when input validation fails

Just to add to the answers above,

I was having a 2 regular buttons as shown below. (No type="submit"anywhere)

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.

As a workaround,

I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.

<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>

<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

Well, my intention was never to submit on Enter, so the above given hack just works fine.

How can I exclude one word with grep?

Invert match using grep -v:

grep -v "unwanted word" file pattern

How to empty a redis database?

Be careful here.

FlushDB deletes all keys in the current database while FlushALL deletes all keys in all databases on the current host.

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).

RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.

WebView : to load html, static or dynamic pages.

For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html

Fastest way(s) to move the cursor on a terminal command line?

I made a script to make the command line cursor move on mouse click :

  1. Enable xterm mouse tracking reporting
  2. Set readline bindings to consume the escape sequence generated by clicks

It can be found on github

More info on another post

Will work if echo -e "\e[?1000;1006;1015h" # Enable tracking print escape sequences on terminal when clicking with mouse

Multiple try codes in one block

You could try a for loop


for func,args,kwargs in zip([a,b,c,d], 
                            [args_a,args_b,args_c,args_d],
                            [kw_a,kw_b,kw_c,kw_d]):
    try:
       func(*args, **kwargs)
       break
    except:
       pass

This way you can loop as many functions as you want without making the code look ugly

Set a thin border using .css() in javascript

After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:

border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.

How to check whether a str(variable) is empty or not?

element = random.choice(myList)
if element:
    # element contains text
else:
    # element is empty ''

Does Google Chrome work with Selenium IDE (as Firefox does)?

If you want to harness Selenium IDE record & playback capabilities for Chrome browser there is an equivalent extension for Chrome called Scirocco. You can add it to Chrome by visiting here using your Chrome browser https://chrome.google.com/webstore/search/scirocco

Scirocco is created by Sonix Asia and is not as polished as Selenium IDE for Firefox. It is in fact quite buggy in places. But it does what you ask.

Different ways of clearing lists

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []

Proxies with Python 'Requests' module

I share some code how to fetch proxies from the site "https://free-proxy-list.net" and store data to a file compatible with tools like "Elite Proxy Switcher"(format IP:PORT):

##PROXY_UPDATER - get free proxies from https://free-proxy-list.net/

from lxml.html import fromstring
import requests
from itertools import cycle
import traceback
import re

######################FIND PROXIES#########################################
def get_proxies():
    url = 'https://free-proxy-list.net/'
    response = requests.get(url)
    parser = fromstring(response.text)
    proxies = set()
    for i in parser.xpath('//tbody/tr')[:299]:   #299 proxies max
        proxy = ":".join([i.xpath('.//td[1]/text()') 
        [0],i.xpath('.//td[2]/text()')[0]])
        proxies.add(proxy)
    return proxies



######################write to file in format   IP:PORT######################
try:
    proxies = get_proxies()
    f=open('proxy_list.txt','w')
    for proxy in proxies:
        f.write(proxy+'\n')
    f.close()
    print ("DONE")
except:
    print ("MAJOR ERROR")

How to perform a for loop on each character in a string in Bash?

TEXT="hello world"
for i in {1..${#TEXT}}; do
   echo ${TEXT[i]}
done

where {1..N} is an inclusive range

${#TEXT} is a number of letters in a string

${TEXT[i]} - you can get char from string like an item from an array

How to connect to a MS Access file (mdb) using C#?

Try this..

using System.Data.OleDb;

OleDbConnection dbConn;

dConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Registration.accdb;");

CSS full screen div with text in the middle

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

Can you target <br /> with css?

There is one good reason you would need to style a <br> tag.

When it is part of code you don't want to (or can't) change and you want this particular <br> not to be displayed.

.xxx br {display:none}

Can save a lot of time and sometimes your day.

Does calling clone() on an array also clone its contents?

1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).

Remember that 2D array clone doesn't work due to shallow copy implementation of clone().

public static void main(String[] args) {
    int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

    int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true
}

Hidden Features of Java

The asList method in java.util.Arrays allows a nice combination of varargs, generic methods and autoboxing:

List<Integer> ints = Arrays.asList(1,2,3);

What should every programmer know about security?

You should know about the three A's. Authentication, Authorization, Audit. Classical mistake is to authenticate a user, while not checking if user is authorized to perform some action, so a user may look at other users private photos, the mistake Diaspora did. Many, many more people forget about Audit, you need, in a secure system, to be able to tell who did what and when.

Convert a date format in epoch

  String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
   DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
        LocalDateTime zdt  = LocalDateTime.parse(dateTime,dtf);
        LocalDateTime now = LocalDateTime.now();
        ZoneId zone = ZoneId.of("Asia/Kolkata");
        ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
        long a= zdt.toInstant(zoneOffSet).toEpochMilli();
        Log.d("time","---"+a);

you can get zone id form this a link!

json_encode/json_decode - returns stdClass instead of Array in PHP

There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).

The concrete code is by Michal Migurski and by Matt Knapp:

YouTube API to fetch all videos on a channel

To get channels list :

Get Channels list by forUserName:

https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&forUsername=Apple&key=

Get channels list by channel id:

https://www.googleapis.com/youtube/v3/channels/?part=snippet,contentDetails,statistics&id=UCE_M8A5yxnLfW0KghEeajjw&key=

Get Channel sections:

https://www.googleapis.com/youtube/v3/channelSections?part=snippet,contentDetails&channelId=UCE_M8A5yxnLfW0KghEeajjw&key=

To get Playlists :

Get Playlists by Channel ID:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=

Get Playlists by Channel ID with pageToken:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=&pageToken=CDIQAA

To get PlaylistItems :

Get PlaylistItems list by PlayListId:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults=25&playlistId=PLHFlHpPjgk70Yv3kxQvkDEO5n5tMQia5I&key=

To get videos :

Get videos list by video id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw&key=

Get videos list by multiple videos id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw,Qgy6LaO3SB0,7yPJXGO2Dcw&key=

Get comments list

Get Comment list by video ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=el****kQak&key=A**********k

Get Comment list by channel ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&channelId=U*****Q&key=AI********k

Get Comment list by allThreadsRelatedToChannelId:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&allThreadsRelatedToChannelId=UC*****ntcQ&key=AI*****k

Here all api's are Get approach.

Based on channel id we con't get all videos directly, that's the important point here.

For integration https://developers.google.com/youtube/v3/quickstart/ios?ver=swift

Make a div fill up the remaining width

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

CSS:

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

HTML:

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

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

jsFiddle

How to alter a column's data type in a PostgreSQL table?

See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);

Interface defining a constructor signature?

I was looking back at this question and I thought to myself, maybe we are aproaching this problem the wrong way. Interfaces might not be the way to go when it concerns defining a constructor with certain parameters... but an (abstract) base class is.

If you create a base class with a constructor on there that accepts the parameters you need, every class that derrives from it needs to supply them.

public abstract class Foo
{
  protected Foo(SomeParameter x)
  {
    this.X = x;
  }

  public SomeParameter X { get; private set }
}

public class Bar : Foo // Bar inherits from Foo
{
  public Bar() 
    : base(new SomeParameter("etc...")) // Bar will need to supply the constructor param
  {
  }
}

The cause of "bad magic number" error when loading a workspace and how to avoid it?

The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.

This error indicates you are trying to load a non-valid file type into R. For some reason, R no longer recognizes this file as an R workspace file.

Tuple unpacking in for loops

Short answer, unpacking tuples from a list in a for loop works. enumerate() creates a tuple using the current index and the entire current item, such as (0, ('bob', 3))

I created some test code to demonstrate this:

    list = [('bob', 3), ('alice', 0), ('john', 5), ('chris', 4), ('alex', 2)]

    print("Displaying Enumerated List")
    for name, num in enumerate(list):
        print("{0}: {1}".format(name, num))

    print("Display Normal Iteration though List")
    for name, num in list:
        print("{0}: {1}".format(name, num))

The simplicity of Tuple unpacking is probably one of my favourite things about Python :D

Getting attributes of Enum's value

Here is code to get information from a Display attribute. It uses a generic method to retrieve the attribute. If the attribute is not found it converts the enum value to a string with pascal/camel case converted to title case (code obtained here)

public static class EnumHelper
{
    // Get the Name value of the Display attribute if the   
    // enum has one, otherwise use the value converted to title case.  
    public static string GetDisplayName<TEnum>(this TEnum value)
        where TEnum : struct, IConvertible
    {
        var attr = value.GetAttributeOfType<TEnum, DisplayAttribute>();
        return attr == null ? value.ToString().ToSpacedTitleCase() : attr.Name;
    }

    // Get the ShortName value of the Display attribute if the   
    // enum has one, otherwise use the value converted to title case.  
    public static string GetDisplayShortName<TEnum>(this TEnum value)
        where TEnum : struct, IConvertible
    {
        var attr = value.GetAttributeOfType<TEnum, DisplayAttribute>();
        return attr == null ? value.ToString().ToSpacedTitleCase() : attr.ShortName;
    }

    /// <summary>
    /// Gets an attribute on an enum field value
    /// </summary>
    /// <typeparam name="TEnum">The enum type</typeparam>
    /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
    /// <param name="value">The enum value</param>
    /// <returns>The attribute of type T that exists on the enum value</returns>
    private static T GetAttributeOfType<TEnum, T>(this TEnum value)
        where TEnum : struct, IConvertible
        where T : Attribute
    {

        return value.GetType()
                    .GetMember(value.ToString())
                    .First()
                    .GetCustomAttributes(false)
                    .OfType<T>()
                    .LastOrDefault();
    }
}

And this is the extension method for strings for converting to title case:

    /// <summary>
    /// Converts camel case or pascal case to separate words with title case
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string ToSpacedTitleCase(this string s)
    {
        //https://stackoverflow.com/a/155486/150342
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;
        return textInfo
           .ToTitleCase(Regex.Replace(s, 
                        "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 "));
    }

Select max value of each group

select Name, Value, AnotherColumn
from out_pumptable
where Value =
(
  select Max(Value)
  from out_pumptable as f where f.Name=out_pumptable.Name
)
group by Name, Value, AnotherColumn

Try like this, It works.

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

String pooling

String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. You can achieve this goal by keeping your own Map (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.

At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.

String.intern() in Java 6

In those good old days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).

The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=96m option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage of String.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.

String.intern() in Java 7

Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.

String pool values are garbage collected

Yes, all strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It applies to all discussed versions of Java. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.

Being eligible for garbage collection and residing in the heap, a JVM string pool seems to be a right place for all your strings, isn’t it? In theory it is true – non-used strings will be garbage collected from the pool, used strings will allow you to save memory in case then you get an equal string from the input. Seems to be a perfect memory saving strategy? Nearly so. You must know how the string pool is implemented before making any decisions.

source.

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

In addition to the repository permissions, the /tmp directory must also be writeable by all users.

How to remove Firefox's dotted outline on BUTTONS as well as links?

[Update] This solution doesn't work anymore. The solution that worked for me is this one https://stackoverflow.com/a/3844452/925560

The answer marked as correct didn't work with Firefox 24.0.

To remove Firefox's dotted outline on buttons and anchor tags I added the code below:

a:focus, a:active, 
button::-moz-focus-inner,
input[type="reset"]::-moz-focus-inner,
input[type="button"]::-moz-focus-inner,
input[type="submit"]::-moz-focus-inner,
select::-moz-focus-inner,
input[type="file"] > input[type="button"]::-moz-focus-inner {
    border: 0;
    outline : 0;
}

I found the solution here: http://aghoshb.com/articles/css-how-to-remove-firefoxs-dotted-outline-on-buttons-and-anchor-tags.html

Navigation Controller Push View Controller

    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"storyBoardName" bundle:nil];
    MemberDetailsViewController* controller = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentiferInStoryBoard"];
[self.navigationController pushViewController:viewControllerName animated:YES];

Swift 4:

let storyBoard = UIStoryboard(name: "storyBoardName", bundle:nil)
let memberDetailsViewController = storyBoard.instantiateViewController(withIdentifier: "viewControllerIdentiferInStoryBoard") as! MemberDetailsViewController
self.navigationController?.pushViewController(memberDetailsViewController, animated:true)

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

In my case, I had to use different certificates for different git repositories.

Follow steps below (If you have a certificate of your repository, you can read from step 5)

  1. Go to remote repository's site. Ex: github.com, bitbucket.org, tfs.example...

  2. Click Lock icon on the upper left side and click Certificate.

  3. Go to Certification Path tab and double click to .. Root Certificate

  4. Go to Details tab and click Copy to file.

  5. Export/Copy certificate to wherever you want. Ex: C:\certs\example.cer

  6. Open git bash at your local repository folder and type:

    $ git config http.sslCAInfo "C:\certs\example.cer"

Now you can use different certificates for each repository.

Remember, calling with the --global parameter will also change the certificates of git repositories in other folders, so you should not use the --global parameter when executing this command.

How do I programmatically click on an element in JavaScript?

Are you trying to actually follow the link or trigger the onclick? You can trigger an onclick with something like this:

var link = document.getElementById(linkId);
link.onclick.call(link);

how to print float value upto 2 decimal place without rounding off

The only easy way to do this is to use snprintf to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:

char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);

Checking whether a string starts with XXXX

I did a little experiment to see which of these methods

  • string.startswith('hello')
  • string.rfind('hello') == 0
  • string.rpartition('hello')[0] == ''
  • string.rindex('hello') == 0

are most efficient to return whether a certain string begins with another string.

Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while loop I used:

['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']

I believe that it is pretty obvious from the start that the startswith method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.

What surprises me is that the seemingly impractical string.rpartition('hello')[0] == '' method always finds a way to be listed first, before the string.startswith('hello') method, every now and then. The results show that using str.partition to determine if a string starts with another string is more efficient then using both rfind and rindex.

Another thing I've noticed is that string.rindex('hello') == 0 and string.rindex('hello') == 0 have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.

Here is the code:

from time import perf_counter

string = 'hello world'
places = dict()

while True:
    start = perf_counter()
    for _ in range(5000000):
        string.startswith('hello')
    end = perf_counter()
    places['startswith'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rfind('hello') == 0
    end = perf_counter()
    places['rfind'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rpartition('hello')[0] == ''
    end = perf_counter()
    places['rpartition'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rindex('hello') == 0
    end = perf_counter()
    places['rindex'] = round(end - start, 2)
    
    print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

How to force IE to reload javascript?

Paolo's general idea (i.e. effectively changing some part of the request uri) is your best bet. However, I'd suggest using a more static value such as a version number that you update when you have changed your script file so that you can still get the performance gains of caching.

So either something like this:

<script src="/my/js/file.js?version=2.1.3" ></script>

or maybe

<script src="/my/js/file.2.1.3.js" ></script>

I prefer the first option because it means you can maintain the one file instead of having to constantly rename it (which for example maintains consistent version history in your source control). Of course either one (as I've described them) would involve updating your include statements each time, so you may want to come up with a dynamic way of doing it, such as replacing a fixed value with a dynamic one every time you deploy (using Ant or whatever).

"Full screen" <iframe>

You can use this piece of code:

  <iframe src="http://example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0%;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>

Which is the correct C# infinite loop, for (;;) or while (true)?

To rehash a couple of old jokes:

  1. Don't use "for (;;) {}" — it makes the statement cry.
  2. Unless, of course, you "#define EVER ;;".

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

How to prevent a jQuery Ajax request from caching in Internet Explorer?

If you set unique parameters, then the cache does not work, for example:

$.ajax({
    url : "my_url",
    data : {
        'uniq_param' : (new Date()).getTime(),
        //other data
    }});

When to use the different log levels

I've always considered warning the first log level that for sure means there is a problem (for example, perhaps a config file isn't where it should be and we're going to have to run with default settings). An error implies, to me, something that means the main goal of the software is now impossible and we're going to try to shut down cleanly.

How do I create a file AND any folders, if the folders don't exist?

Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions Sample code:

FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
    f2.Demand();
}
catch (SecurityException s)
{
    Console.WriteLine(s.Message);
}

Understanding .NET Code Access Security

Is “Code Access Security” of any real world use?

How do I encode and decode a base64 string?

One liner code:

Note: Use System and System.Text directives.

Encode:

string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes("inputStr"));

Decode:

string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(encodedStr));

URL to load resources from the classpath in Java

Intro and basic Implementation

First up, you're going to need at least a URLStreamHandler. This will actually open the connection to a given URL. Notice that this is simply called Handler; this allows you to specify java -Djava.protocol.handler.pkgs=org.my.protocols and it will automatically be picked up, using the "simple" package name as the supported protocol (in this case "classpath").

Usage

new URL("classpath:org/my/package/resource.extension").openConnection();

Code

package org.my.protocols.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class Handler extends URLStreamHandler {
    /** The classloader to find resources from. */
    private final ClassLoader classLoader;

    public Handler() {
        this.classLoader = getClass().getClassLoader();
    }

    public Handler(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        final URL resourceUrl = classLoader.getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}

Launch issues

If you're anything like me, you don't want to rely on a property being set in the launch to get you somewhere (in my case, I like to keep my options open like Java WebStart - which is why I need all this).

Workarounds/Enhancements

Manual code Handler specification

If you control the code, you can do

new URL(null, "classpath:some/package/resource.extension", new org.my.protocols.classpath.Handler(ClassLoader.getSystemClassLoader()))

and this will use your handler to open the connection.

But again, this is less than satisfactory, as you don't need a URL to do this - you want to do this because some lib you can't (or don't want to) control wants urls...

JVM Handler registration

The ultimate option is to register a URLStreamHandlerFactory that will handle all urls across the jvm:

package my.org.url;

import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map;

class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory {
    private final Map<String, URLStreamHandler> protocolHandlers;

    public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) {
        protocolHandlers = new HashMap<String, URLStreamHandler>();
        addHandler(protocol, urlHandler);
    }

    public void addHandler(String protocol, URLStreamHandler urlHandler) {
        protocolHandlers.put(protocol, urlHandler);
    }

    public URLStreamHandler createURLStreamHandler(String protocol) {
        return protocolHandlers.get(protocol);
    }
}

To register the handler, call URL.setURLStreamHandlerFactory() with your configured factory. Then do new URL("classpath:org/my/package/resource.extension") like the first example and away you go.

JVM Handler Registration Issue

Note that this method may only be called once per JVM, and note well that Tomcat will use this method to register a JNDI handler (AFAIK). Try Jetty (I will be); at worst, you can use the method first and then it has to work around you!

License

I release this to the public domain, and ask that if you wish to modify that you start a OSS project somewhere and comment here with the details. A better implementation would be to have a URLStreamHandlerFactory that uses ThreadLocals to store URLStreamHandlers for each Thread.currentThread().getContextClassLoader(). I'll even give you my modifications and test classes.

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

Fastest way to tell if two files have the same contents in Unix/Linux?

Doing some testing with a Raspberry Pi 3B+ (I'm using an overlay file system, and need to sync periodically), I ran a comparison of my own for diff -q and cmp -s; note that this is a log from inside /dev/shm, so disk access speeds are a non-issue:

[root@mypi shm]# dd if=/dev/urandom of=test.file bs=1M count=100 ; time diff -q test.file test.copy && echo diff true || echo diff false ; time cmp -s test.file test.copy && echo cmp true || echo cmp false ; cp -a test.file test.copy ; time diff -q test.file test.copy && echo diff true || echo diff false; time cmp -s test.file test.copy && echo cmp true || echo cmp false
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 6.2564 s, 16.8 MB/s
Files test.file and test.copy differ

real    0m0.008s
user    0m0.008s
sys     0m0.000s
diff false

real    0m0.009s
user    0m0.007s
sys     0m0.001s
cmp false
cp: overwrite âtest.copyâ? y

real    0m0.966s
user    0m0.447s
sys     0m0.518s
diff true

real    0m0.785s
user    0m0.211s
sys     0m0.573s
cmp true
[root@mypi shm]# pico /root/rwbscripts/utils/squish.sh

I ran it a couple of times. cmp -s consistently had slightly shorter times on the test box I was using. So if you want to use cmp -s to do things between two files....

identical (){
  echo "$1" and "$2" are the same.
  echo This is a function, you can put whatever you want in here.
}
different () {
  echo "$1" and "$2" are different.
  echo This is a function, you can put whatever you want in here, too.
}
cmp -s "$FILEA" "$FILEB" && identical "$FILEA" "$FILEB" || different "$FILEA" "$FILEB"

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

For use the syntax like return Post::getAll(); you should have a magic function __callStatic in your class where handle all static calls:

public static function __callStatic($method, $parameters)
{
    return (new static)->$method(...$parameters);
}

disabling spring security in spring boot app

Use @profile("whatever-name-profile-to-activate-if-needed") on your security configuration class that extends WebSecurityConfigurerAdapter

security.ignored=/**

security.basic.enable: false

NB. I need to debug to know why why exclude auto configuration did not work for me. But the profile is sot so bad as you can still re-activate it via configuration properties if needed

Disable mouse scroll wheel zoom on embedded Google Maps

Here is my solution for the problem, I was building a WP site, so there is a little php code here. But the key is scrollwheel: false, in the map object.

function initMap() {
        var uluru = {lat: <?php echo $latitude; ?>, lng: <?php echo $Longitude; ?>};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 18,
            scrollwheel: false,
            center: uluru
        });
        var marker = new google.maps.Marker({
            position: uluru,
            map: map
        });
    }

Hope this will help. Cheers

javax vs java package

java.* packages are the core Java language packages, meaning that programmers using the Java language had to use them in order to make any worthwhile use of the java language.

javax.* packages are optional packages, which provides a standard, scalable way to make custom APIs available to all applications running on the Java platform.

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

Putting a simple if-then-else statement on one line

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()

How do I install a plugin for vim?

Update (as 2019):

cd ~/.vim
git clone git://github.com/tpope/vim-haml.git pack/bundle/start/haml

Explanation (from :h pack ad :h packages):

  1. All the directories found are added to runtimepath. They must be in ~/.vim/pack/whatever/start [you can only change whatever].
  2. the plugins found in the plugins dir in runtimepath are sourced.

So this load the plugin on start (hence the name start).

You can also get optional plugin (loaded with :packadd) if you put them in ~/.vim/pack/bundle/opt

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

What is the maximum recursion depth in Python, and how to increase it?

I wanted to give you an example for using memoization to compute Fibonacci as this will allow you to compute significantly larger numbers using recursion:

cache = {}
def fib_dp(n):
    if n in cache:
        return cache[n]
    if n == 0: return 0
    elif n == 1: return 1
    else:
        value = fib_dp(n-1) + fib_dp(n-2)
    cache[n] = value
    return value

print(fib_dp(998))

This is still recursive, but uses a simple hashtable that allows the reuse of previously calculated Fibonacci numbers instead of doing them again.

Add custom message to thrown exception while maintaining stack trace in Java

Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:

throw new TransactionProblemException(transNbr, originalException);

The stack trace will look like

TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...

Is it possible to access an SQLite database from JavaScript?

IMHO, the best way is to call Python using POST via AJAX and do everything you need to do with the DB within Python, then return the result to the javascript. json and sqlite support in Python is awesome and it's 100% built-in within even slightly recent versions of Python, so there is no "install this, install that" pain. In Python:

import sqlite3
import json

...that's all you need. It's part of every Python distribution.

@Sedrick Jefferson asked for examples, so (somewhat tardily) I have written up a stand-alone back-and-forth between Javascript and Python here.

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

AWK: Access captured group from line pattern

That was a stroll down memory lane...

I replaced awk by perl a long time ago.

Apparently the AWK regular expression engine does not capture its groups.

you might consider using something like :

perl -n -e'/test(\d+)/ && print $1'

the -n flag causes perl to loop over every line like awk does.

How to get 30 days prior to current date?

let today = new Date()

let last30Days = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30)

last30Days will be in Date Object

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

Did you try this simple solution? Only 2 clicks away!

At the query window,

  1. set query options to "Results to Grid", run your query
  2. Right click on the results tab at the grid corner, save results as any files

You will get all the text you want to see in the file!!! I can see 130,556 characters for my result of a varchar(MAX) field

Results in a file

CSS: How to position two elements on top of each other, without specifying a height?

I had to set

Container_height = Element1_height = Element2_height

.Container {
    position: relative;
}

.ElementOne, .Container ,.ElementTwo{
    width: 283px;
    height: 71px;
}

.ElementOne {
    position:absolute;
}

.ElementTwo{
    position:absolute;
}

Use can use z-index to set which one to be on top.

Using headers with the Python requests library's get method

This answer taught me that you can set headers for an entire session:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

Bonus: Sessions also handle cookies.

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

Open two instances of a file in a single Visual Studio session

How to open two instances of the same file side by side in Visual Studio 2019:

  1. Open the file.

  2. Click Window -> New Window.

  3. A new window should be open with the same file.

  4. Click on Window -> New Vertical Document Group.

Result: enter image description here

Set selected item in Android BottomNavigationView

To programmatically click on the BottomNavigationBar item you need use:

View view = bottomNavigationView.findViewById(R.id.menu_action_item);
view.performClick();

This arranges all the items with their labels correctly.

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

Set selected option of select box

$(function() {
$("#demo").val('hello');
});

HTML table with 100% width, with vertical scroll inside tbody

I got it finally right with pure CSS by following these instructions:

http://tjvantoll.com/2012/11/10/creating-cross-browser-scrollable-tbody/

The first step is to set the <tbody> to display: block so an overflow and height can be applied. From there the rows in the <thead> need to be set to position: relative and display: block so that they’ll sit on top of the now scrollable <tbody>.

tbody, thead { display: block; overflow-y: auto; }

Because the <thead> is relatively positioned each table cell needs an explicit width

td:nth-child(1), th:nth-child(1) { width: 100px; }
td:nth-child(2), th:nth-child(2) { width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }

But unfortunately that is not enough. When a scrollbar is present browsers allocate space for it, therefore, the <tbody> ends up having less space available than the <thead>. Notice the slight misalignment this creates...

The only workaround I could come up with was to set a min-width on all columns except the last one.

td:nth-child(1), th:nth-child(1) { min-width: 100px; }
td:nth-child(2), th:nth-child(2) { min-width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }

Whole codepen example below:

CSS:

.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed_headers th {
  text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
}
.fixed_headers thead {
  background-color: #333333;
  color: #fdfdfd;
}
.fixed_headers thead tr {
  display: block;
  position: relative;
}
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
  background-color: #dddddd;
}
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
}
.old_ie_wrapper tbody {
  height: auto;
}

Html:

<!-- IE < 10 does not like giving a tbody a height.  The workaround here applies the scrolling to a wrapped <div>. -->
<!--[if lte IE 9]>
<div class="old_ie_wrapper">
<!--<![endif]-->

<table class="fixed_headers">
  <thead>
    <tr>
      <th>Name</th>
      <th>Color</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Pear</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Grape</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
    </tr>
    <tr>
      <td>Orange</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Banana</td>
      <td>Yellow</td>
      <td>These are yellow.</td>
    </tr>
    <tr>
      <td>Kiwi</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Plum</td>
      <td>Purple</td>
      <td>These are Purple</td>
    </tr>
    <tr>
      <td>Watermelon</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Tomato</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cherry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cantelope</td>
      <td>Orange</td>
      <td>These are orange inside.</td>
    </tr>
    <tr>
      <td>Honeydew</td>
      <td>Green</td>
      <td>These are green inside.</td>
    </tr>
    <tr>
      <td>Papaya</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Raspberry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Blueberry</td>
      <td>Blue</td>
      <td>These are blue.</td>
    </tr>
    <tr>
      <td>Mango</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Passion Fruit</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
  </tbody>
</table>

<!--[if lte IE 9]>
</div>
<!--<![endif]-->

EDIT: Alternative solution for table width 100% (above actually is for fixed width and didn't answer the question):

HTML:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Color</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Pear</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Grape</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
    </tr>
    <tr>
      <td>Orange</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Banana</td>
      <td>Yellow</td>
      <td>These are yellow.</td>
    </tr>
    <tr>
      <td>Kiwi</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
  </tbody>
</table>

CSS:

table {
  width: 100%;
  text-align: left;
  min-width: 610px;
}
tr {
  height: 30px;
  padding-top: 10px
}
tbody { 
  height: 150px; 
  overflow-y: auto;
  overflow-x: hidden;
}
th,td,tr,thead,tbody { display: block; }
td,th { float: left; }
td:nth-child(1),
th:nth-child(1) {
  width: 20%;
}
td:nth-child(2),
th:nth-child(2) {
  width: 20%;
  float: left;
}
td:nth-child(3),
th:nth-child(3) {
  width: 59%;
  float: left;
}
/* some colors */
thead {
  background-color: #333333;
  color: #fdfdfd;
}
table tbody tr:nth-child(even) {
  background-color: #dddddd;
}

Demo: http://codepen.io/anon/pen/bNJeLO

How do I fire an event when a iframe has finished loading in jQuery?

I tried an out of the box approach to this, I havent tested this for PDF content but it did work for normal HTML based content, heres how:

Step 1: Wrap your Iframe in a div wrapper

Step 2: Add a background image to your div wrapper:

.wrapperdiv{
  background-image:url(img/loading.gif);
  background-repeat:no-repeat;
  background-position:center center; /*Can place your loader where ever you like */
}

Step 3: in ur iframe tag add ALLOWTRANSPARENCY="false"

The idea is to show the loading animation in the wrapper div till the iframe loads after it has loaded the iframe would cover the loading animation.

Give it a try.

Streaming via RTSP or RTP in HTML5

There are three streaming protocols / technology in HTML5:

Live streaming, low latency - WebRTC - Websocket

VOD and Live streaming, high latency - HLS

1. WebRTC

In fact WebRTC is SRTP(secure RTP protocol). Thus we can say that video tag supports RTP(SRTP) indirectly via WebRTC.

Therefore to get RTP stream on your Chrome, Firefox or another HTML5 browser, you need a WebRTC server which will deliver the SRTP stream to browser.

2. Websocket

It is TCP based, but with lower latency than HLS. Again you need a Websocket server.

3. HLS

Most popular high-latency streaming protocol for VOD(pre-recorded video).

How to set background color of a View

I use at API min 16 , target 23

Button WeekDoneButton = (Button) viewWeeklyTimetable.findViewById(R.id.week_done_button);

WeekDoneButton.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));

TestNG ERROR Cannot find class in classpath

I had to make a jar file from my test classes and add it to my class path. Previously I added my test class file to class path and then I got above error. So I created a jar and added to classpath.

e.g

java -cp "my_jars/*" org.testng.TestNG testing.xml

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

Print Html template in Angular 2 (ng-print in Angular 2)

Print service

import { Injectable } from '@angular/core';

@Injectable()
export class PrintingService {

public print(printEl: HTMLElement) {
    let printContainer: HTMLElement = document.querySelector('#print-container');

    if (!printContainer) {
      printContainer = document.createElement('div');
      printContainer.id = 'print-container';
    } 

    printContainer.innerHTML = '';

    let elementCopy = printEl.cloneNode(true);
    printContainer.appendChild(elementCopy);
    document.body.appendChild(printContainer);

    window.print();
  }
}

?omponent that I want to print

@Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  styleUrls: ['./component.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class MyComponent {
  @ViewChild('printEl') printEl: ElementRef;

  constructor(private printingService: PrintingService) {}

  public print(): void {
    this.printingService.print(this.printEl.nativeElement);
 }

}

Not the best choice, but works.

Determining whether an object is a member of a collection in VBA

Not exactly elegant, but the best (and quickest) solution i could find was using OnError. This will be significantly faster than iteration for any medium to large collection.

Public Function InCollection(col As Collection, key As String) As Boolean
  Dim var As Variant
  Dim errNumber As Long

  InCollection = False
  Set var = Nothing

  Err.Clear
  On Error Resume Next
    var = col.Item(key)
    errNumber = CLng(Err.Number)
  On Error GoTo 0

  '5 is not in, 0 and 438 represent incollection
  If errNumber = 5 Then ' it is 5 if not in collection
    InCollection = False
  Else
    InCollection = True
  End If

End Function

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

AngularJS access parent scope from child controller

When you are using as syntax, like ParentController as parentCtrl, to define a controller then to access parent scope variable in child controller use following :

var id = $scope.parentCtrl.id;

Where parentCtrl is name of parent controller using as syntax and id is a variable defined in same controller.

installing JDK8 on Windows XP - advapi32.dll error

With JRE 8 on XP there is another way - to use MSI to deploy package.

  • Install JRE 8 x86 on a PC with supported OS
  • Copy c:\Users[USER]\AppData\LocalLow\Sun\Java\jre1.8.0\jre1.8.0.msi and Data1.cab to XP PC and run jre1.8.0.msi

or (silent way, usable in batch file etc..)

for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

JSON_UNESCAPED_UNICODE is available on PHP Version 5.4 or later.
The following code is for Version 5.3.

UPDATED

  • html_entity_decode is a bit more efficient than pack + mb_convert_encoding.
  • (*SKIP)(*FAIL) skips backslashes itself and specified characters by JSON_HEX_* flags.

 

function raw_json_encode($input, $flags = 0) {
    $fails = implode('|', array_filter(array(
        '\\\\',
        $flags & JSON_HEX_TAG ? 'u003[CE]' : '',
        $flags & JSON_HEX_AMP ? 'u0026' : '',
        $flags & JSON_HEX_APOS ? 'u0027' : '',
        $flags & JSON_HEX_QUOT ? 'u0022' : '',
    )));
    $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
    $callback = function ($m) {
        return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
    };
    return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
}

What is a good game engine that uses Lua?

Heroes of Might and Magic V used modified Silent Storm engine. I think you can find many good engines listed in wikipedia: Lua-scriptable game engines

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

len() of a numpy array in python

Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.

How to view the list of compile errors in IntelliJ?

On my system (IntelliJ Idea 2017.2.5), it was not sufficient to enable "Make Project Automatically". I also had to use the menu item "View, Tool Windows, Problems" to see the problems tool window at the bottom of the screen.

Opening the problems tool window

How to compare timestamp dates with date-only parameter in MySQL?

 WHERE cast(timestamp as date) = '2012-05-05'

How to change the default docker registry from docker.io to my private registry?

if you are using the fedora distro, you can change the file

/etc/containers/registries.conf

Adding domain docker.io

Is there a way to specify which pytest tests to run from a file?

Specifying tests / selecting tests

Pytest supports several ways to run and select tests from the command-line.

Run tests in a module

pytest test_mod.py

Run tests in a directory

pytest testing/

Run tests by keyword expressions

pytest -k "MyClass and not method"

This will run tests which contain names that match the given string expression, which can include Python operators that use filenames, class names and function names as variables. The example above will run TestMyClass.test_something but not TestMyClass.test_method_simple.

Run tests by node ids

Each collected test is assigned a unique nodeid which consist of the module filename followed by specifiers like class names, function names and parameters from parametrization, separated by :: characters.

To run a specific test within a module:

pytest test_mod.py::test_func

Another example specifying a test method in the command line:

pytest test_mod.py::TestClass::test_method

Run tests by marker expressions

pytest -m slow

Will run all tests which are decorated with the @pytest.mark.slow decorator.

For more information see marks.

Run tests from packages

pytest --pyargs pkg.testing

This will import pkg.testing and use its filesystem location to find and run tests from.

Source: https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests

Android: checkbox listener

try this

satView.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (isChecked){
                // perform logic
            }
        }

    });

Tooltips for cells in HTML table (no Javascript)

Yes. You can use the title attribute on cell elements, with poor usability, or you can use CSS tooltips (several existing questions, possibly duplicates of this one).

How to create javascript delay function

You can create a delay using the following example

setInterval(function(){alert("Hello")},3000);

Replace 3000 with # of milliseconds

You can place the content of what you want executed inside the function.

Executing multi-line statements in the one-line command-line?

I wanted a solution with the following properties:

  1. Readable
  2. Read stdin for processing output of other tools

Both requirements were not provided in the other answers, so here's how to read stdin while doing everything on the command line:

grep special_string -r | sort | python3 <(cat <<EOF
import sys
for line in sys.stdin:
    tokens = line.split()
    if len(tokens) == 4:
        print("%-45s %7.3f    %s    %s" % (tokens[0], float(tokens[1]), tokens[2], tokens[3]))
EOF
)

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

You can easily write the method to do that :

  public static String toCamelCase(final String init) {
    if (init == null)
        return null;

    final StringBuilder ret = new StringBuilder(init.length());

    for (final String word : init.split(" ")) {
        if (!word.isEmpty()) {
            ret.append(Character.toUpperCase(word.charAt(0)));
            ret.append(word.substring(1).toLowerCase());
        }
        if (!(ret.length() == init.length()))
            ret.append(" ");
    }

    return ret.toString();
}

Angular redirect to login page

Please, do not override Router Outlet! It's a nightmare with latest router release (3.0 beta).

Instead use the interfaces CanActivate and CanDeactivate and set the class as canActivate / canDeactivate in your route definition.

Like that:

{ path: '', component: Component, canActivate: [AuthGuard] },

Class:

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(protected router: Router, protected authService: AuthService)
    {

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

        if (state.url !== '/login' && !this.authService.isAuthenticated()) {
            this.router.navigate(['/login']);
            return false;
        }

        return true;
    }
}

See also: https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

How to generate UML diagrams (especially sequence diagrams) from Java code?

I am one of the authors, so the answer can be biased. It is open-source (Apache 2.0), but the plugin is not free. You don't have to pay (obviously) if you clone and build it locally.

On Intellij IDEA, ZenUML can generate sequence diagram from Java code. enter image description here

Check it out at https://plugins.jetbrains.com/plugin/12437-zenuml-support

Source code: https://github.com/ZenUml/jetbrains-zenuml

What is a 'NoneType' object?

Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>

Python's None object is roughly equivalent to null, nil, etc. in other languages.

T-SQL loop over query results

DECLARE @id INT
DECLARE @filename NVARCHAR(100)
DECLARE @getid CURSOR

SET @getid = CURSOR FOR
SELECT top 3 id,
filename 
FROM  table

OPEN @getid
WHILE 1=1
BEGIN

    FETCH NEXT
    FROM @getid INTO @id, @filename
    IF @@FETCH_STATUS < 0 BREAK

    print @id

END


CLOSE @getid
DEALLOCATE @getid

Efficient way to Handle ResultSet in Java

public static List<HashMap<Object, Object>> GetListOfDataFromResultSet(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int count = metaData.getColumnCount();
        String[] columnName = new String[count];
        List<HashMap<Object,Object>> lst=new ArrayList<>();
        while(rs.next()) {
            HashMap<Object,Object> map=new HashMap<>();
            for (int i = 1; i <= count; i++){
                   columnName[i-1] = metaData.getColumnLabel(i);
                   map.put(columnName[i-1], rs.getObject(i));
            }
            lst.add(map);

        }
        return lst;
    }

Git push error '[remote rejected] master -> master (branch is currently checked out)'

Using this to push it to the remote upstream branch solved this issue for me:

git push <remote> master:origin/master

The remote had no access to the upstream repo so this was a good way to get the latest changes into that remote

Determine project root from a running node.js application

Finding the root path of an electron app could get tricky. Because the root path is different for the main process and renderer under different conditions such as production, development and packaged conditions.

I have written a npm package electron-root-path to capture the root path of an electron app.

$ npm install electron-root-path

or 

$ yarn add electron-root-path


// Import ES6 way
import { rootPath } from 'electron-root-path';

// Import ES2015 way
const rootPath = require('electron-root-path').rootPath;

// e.g:
// read a file in the root
const location = path.join(rootPath, 'package.json');
const pkgInfo = fs.readFileSync(location, { encoding: 'utf8' });

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

How to find if an array contains a specific string in JavaScript/jQuery?

You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

or

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.

Easiest way to change font and font size

Maybe something like this:

yourformName.YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

Or if you are in the same class as the form then simply do this:

YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

The constructor takes diffrent parameters (so pick your poison). Like this:

Font(Font, FontStyle)   
Font(FontFamily, Single)
Font(String, Single)
Font(FontFamily, Single, FontStyle)
Font(FontFamily, Single, GraphicsUnit)
Font(String, Single, FontStyle)
Font(String, Single, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit)
Font(String, Single, FontStyle, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte)
Font(String, Single, FontStyle, GraphicsUnit, Byte)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte, Boolean)
Font(String, Single, FontStyle, GraphicsUnit, Byte, Boolean)

Reference here

Is there any way to delete local commits in Mercurial?

Enable the "strip" extension and type the following:

hg strip #changeset# --keep

Where #changeset# is the hash for the changeset you want to remove. This will remove the said changeset including changesets that descend from it and will leave your working directory untouched. If you wish to also revert your committed code changes remove the --keep option.

For more information, check the Strip Extension.

If you get "unkown command 'strip'" you may need to enable it. To do so find the .hgrc or Mercurial.ini file and add the following to it:

[extensions]
strip =

Note that (as Juozas mentioned in his comment) having multiple heads is normal workflow in Mercurial. You should not use the strip command to battle that. Instead, you should merge your head with the incoming head, resolve any conflicts, test, and then push.

The strip command is useful when you really want to get rid of changesets that pollute the branch. In fact, if you're in this question's situation and you want to completely remove all "draft" change sets permanently, check out the top answer, which basically suggests doing:

hg strip 'roots(outgoing())'

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

To the power of in C?

You need pow(); function from math.h header.
syntax

#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);

Here x is base and y is exponent. result is x^y.

usage

pow(2,4);  

result is 2^4 = 16. //this is math notation only   
// In c ^ is a bitwise operator

And make sure you include math.h to avoid warning ("incompatible implicit declaration of built in function 'pow' ").

Link math library by using -lm while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.

How to use ImageBackground to set background image for screen in react-native

Here is a link to the RN docs: https://facebook.github.io/react-native/docs/images

A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the <ImageBackground> component, which has the same props as <Image>, and add whatever children to it you would like to layer on top of it.

You might not want to use <ImageBackground> in some cases, since the implementation is very simple. Refer to <ImageBackground>'s source code for more insight, and create your own custom component when needed.

return (
  <ImageBackground source={require('./image.png')} style={{width: '100%', height: '100%'}}>
    <Text>Inside</Text>
  </ImageBackground>
);

Note that you must specify some width and height style attributes.

Note also that the file path is relative to the directory the component is in.

How to format numbers as currency string?

javascript-number-formatter (formerly at Google Code)

  • Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
  • Accept standard number formatting like #,##0.00 or with negation -000.####.
  • Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
  • Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
  • Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
  • Auto number rounding.
  • Simple interface, just supply mask & value like this: format( "0.0000", 3.141592).
  • Include a prefix & suffix with the mask

(excerpt from its README)

Is there a simple JavaScript slider?

script.aculo.us has a slider control that might be worth checking out.

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to convert php array to utf8?

$utfEncodedArray = array_map("utf8_encode", $inputArray );

Does the job and returns a serialized array with numeric keys (not an assoc).

"The given path's format is not supported."

Does using the Path.Combine method help? It's a safer way for joining file paths together. It could be that it's having problems joining the paths together

How do I add an image to a JButton

This code work for me:

    BufferedImage image = null;
    try {
        URL file = getClass().getResource("water.bmp");
        image = ImageIO.read(file);
    } catch (IOException ioex) {
        System.err.println("load error: " + ioex.getMessage());
    }
    ImageIcon icon = new ImageIcon(image);
    JButton quitButton = new JButton(icon);

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

wait until all threads finish their work in java

Wait/block the Thread Main until some other threads complete their work.

As @Ravindra babu said it can be achieved in various ways, but showing with examples.

  • java.lang.Thread.join() Since:1.0

    public static void joiningThreads() throws InterruptedException {
        Thread t1 = new Thread( new LatchTask(1, null), "T1" );
        Thread t2 = new Thread( new LatchTask(7, null), "T2" );
        Thread t3 = new Thread( new LatchTask(5, null), "T3" );
        Thread t4 = new Thread( new LatchTask(2, null), "T4" );
    
        // Start all the threads
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    
        // Wait till all threads completes
        t1.join();
        t2.join();
        t3.join();
        t4.join();
    }
    
  • java.util.concurrent.CountDownLatch Since:1.5

    • .countDown() « Decrements the count of the latch group.
    • .await() « The await methods block until the current count reaches zero.

    If you created latchGroupCount = 4 then countDown() should be called 4 times to make count 0. So, that await() will release the blocking threads.

    public static void latchThreads() throws InterruptedException {
        int latchGroupCount = 4;
        CountDownLatch latch = new CountDownLatch(latchGroupCount);
        Thread t1 = new Thread( new LatchTask(1, latch), "T1" );
        Thread t2 = new Thread( new LatchTask(7, latch), "T2" );
        Thread t3 = new Thread( new LatchTask(5, latch), "T3" );
        Thread t4 = new Thread( new LatchTask(2, latch), "T4" );
    
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    
        //latch.countDown();
    
        latch.await(); // block until latchGroupCount is 0.
    }
    

Example code of Threaded class LatchTask. To test the approach use joiningThreads(); and latchThreads(); from main method.

class LatchTask extends Thread {
    CountDownLatch latch;
    int iterations = 10;
    public LatchTask(int iterations, CountDownLatch latch) {
        this.iterations = iterations;
        this.latch = latch;
    }

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");

        for (int i = 0; i < iterations; i++) {
            System.out.println(threadName + " : " + i);
            MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
        }
        System.out.println(threadName + " : Completed Task");
        // countDown() « Decrements the count of the latch group.
        if(latch != null)
            latch.countDown();
    }
}
  • CyclicBarriers A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
    CyclicBarrier barrier = new CyclicBarrier(3);
    barrier.await();
    
    For example refer this Concurrent_ParallelNotifyies class.

  • Executer framework: we can use ExecutorService to create a thread pool, and tracks the progress of the asynchronous tasks with Future.

    • submit(Runnable), submit(Callable) which return Future Object. By using future.get() function we can block the main thread till the working threads completes its work.

    • invokeAll(...) - returns a list of Future objects via which you can obtain the results of the executions of each Callable.

Find example of using Interfaces Runnable, Callable with Executor framework.


@See also

Style child element when hover on parent

Yes, you can do this use this below code it may help you.

_x000D_
_x000D_
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
  display : block;_x000D_
  padding : 10px;_x000D_
  text-align : center;_x000D_
  border: 5px solid #000;_x000D_
  margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
  <div class="childDiv1">_x000D_
    First Div Child_x000D_
  </div>_x000D_
  <div class="childDiv2">_x000D_
    Second Div Child_x000D_
  </div>_x000D_
  <div class="childDiv3">_x000D_
    Third Div Child_x000D_
  </div>_x000D_
  <div class="childDiv4">_x000D_
    Fourth Div Child_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

It is possible to set environment variables on Mac OS X 10.10 Yosemite with 3 files + 2 commands.

Main file with environment variables definition:

$ ls -la /etc/environment 
-r-xr-xr-x  1 root  wheel  369 Oct 21 04:42 /etc/environment
$ cat /etc/environment
#!/bin/sh

set -e

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - start"

launchctl setenv JAVA_HOME      /usr/local/jdk1.7
launchctl setenv MAVEN_HOME     /opt/local/share/java/maven3

if [ -x /usr/libexec/path_helper ]; then
    export PATH=""
    eval `/usr/libexec/path_helper -s`
    launchctl setenv PATH $PATH
fi

osascript -e 'tell app "Dock" to quit'

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - complete"

Service definition to load environment variables for user applications (terminal, IDE, ...):

$ ls -la /Library/LaunchAgents/environment.user.plist
-rw-------  1 root  wheel  504 Oct 21 04:37 /Library/LaunchAgents/environment.user.plist
$ sudo cat /Library/LaunchAgents/environment.user.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment.user</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

The same service definition for root user applications:

$ ls -la /Library/LaunchDaemons/environment.plist
-rw-------  1 root  wheel  499 Oct 21 04:38 /Library/LaunchDaemons/environment.plist
$ sudo cat /Library/LaunchDaemons/environment.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

And finally we should register these services:

$ launchctl load -w /Library/LaunchAgents/environment.user.plist
$ sudo launchctl load -w /Library/LaunchDaemons/environment.plist

What we get:

  1. The only place to declare system environment variables: /etc/environment
  2. Instant auto-update of environment variables after modification of /etc/environment file - just relaunch your application

Issues / problems:

In order your env variables were correctly taken by applications after system reboot you will need:

  • either login twice: login => logout => login
  • or close & re-open applications manually, where env variables should be taken
  • or do NOT use feature "Reopen windows when logging back".

This happens due to Apple denies explicit ordering of loaded services, so env variables are registered in parallel with processing of the "reopen queue".

But actually, I reboot my system only several times per year (on big updates), so it is not a big deal.

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

destination path already exists and is not an empty directory

What works for me is that, I created a new folder that doesn't contain any other files, and selected that new folder I created and put the clone there.

I hope this helps

How do I open a Visual Studio project in design view?

Click on the form in the Solution Explorer

Receiver not registered exception error?

EDIT: This is the answer for inazaruk and electrichead... I had run into a similar issue to them and found out the following...

There is a long-standing bug for this problem here: http://code.google.com/p/android/issues/detail?id=6191

Looks like it started around Android 2.1 and has been present in all of the Android 2.x releases since. I'm not sure if it is still a problem in Android 3.x or 4.x though.

Anyway, this StackOverflow post explains how to workaround the problem correctly (it doesn't look relevant by the URL but I promise it is)

Why does keyboard-slide crash my app?

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.

But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

How to get HTTP response code for a URL in Java?

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

. . . . . . .

System.out.println("Value" + connection.getResponseCode());
             System.out.println(connection.getResponseMessage());
             System.out.println("content"+connection.getContent());

How can I make directory writable?

chmod 777 <directory>

This will give you execute/read/write privileges. You can play with the numbers to finely tune your desired permissions.

Here is the wiki with great examples.

how to customise input field width in bootstrap 3

i solved with a max-width in my main css-file.

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

It's a simple solution with little "code"

How to get all Windows service names starting with a common word?

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

Select 2 columns in one and combine them

Yes, you can combine columns easily enough such as concatenating character data:

select col1 | col 2 as bothcols from tbl ...

or adding (for example) numeric data:

select col1 + col2 as bothcols from tbl ...

In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.

Common elements comparison between 2 lists

you can use a simple list comprehension:

x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]

Why am I getting a FileNotFoundError?

A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:

import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
    fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")

This is with a little help from the built in module os, That is a part of the Standard Python Library.

Change placeholder text

var input = document.getElementById ("IdofInput");
input.placeholder = "No need to fill this field";

You can find out more about placeholder here: http://help.dottoro.com/ljgugboo.php

How can I execute PHP code from the command line?

On the command line:

php -i | grep sourceguardian

If it's there, then you'll get some text. If not, you won't get a thing.

Setting query string using Fetch GET request

Was just working with Nativescript's fetchModule and figured out my own solution using string manipulation. Append the query string bit by bit to the url. Here is an example where query is passed as a json object (query = {order_id: 1}):

function performGetHttpRequest(fetchLink='http://myapi.com/orders', query=null) {
    if(query) {
        fetchLink += '?';
        let count = 0;
        const queryLength = Object.keys(query).length;
        for(let key in query) {
            fetchLink += key+'='+query[key];
            fetchLink += (count < queryLength) ? '&' : '';
            count++;
        }
    }
    // link becomes: 'http://myapi.com/orders?order_id=1'
    // Then, use fetch as in MDN and simply pass this fetchLink as the url.
}

I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.

Which Ruby version am I really running?

On your terminal, try running:

which -a ruby

This will output all the installed Ruby versions (via RVM, or otherwise) on your system in your PATH. If 1.8.7 is your system Ruby version, you can uninstall the system Ruby using:

sudo apt-get purge ruby

Once you have made sure you have Ruby installed via RVM alone, in your login shell you can type:

rvm --default use 2.0.0

You don't need to do this if you have only one Ruby version installed.

If you still face issues with any system Ruby files, try running:

dpkg-query -l '*ruby*'

This will output a bunch of Ruby-related files and packages which are, or were, installed on your system at the system level. Check the status of each to find if any of them is native and is causing issues.

How do you upload a file to a document library in sharepoint?

string filePath = @"C:\styles\MyStyles.css"; 
string siteURL = "http://example.org/"; 
string libraryName = "Style Library"; 

using (SPSite oSite = new SPSite(siteURL)) 
{ 
    using (SPWeb oWeb = oSite.OpenWeb()) 
    { 
        if (!System.IO.File.Exists(filePath)) 
            throw new FileNotFoundException("File not found.", filePath);                     

        SPFolder libFolder = oWeb.Folders[libraryName]; 

        // Prepare to upload 
        string fileName = System.IO.Path.GetFileName(filePath); 
        FileStream fileStream = File.OpenRead(filePath); 

        //Check the existing File out if the Library Requires CheckOut
        if (libFolder.RequiresCheckout)
        {
            try {
                SPFile fileOld = libFolder.Files[fileName];
                fileOld.CheckOut();
            } catch {}
        }

        // Upload document 
        SPFile spfile = libFolder.Files.Add(fileName, fileStream, true); 

        // Commit  
        myLibrary.Update(); 

        //Check the File in and Publish a Major Version
        if (libFolder.RequiresCheckout)
        {
                spFile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
                spFile.Publish("Publish Comment");
        }
    } 
} 

Control the size of points in an R scatterplot?

Try the cex argument:

?par

  • cex
    A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points accept a vector of values which are recycled. Other uses will take just the first value if a vector of length greater than one is supplied.

Simple and clean way to convert JSON string to Object in Swift

Here's a sample for you to make things simpler and easier. My String data in my database is a JSON file that looks like this:

[{"stype":"noun","sdsc":"careless disregard for consequences","swds":"disregard, freedom, impulse, licentiousness, recklessness, spontaneity, thoughtlessness, uninhibitedness, unrestraint, wantonness, wildness","anwds":"restraint, self-restraint"},{"stype":"verb","sdsc":"leave behind, relinquish","swds":"abdicate, back out, bail out, bow out, chicken out, cop out, cut loose, desert, discard, discontinue, ditch, drop, drop out, duck, dump, dust, flake out, fly the coop, give up the ship, kiss goodbye, leave, leg it, let go, opt out, pull out, quit, run out on, screw, ship out, stop, storm out, surrender, take a powder, take a walk, throw over, vacate, walk out on, wash hands of, withdraw, yield","anwds":"adopt, advance, allow, assert, begin, cherish, come, continue, defend, favor, go, hold, keep, maintain, persevere, pursue, remain, retain, start, stay, support, uphold"},{"stype":"verb","sdsc":"leave in troubled state","swds":"back out, desert, disown, forsake, jilt, leave, leave behind, quit, reject, renounce, throw over, walk out on","anwds":"adopt, allow, approve, assert, cherish, come, continue, defend, favor, keep, pursue, retain, stay, support, uphold"}]

To load this JSON String Data, follow these simple Steps. First, create a class for my MoreData Object like this:

class  MoreData {
public private(set) var stype : String
public private(set) var sdsc : String
public private(set) var swds : String
public private(set) var anwds : String

init( stype : String, sdsc : String, swds : String, anwds : String) {

    self.stype = stype
    self.sdsc = sdsc
    self.swds = swds
    self.anwds = anwds
}}

Second, create my String extension for my JSON String like this:

extension  String {
func toJSON() -> Any? {
    guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
    return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
}}

Third, create My Srevices Class to handle my String Data like this:

class Services {
static let instance: Services = Services()

func loadMoreDataByString(byString: String) -> [MoreData]{
    var  myVariable = [MoreData]()

    guard let ListOf = byString.toJSON() as? [[String: AnyObject]] else { return  [] }

    for object in ListOf {
        let stype  = object["stype"] as? String ?? ""
        let sdsc  = object["sdsc"] as? String ?? ""
         let swds  = object["swds"] as? String ?? ""
        let anwds  = object["anwds"] as? String ?? ""

        let myMoreData = MoreData(stype : stype, sdsc : sdsc, swds : swds, anwds : anwds)
        myVariable.append(myMoreData)
    }
    return myVariable
}}

Finally, call this Function from the View Controller to load data in the table view like this:

    func handlingJsonStringData(){
    moreData.removeAll(keepingCapacity: false)
    moreData =  Services.instance.loadMoreDataByString(byString: jsonString)
    print(self.moreData.count)
    tableView.reloadData()
}

Fixing Sublime Text 2 line endings?

The EditorConfig project (Github link) is another very viable solution. Similar to sftp-config.json and .sublime-project/workspace sort of file, once you set up a .editorconfig file, either in project folder or in a parent folder, every time you save a file within that directory structure the plugin will automatically apply the settings in the dot file and automate a few different things for you. Some of which are saving Unix-style line endings, adding end-of-file newline, removing whitespace, and adjusting your indent tab/space settings.


QUICK EXAMPLE

Install the EditorConfig plugin in Sublime using Package Control; then place a file named .editorconfig in a parent directory (even your home or the root if you like), with the following content:

[*]
end_of_line = lf

That's it. This setting will automatically apply Unix-style line endings whenever you save a file within that directory structure. You can do more cool stuff, ex. trim unwanted trailing white-spaces or add a trailing newline at the end of each file. For more detail, refer to the example file at https://github.com/sindresorhus/editorconfig-sublime, that is:

# editorconfig.org
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

The root = true line means that EditorConfig won't look for other .editorconfig files in the upper levels of the directory structure.

What is the difference between sed and awk?

sed is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.

There are various versions of sed with different levels of support for command line options and language features.

awk is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if/else, while, do/while and for (C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk.

GNU awk (gawk) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk including mawk and nawk.

Both programs use regular expressions for selecting and processing text.

I would tend to use sed where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):

sed 's/-\([0-9.]\+\)/(\1)/g' inputfile

I would use awk when the text looks more like rows and columns or, as awk refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:

awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile

Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.

filedialog, tkinter and opening files

The exception you get is telling you filedialog is not in your namespace. filedialog (and btw messagebox) is a tkinter module, so it is not imported just with from tkinter import *

>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>> 

you should use for example:

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>

or

>>> import tkinter.filedialog as fdialog

or

>>> from tkinter.filedialog import askopenfilename

So this would do for your browse button:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Example")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)

        self.button = Button(self, text="Browse", command=self.load_file, width=10)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                print("""here it comes: self.settings["template"].set(fname)""")
            except:                     # <- naked except is a bad idea
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return


if __name__ == "__main__":
    MyFrame().mainloop()

enter image description here

How to change string into QString?

Moreover, to convert whatever you want, you can use the QVariant class.

for example:

std::string str("hello !");
qDebug() << QVariant(str.c_str()).toString();
int test = 10;
double titi = 5.42;
qDebug() << QVariant(test).toString();
qDebug() << QVariant(titi).toString();
qDebug() << QVariant(titi).toInt();

output

"hello !"
"10"
"5.42"
5

Maven: add a dependency to a jar by relative path

You can use eclipse to generate a runnable Jar : Export/Runable Jar file

Session variables not working php

If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.

Easy way to password-protect php page

I would simply look for a $_GET variable and redirect the user if it's not correct.

<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
  header('Location: http://www.staggeringbeauty.com/');
}
?>

Now, if this page is located at say: http://example.com/secrets/files.php

You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)