Programs & Examples On #Inline view

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I am using Eclipse mars, Hibernate 5.2.1, Jdk7 and Oracle 11g.

I get the same error when I run Hibernate code generation tool. I guess it is a versions issue due to I have solved it through choosing Hibernate version (5.1 to 5.0) in the type frame in my Hibernate console configuration.

How do you determine the size of a file in C?

I have a function that works well with only stdio.h. I like it a lot and it works very well and is pretty concise:

size_t fsize(FILE *File) {
    size_t FSZ;
    fseek(File, 0, 2);
    FSZ = ftell(File);
    rewind(File);
    return FSZ;
}

How to dynamically change header based on AngularJS partial view?

When I had to solve this, I couldn't place the ng-app on the page's html tag, so I solved it with a service:

angular.module('myapp.common').factory('pageInfo', function ($document) {

    // Public API
    return {
        // Set page <title> tag. Both parameters are optional.
        setTitle: function (title, hideTextLogo) {
            var defaultTitle = "My App - and my app's cool tagline";
            var newTitle = (title ? title : defaultTitle) + (hideTextLogo ? '' : ' - My App')
            $document[0].title = newTitle;
        }
    };

});

Can I give a default value to parameters or optional parameters in C# functions?

It is only possible as from C# 4.0

However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:

public void Func( int i, int j )
{
    Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}

public void Func( int i )
{
    Func (i, 4);
}

public void Func ()
{
    Func (5);
}

(Or, you can upgrade to C# 4.0 offcourse).

Type converting slices of interfaces

The thing you are missing is that T and interface{} which holds a value of T have different representations in memory so can't be trivially converted.

A variable of type T is just its value in memory. There is no associated type information (in Go every variable has a single type known at compile time not at run time). It is represented in memory like this:

  • value

An interface{} holding a variable of type T is represented in memory like this

  • pointer to type T
  • value

So coming back to your original question: why go does't implicitly convert []T to []interface{}?

Converting []T to []interface{} would involve creating a new slice of interface {} values which is a non-trivial operation since the in-memory layout is completely different.

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

WPF ListView - detect when selected item is clicked

You can handle click on list view item like this:

<ListView.ItemTemplate>
  <DataTemplate>
     <Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
        <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
                </i:EventTrigger>
        </i:Interaction.Triggers>
      <Button.Template>
      <ControlTemplate>
         <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    ...

Xcode 7.2 no matching provisioning profiles found

Using Xcode 7.3, I spent way too much time trying to figure this out -- none of the answers here or elsewhere did the trick -- and ultimately stumbled into a ridiculously easy solution.

  1. In the Xcode preferences team settings, delete all provisioning profiles as mentioned in several other answers. I do this with right click, "Show in Finder," Command+A, delete -- it seems these details have changed over different Xcode versions.
  2. Do not re-download any profiles. Instead, exit your preferences and rebuild your project (I built it for my connected iPhone). A little while into the build sequence there will be an alert informing you no provisioning profiles were found, and it will ask if you want this to be fixed automatically. Choose to fix it automatically.
  3. After Xcode does some stuff, you will magically have a new provisioning profile providing what your app needs. I have since uploaded my app for TestFlight and it works great.

Hope this helps someone.

Postgresql GROUP_CONCAT equivalent?

and the version to work on the array type:

select
  array_to_string(
    array(select distinct unnest(zip_codes) from table),
    ', '
);

Function to check if a string is a date

strtotime? Lists? Regular expressions?

What's wrong with PHP's native DateTime object?

http://www.php.net/manual/en/datetime.construct.php

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.

The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.

How to combine two byte arrays

String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
    byteData[start + i] = byteSalt[i];
}

The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array. So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32. What will correct it is replacing the following line:

for (int i = 0; i < byteData.length; i ++)

with:

for (int i = 0; i < byteSalt.length; i ++)

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

VS 2010 Express is no longer linked to any VS Express pages (that I found). I did find this link to the ISO which I used and it fixed the errors mentioned here.

http://download.microsoft.com/download/1/E/5/1E5F1C0A-0D5B-426A-A603-1798B951DDAE/VS2010Express1.iso

Note: Also make sure you have x86 everything (Python + Postgresql) or you'll get other errors. I did not try x64 everything.

Unable to start Service Intent

1) check if service declaration in manifest is nested in application tag

<application>
    <service android:name="" />
</application>

2) check if your service.java is in the same package or diff package as the activity

<application>
    <!-- service.java exists in diff package -->
    <service android:name="com.package.helper.service" /> 
</application>
<application>
    <!-- service.java exists in same package -->
    <service android:name=".service" /> 
</application>

Update Top 1 record in table sql server

For those who are finding for a thread safe solution, take a look here.

Code:

UPDATE Account 
SET    sg_status = 'A'
OUTPUT INSERTED.AccountId --You only need this if you want to return some column of the updated item
WHERE  AccountId = 
(
    SELECT TOP 1 AccountId 
    FROM Account WITH (UPDLOCK) --this is what makes the query thread safe!
    ORDER  BY CreationDate 
)

Numpy: Creating a complex array from 2 real ones?

There's of course the rather obvious:

Data[...,0] + 1j * Data[...,1]

Is it safe to delete the "InetPub" folder?

Don't delete the folder or you will create a registry problem. However, if you do not want to use IIS, search the web for turning it off. You might want to check out "www.blackviper.com" because he lists all Operating System "services" (Not "Computer Services" - both are in Administrator Tools) with extra information for what you can and cannot disable to change to manual. If I recall correctly, he had some IIS info and how to turn it off.

How to create relationships in MySQL

Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than

customer_id INT( 4 ) NOT NULL ,

make it

customer_id INT( 10 ) NOT NULL ,

and make sure your int column in the customers table is int(10) also.

Setting up PostgreSQL ODBC on Windows

Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards

jQuery - Getting form values for ajax POST

try as this code.

$.ajax({
        type: "POST",
        url: "http://rt.ja.com/includes/register.php?submit=1",
        data: "username="+username+"&email="+email+"&password="+password+"&passconf="+passconf,

        success: function(html)
        {   
            //alert(html);
            $('#userError').html(html);
            $("#userError").html(userChar);
            $("#userError").html(userTaken);
        }
    });

i think this will work definitely..

you can also use .serialize() function for sending data via jquery Ajax..

i.e: data : $("#registerSubmit").serialize()

Thanks.

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

What is the difference between static func and class func in Swift?

To be clearer, I make an example here,

class ClassA {
  class func func1() -> String {
    return "func1"
  }

  static func func2() -> String {
    return "func2"
  }

  /* same as above
  final class func func2() -> String {
    return "func2"
  }
  */
}

static func is same as final class func

Because it is final, we can not override it in subclass as below:

class ClassB : ClassA {
  override class func func1() -> String {
    return "func1 in ClassB"
  }

  // ERROR: Class method overrides a 'final` class method
  override static func func2() -> String {
    return "func2 in ClassB"
  }
}

Linux: copy and create destination dir if it does not exist

mkdir -p "$d" && cp file "$d"

(there's no such option for cp).

Share variables between files in Node.js?

Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..

// main.js
var myModule = require('./module.js');
var shares = {value:123};

// Initialize module and pass the shareable object
myModule.init(shares);

// The value was changed from init2 on the other file
console.log(shares.value); // 789

On the other file..

// module.js
var shared = null;

function init2(){
    console.log(shared.value); // 123
    shared.value = 789;
}

module.exports = {
    init:function(obj){
        // Save the shared object on current module
        shared = obj;

        // Call something outside
        init2();
    }
}

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

hibernate - get id after save object

Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned

Integer id = (Integer)session.save(ticket);

Function passed as template argument

Function pointers can be passed as template parameters, and this is part of standard C++ . However in the template they are declared and used as functions rather than pointer-to-function. At template instantiation one passes the address of the function rather than just the name.

For example:

int i;


void add1(int& i) { i += 1; }

template<void op(int&)>
void do_op_fn_ptr_tpl(int& i) { op(i); }

i = 0;
do_op_fn_ptr_tpl<&add1>(i);

If you want to pass a functor type as a template argument:

struct add2_t {
  void operator()(int& i) { i += 2; }
};

template<typename op>
void do_op_fntr_tpl(int& i) {
  op o;
  o(i);
}

i = 0;
do_op_fntr_tpl<add2_t>(i);

Several answers pass a functor instance as an argument:

template<typename op>
void do_op_fntr_arg(int& i, op o) { o(i); }

i = 0;
add2_t add2;

// This has the advantage of looking identical whether 
// you pass a functor or a free function:
do_op_fntr_arg(i, add1);
do_op_fntr_arg(i, add2);

The closest you can get to this uniform appearance with a template argument is to define do_op twice- once with a non-type parameter and once with a type parameter.

// non-type (function pointer) template parameter
template<void op(int&)>
void do_op(int& i) { op(i); }

// type (functor class) template parameter
template<typename op>
void do_op(int& i) {
  op o; 
  o(i); 
}

i = 0;
do_op<&add1>(i); // still need address-of operator in the function pointer case.
do_op<add2_t>(i);

Honestly, I really expected this not to compile, but it worked for me with gcc-4.8 and Visual Studio 2013.

Regular expression for first and last name

This is what I use.

This regex accepts only names with minimum characters, from A-Z a-z ,space and -.

Names example:

Ionut Ionete, Ionut-Ionete Cantemir, Ionete Ionut-Cantemirm Ionut-Cantemir Ionete-Second

The limit of name's character is 3. If you want to change this, modify {3,} to {6,}

([a-zA-Z\-]+){3,}\s+([a-zA-Z\-]+){3,}

How to end a session in ExpressJS

req.session.destroy(); 

The above did not work for me so I did this.

req.session.cookie.expires = new Date().getTime();

By setting the expiration of the cookie to the current time, the session expired on its own.

Create boolean column in MySQL with false as default value?

You have to specify 0 (meaning false) or 1 (meaning true) as the default. Here is an example:

create table mytable (
     mybool boolean not null default 0
);

FYI: boolean is an alias for tinyint(1).

Here is the proof:

mysql> create table mytable (
    ->          mybool boolean not null default 0
    ->     );
Query OK, 0 rows affected (0.35 sec)

mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from mytable;
+--------+
| mybool |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

FYI: My test was done on the following version of MySQL:

mysql> select version();
+----------------+
| version()      |
+----------------+
| 5.0.18-max-log |
+----------------+
1 row in set (0.00 sec)

Java Hashmap: How to get key from value?

My 2 cents. You can get the keys in an array and then loop through the array. This will affect performance of this code block if the map is pretty big , where in you are getting the keys in an array first which might consume some time and then you are looping. Otherwise for smaller maps it should be ok.

String[] keys =  yourMap.keySet().toArray(new String[0]);

for(int i = 0 ; i < keys.length ; i++){
    //This is your key    
    String key = keys[i];

    //This is your value
    yourMap.get(key)            
}

How can I easily convert DataReader to List<T>?

I've covered this in a pet project.. use what you want.

Note that the ListEx implements the IDataReader interface.


people = new ListExCommand(command)
.Map(p=> new ContactPerson()
{
  Age = p.GetInt32(p.GetOrdinal("Age")),
  FirstName = p.GetString(p.GetOrdinal("FirstName")),
  IdNumber = p.GetInt64(p.GetOrdinal("IdNumber")),
  Surname = p.GetString(p.GetOrdinal("Surname")),
  Email = "[email protected]"
})
.ToListEx()
.Where("FirstName", "Peter");

Or use object mapping like in the following example.


people = new ListExAutoMap(personList)
.Map(p => new ContactPerson()
{
    Age = p.Age,
    FirstName = p.FirstName,
    IdNumber = p.IdNumber,
    Surname = p.Surname,
    Email = "[email protected]"
})
.ToListEx()
.Where(contactPerson => contactPerson.FirstName == "Zack");

Have a look at http://caprisoft.codeplex.com

CentOS: Copy directory to another directory

To copy all files, including hidden files use:

cp -r /home/server/folder/test/. /home/server/

Generate an integer that is not among four billion given ones

I will answer the 1 GB version:

There is not enough information in the question, so I will state some assumptions first:

The integer is 32 bits with range -2,147,483,648 to 2,147,483,647.

Pseudo-code:

var bitArray = new bit[4294967296];  // 0.5 GB, initialized to all 0s.

foreach (var number in file) {
    bitArray[number + 2147483648] = 1;   // Shift all numbers so they start at 0.
}

for (var i = 0; i < 4294967296; i++) {
    if (bitArray[i] == 0) {
        return i - 2147483648;
    }
}

converting a javascript string to a html object

You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..

string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call

but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.

You would need to use append or appendTo or after etc.. to put it in the dom first..

Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..

Using TortoiseSVN via the command line

As Joey pointed out, TortoiseSVN has a commandline syntax of its own. Unfortunately it is quite ugly, if you are used to svn commands, and it ignores the current working directory, thus it is not very usable - except for scripting.

I have created a little Python program (tsvn) which mimics the svn commandline syntax as closely as possible and calls TortoiseSVN accordingly. Thus, the difference between calling the normal commandline tools and calling TortoiseSVN is reduced to a little letter t at the beginning.

My tsvn program is not yet complete but already useful. It can be found in the cheeseshop (https://pypi.python.org/pypi/tsvn/)

How can I convert a string to boolean in JavaScript?

The simplest way to convert a string to a boolean is the following:

Boolean(<stringVariable>)

How to use the 'og' (Open Graph) meta tag for Facebook share

I built a tool for meta generation. It pre-configures entries for Facebook, Google+ and Twitter, and you can use it free here: http://www.groovymeta.com

To answer the question a bit more, OG tags (Open Graph) tags work similarly to meta tags, and should be placed in the HEAD section of your HTML file. See Facebook's best practises for more information on how to use OG tags effectively.

Class not registered Error

Long solved I'm sure but this might help some other poor soul.

This error can ocurre if the DLL you are deploying in the install package is not the same as the DLL you are referencing (these will have different IDs)

Sounds obvious but can easily happen if you make a small change to the dll and have previously installed the app on your own machine which reregisters the dll.

Shift elements in a numpy array

One way to do it without spilt the code into cases

with array:

def shift(arr, dx, default_value):
    result = np.empty_like(arr)
    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s: s if s > 0 else None
    result[get_neg_or_none(dx): get_pos_or_none(dx)] = default_value
    result[get_pos_or_none(dx): get_neg_or_none(dx)] = arr[get_pos_or_none(-dx): get_neg_or_none(-dx)]     
    return result

with matrix it can be done like this:

def shift(image, dx, dy, default_value):
    res = np.full_like(image, default_value)

    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s : s if s > 0 else None

    res[get_pos_or_none(-dy): get_neg_or_none(-dy), get_pos_or_none(-dx): get_neg_or_none(-dx)] = \
        image[get_pos_or_none(dy): get_neg_or_none(dy), get_pos_or_none(dx): get_neg_or_none(dx)]
    return res

Oracle: Call stored procedure inside the package

You're nearly there, just take out the EXECUTE:

DECLARE
  procId NUMBER;

BEGIN
  PKG1.INIT(1143824, 0, procId);
  DBMS_OUTPUT.PUT_LINE(procId);
END;

Converting serial port data to TCP/IP in a Linux environment

You don't need to write a program to do this in Linux. Just pipe the serial port through netcat:

netcat www.example.com port </dev/ttyS0 >/dev/ttyS0

Just replace the address and port information. Also, you may be using a different serial port (i.e. change the /dev/ttyS0 part). You can use the stty or setserial commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).

Find all paths between two graph nodes

You usually don't want to, because there is an exponential number of them in nontrivial graphs; if you really want to get all (simple) paths, or all (simple) cycles, you just find one (by walking the graph), then backtrack to another.

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

Downgrading the iOS development Target from 12.1 to 12 fix the issue for me as I don't have a dev team configured.

Make a link use POST instead of GET

This is an old question, but none of the answers satisfy the request in-full. So I'm adding another answer.

The requested code, as I understand, should make only one change to the way normal hyperlinks work: the POST method should be used instead of GET. The immediate implications would be:

  1. When the link is clicked we should reload the tab to the url of the href
  2. As the method is POST, we should have no query string in the URL of the target page we load
  3. That page should receive the data in parameters (names and value) by POST

I am using jquery here, but this could be done with native apis (harder and longer of course).

<html>
<head>
    <script src="path/to/jquery.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {

            $("a.post").click(function(e) {
                e.stopPropagation();
                e.preventDefault();
                var href = this.href;
                var parts = href.split('?');
                var url = parts[0];
                var params = parts[1].split('&');
                var pp, inputs = '';
                for(var i = 0, n = params.length; i < n; i++) {
                    pp = params[i].split('=');
                    inputs += '<input type="hidden" name="' + pp[0] + '" value="' + pp[1] + '" />';
                }
                $("body").append('<form action="'+url+'" method="post" id="poster">'+inputs+'</form>');
                $("#poster").submit();
            });
        });
    </script>
</head>
<body>
    <a class="post" href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Post it!</a><br/>
    <a href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Normal link</a>
</body>
</html>

And to see the result, save the following as reflector.php in the same directory you have the above saved.

<h2>Get</h2>
<pre>
<?php print_r($_GET); ?>
</pre>

<h2>Post</h2>
<pre>
<?php print_r($_POST); ?>
</pre>

How to center align the ActionBar title in Android?

This code will not hide back button, Same time will align the title in centre.

call this method in oncreate

centerActionBarTitle();



getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myActionBar.setIcon(new ColorDrawable(Color.TRANSPARENT));

private void centerActionBarTitle() {
    int titleId = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        titleId = getResources().getIdentifier("action_bar_title", "id", "android");
    } else {
        // This is the id is from your app's generated R class when 
        // ActionBarActivity is used for SupportActionBar
        titleId = R.id.action_bar_title;
    }

    // Final check for non-zero invalid id
    if (titleId > 0) {
        TextView titleTextView = (TextView) findViewById(titleId);
        DisplayMetrics metrics = getResources().getDisplayMetrics();

        // Fetch layout parameters of titleTextView 
        // (LinearLayout.LayoutParams : Info from HierarchyViewer)
        LinearLayout.LayoutParams txvPars = (LayoutParams) titleTextView.getLayoutParams();
        txvPars.gravity = Gravity.CENTER_HORIZONTAL;
        txvPars.width = metrics.widthPixels;
        titleTextView.setLayoutParams(txvPars);
        titleTextView.setGravity(Gravity.CENTER);
    }
}

How can I show an image using the ImageView component in javafx and fxml?

You don't need an initializer, unless you're dynamically loading a different image each time. I think doing as much as possible in fxml is more organized. Here is an fxml file that will do what you need.

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>

<AnchorPane
    xmlns:fx="http://javafx.co/fxml/1"
    xmlns="http://javafx.com/javafx/2.2"
    fx:controller="application.SampleController"
    prefHeight="316.0"
    prefWidth="321.0"
    >
    <children>
        <ImageView
                fx:id="imageView"
                fitHeight="150.0"
                fitWidth="200.0"
                layoutX="61.0"
                layoutY="83.0"
                pickOnBounds="true"
                preserveRatio="true"
            >
            <image>
                <Image
                    url="src/Box13.jpg"
                    backgroundLoading="true"
                    />
            </image>
        </ImageView>
    </children>
</AnchorPane>

Specifying the backgroundLoading property in the Image tag is optional, it defaults to false. It's best to set backgroundLoading true when it takes a moment or longer to load the image, that way a placeholder will be used until the image loads, and the program wont freeze while loading.

How can I extract a predetermined range of lines from a text file on Unix?

I wrote a Haskell program called splitter that does exactly this: have a read through my release blog post.

You can use the program as follows:

$ cat somefile | splitter 16224-16482

And that is all that there is to it. You will need Haskell to install it. Just:

$ cabal install splitter

And you are done. I hope that you find this program useful.

How to run script as another user without password?

try running:

su -c "Your command right here" -s /bin/sh username

This will run the command as username given that you have permissions to sudo as that user.

How to make a transparent border using CSS?

Using the :before pseudo-element,
CSS3's border-radius,
and some transparency is quite easy:

LIVE DEMO

enter image description here

<div class="circle"></div>

CSS:

.circle, .circle:before{
  position:absolute;
  border-radius:150px;  
}
.circle{  
  width:200px;
  height:200px;
  z-index:0;
  margin:11%;
  padding:40px;
  background: hsla(0, 100%, 100%, 0.6);   
}
.circle:before{
  content:'';
  display:block;
  z-index:-1;  
  width:200px;
  height:200px;

  padding:44px;
  border: 6px solid hsla(0, 100%, 100%, 0.6);
  /* 4px more padding + 6px border = 10 so... */  
  top:-10px;
  left:-10px; 
}

The :before attaches to our .circle another element which you only need to make (ok, block, absolute, etc...) transparent and play with the border opacity.

How to parse XML to R data frame

Use xpath more directly for both performance and clarity.

time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"

df <- data.frame(
    latitude=data[["number(//point/@latitude)"]],
    longitude=data[["number(//point/@longitude)"]],
    start_valid_time=sapply(data[time_path], xmlValue),
    hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))

leading to

> head(df, 2)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2014-02-14T18:00:00-05:00                 60
2    29.81    -82.42 2014-02-14T19:00:00-05:00                 55

Relational Database Design Patterns?

Design patterns aren't trivially reusable solutions.

Design patterns are reusable, by definition. They're patterns you detect in other good solutions.

A pattern is not trivially reusable. You can implement your down design following the pattern however.

Relational design patters include things like:

  1. One-to-Many relationships (master-detail, parent-child) relationships using a foreign key.

  2. Many-to-Many relationships with a bridge table.

  3. Optional one-to-one relationships managed with NULLs in the FK column.

  4. Star-Schema: Dimension and Fact, OLAP design.

  5. Fully normalized OLTP design.

  6. Multiple indexed search columns in a dimension.

  7. "Lookup table" that contains PK, description and code value(s) used by one or more applications. Why have code? I don't know, but when they have to be used, this is a way to manage the codes.

  8. Uni-table. [Some call this an anti-pattern; it's a pattern, sometimes it's bad, sometimes it's good.] This is a table with lots of pre-joined stuff that violates second and third normal form.

  9. Array table. This is a table that violates first normal form by having an array or sequence of values in the columns.

  10. Mixed-use database. This is a database normalized for transaction processing but with lots of extra indexes for reporting and analysis. It's an anti-pattern -- don't do this. People do it anyway, so it's still a pattern.

Most folks who design databases can easily rattle off a half-dozen "It's another one of those"; these are design patterns that they use on a regular basis.

And this doesn't include administrative and operational patterns of use and management.

How to draw rounded rectangle in Android UI?

I think, this is you exactly needed.

Here drawable(xml) file that creates rounded rectangle. round_rect_shape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ffffff" />

    <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp" />

</shape>

Here layout file: my_layout.xml

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/round_rect_shape"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Something text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ff0000" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>
</LinearLayout>

-> In the above code, LinearLayout having the background(That is the key role to place to create rounded rectangle). So you can place any view like TextView, EditText... in that LinearLayout to see background as round rectangle for all.

Rollback to an old Git commit in a public repo

Want HEAD detached mode?

If you wish to rollback X time to a certain commit with a DETACHED HEAD (meaning you can't mess up anything), then by all means, use the following:

(replace X with how many commits you wish to go back)

git checkout HEAD~X

I.E. to go back one commit:

git checkout HEAD~1

HTTP Status 405 - Method Not Allowed Error for Rest API

@Produces({"text/plain","application/xml","application/json"}) change this to @Produces("text/plain") and try,

Django Admin - change header 'Django administration' text

Hope am not too late to the party, The easiest would be to edit the admin.py file.

admin.site.site_header = 'your_header'
admin.site.site_title = 'site_title'
admin.site.index_title = 'index_title'

The name 'ConfigurationManager' does not exist in the current context

For a sanity check, try creating a new Web Application Project, open the code behind for the Default.aspx page. Add a line in Page_Load to access your connection string.

It should have System.Configuration added as reference by default. You should also see the using statement at the top of your code file already.

My code behind file now looks like this and compiles with no problems.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace WebApplication1
{
  public partial class _Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      string connString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
    }
  }
}

This assumes I have a connection string in my web.config with a name equal to "MyConnectionStringName" like so...

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="MyConnectionStringName"
            connectionString="Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Yeah, it's elementary I know. But if you don't have any better ideas sometimes it helps to check against something really simple that you know should work.

Print Combining Strings and Numbers

Yes there is. The preferred syntax is to favor str.format over the deprecated % operator.

print "First number is {} and second number is {}".format(first, second)

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

Best way to implement multi-language/globalization in large .NET project

Standard resource files are easier. However, if you have any language dependent data such as lookup tables then you will have to manage two resource sets.

I haven't done it, but in my next project I would implement a database resource provider. I found how to do it on MSDN:

http://msdn.microsoft.com/en-us/library/aa905797.aspx

I also found this implementation:

DBResource Provider

Add a duration to a moment (moment.js)

For people having a startTime (like 12h:30:30) and a duration (value in minutes like 120), you can guess the endTime like so:

const startTime = '12:30:00';
const durationInMinutes = '120';

const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');

// endTime is equal to "14:30"

SSH library for Java

The Java Secure Channel (JSCH) is a very popular library, used by maven, ant and eclipse. It is open source with a BSD style license.

Using CSS in Laravel views?

Since Laravel 5 the HTML class is not included by default anymore.

If you're using Form or HTML helpers, you will see an error stating class 'Form' not found or class 'Html' not found. The Form and HTML helpers have been deprecated in Laravel 5.0; however, there are community-driven replacements such as those maintained by the Laravel Collective.

You can make use of the following line to include your CSS or JS files:

<link href="{{ URL::asset('css/base.css') }}" rel="stylesheet">
<link href="{{ URL::asset('js/project.js') }}" rel="script">

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

How to read XML response from a URL in java?

do it with the following code:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document doc = builder.parse("/home/codefelix/IdeaProjects/Gradle/src/main/resources/static/Employees.xml");
        NodeList namelist = (NodeList) doc.getElementById("1");

        for (int i = 0; i < namelist.getLength(); i++) {
            Node p = namelist.item(i);

            if (p.getNodeType() == Node.ELEMENT_NODE) {
                Element person = (Element) p;
                NodeList id = (NodeList) person.getElementsByTagName("Employee");
                NodeList nodeList = person.getChildNodes();
                List<EmployeeDto> employeeDtoList=new ArrayList();

                for (int j = 0; j < nodeList.getLength(); j++) {
                    Node n = nodeList.item(j);

                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element naame = (Element) n;
                        System.out.println("Employee" + id + ":" + naame.getTagName() + "=" +naame.getTextContent());
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Count distinct value pairs in multiple columns in SQL

You can also do something like:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

Catch browser's "zoom" event in JavaScript

According to MDN, "matchMedia" is the proper way to do this https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Monitoring_screen_resolution_or_zoom_level_changes

it's a bit finicky because each instance can only watch one MQ at a time, so if you're interested in any zoom level change you need to make a bunch of matchers.. but since the browser is in charge to emitting the events it's probably still more performant than polling, and you could throttle or debounce the callback or pin it to an animation frame or something - here's an implementation that seems pretty snappy, feel free to swap in _throttle or whatever if you're already depending on that.

Run the code snippet and zoom in and out in your browser, note the updated value in the markup - I only tested this in Firefox! lemme know if you see any issues.

_x000D_
_x000D_
const el = document.querySelector('#dppx')_x000D_
_x000D_
if ('matchMedia' in window) {_x000D_
  function observeZoom(cb, opts) {_x000D_
    opts = {_x000D_
      // first pass for defaults - range and granularity to capture all the zoom levels in desktop firefox_x000D_
      ceiling: 3,_x000D_
      floor: 0.3,_x000D_
      granularity: 0.05,_x000D_
      ...opts_x000D_
    }_x000D_
    const precision = `${opts.granularity}`.split('.')[1].length_x000D_
_x000D_
    let val = opts.floor_x000D_
    const vals = []_x000D_
    while (val <= opts.ceiling) {_x000D_
      vals.push(val)_x000D_
      val = parseFloat((val + opts.granularity).toFixed(precision))_x000D_
    }_x000D_
_x000D_
    // construct a number of mediamatchers and assign CB to all of them_x000D_
    const mqls = vals.map(v => matchMedia(`(min-resolution: ${v}dppx)`))_x000D_
_x000D_
    // poor person's throttle_x000D_
    const throttle = 3_x000D_
    let last = performance.now()_x000D_
    mqls.forEach(mql => mql.addListener(function() {_x000D_
      console.debug(this, arguments)_x000D_
      const now = performance.now()_x000D_
      if (now - last > throttle) {_x000D_
        cb()_x000D_
        last = now_x000D_
      }_x000D_
    }))_x000D_
  }_x000D_
_x000D_
  observeZoom(function() {_x000D_
    el.innerText = window.devicePixelRatio_x000D_
  })_x000D_
} else {_x000D_
  el.innerText = 'unable to observe zoom level changes, matchMedia is not supported'_x000D_
}
_x000D_
<div id='dppx'>--</div>
_x000D_
_x000D_
_x000D_

Writing outputs to log file and console

I have found a way to get the desired output. Though it may be somewhat unorthodox way. Anyways here it goes. In the redir.env file I have following code:

#####redir.env#####    
export LOG_FILE=log.txt

      exec 2>>${LOG_FILE}

    function log {
     echo "$1">>${LOG_FILE}
    }

    function message {
     echo "$1"
     echo "$1">>${LOG_FILE}
    }

Then in the actual script I have the following codes:

#!/bin/sh 
. redir.env
echo "Echoed to console only"
log "Written to log file only"
message "To console and log"
echo "This is stderr. Written to log file only" 1>&2

Here echo outputs only to console, log outputs to only log file and message outputs to both the log file and console.

After executing the above script file I have following outputs:

In console

In console
Echoed to console only
To console and log

For the Log file

In Log File Written to log file only
This is stderr. Written to log file only
To console and log

Hope this help.

How to change credentials for SVN repository in Eclipse?

On Mac OS X, go to folder /$HOME (/Users/{user home}/). You will see file '.eclipse_keyring'. Remove it. All saved credentials will be lost.

What are the sizes used for the iOS application splash screen?

Update 2020 - Xcode 11

In Xcode 11, you can provide only one image with 1x, 2x, and 3x scales then set it in LaunchScreen.storyboard to fill up the screen and everything goes well!

For Example: (1242pt x 2688pt @1x)

This is the portrait screen size of iPhone 11 Pro Max which is the large iPhone screen size yet so it will give you high-quality splash screen on all iOS devices.

Update 2019 - iOS 12

I have collected all sizes needed for the splash screen. All u need is to just drag images with these sizes and drop them, Xcode will place each size in the right place.

Good luck.

Sizes :

320×480

640×960

640×1136

750×1334

768×1004

768×1024

828×1792

1024×748

1024×768

1125×2436

1242×2208

1242×2688

1536×2008

1536×2048

1792×828

2048×1496

2048×1536

2208×1242

2436×1125

2688×1242

Note

Count of required images are 26 images but there are 6 duplicated sizes so u will find the above sizes are only 20.

How to update maven repository in Eclipse?

In newer versions of Eclipse that use the M2E plugin it is:

Right-click on your project(s) --> Maven --> Update Project...

In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")

How to remove a build from itunes connect?

In our case, deletion was not possible due to already having an app that we were in pre-release. The fix was not to delete but rather to edit each section, including version number, that needed to change for the new candidate.

Change background color on mouseover and remove it after mouseout

Try this , its working and simple

HTML

?????????????????????<html>
<head></head>
<body>
    <div class="forum">
        test
    </div>
</body>
</html>?????????????????????????????????????????????

Javascript

$(document).ready(function() {
    var colorOrig=$(".forum").css('background-color');
    $(".forum").hover(
    function() {
        //mouse over
        $(this).css('background', '#ff0')
    }, function() {
        //mouse out
        $(this).css('background', colorOrig)
    });
});?

css ?

.forum{
    background:#f0f;
}?

live demo

http://jsfiddle.net/caBzg/

Resource u'tokenizers/punkt/english.pickle' not found

For me it got solved by using "nltk:"

http://www.nltk.org/howto/data.html

Failed loading english.pickle with nltk.data.load

sent_tokenizer=nltk.data.load('nltk:tokenizers/punkt/english.pickle')

Add CSS box shadow around the whole DIV

Yes, don't offset vertically or horizontally, and use a relatively large blur radius: fiddle

Also, you can use multiple box-shadows if you separate them with a comma. This will allow you to fine-tune where they blur and how much they extend. The example I provide is indistinguishable from a large outline, but it can be fine-tuned significantly more: fiddle

You missed the last and most relevant property of box-shadow, which is spread-distance. You can specify a value for how much the shadow expands or contracts (makes my second example obsolete): fiddle

The full property list is:

box-shadow: [horizontal-offset] [vertical-offset] [blur-radius] [spread-distance] [color] inset?

But even better, read through the spec.

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

The way without re-inserting all entries into the new map should be the fastest it won't because HashMap.clone internally performs rehash as well.

Map<String, Column> newColumnMap = originalColumnMap.clone();
newColumnMap.replaceAll((s, c) -> new Column(c));

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

Check if a file is executable

Also seems nobody noticed -x operator on symlinks. A symlink (chain) to a regular file (not classified as executable) fails the test.

jQuery delete confirmation box

Try with this JSFiddle DEMO : http://jsfiddle.net/2yEtK/3/

Jquery Code:

$("a.removeRecord").live("click",function(event){
   event.stopPropagation();
   if(confirm("Do you want to delete?")) {
    this.click;
       alert("Ok");
   }
   else
   {
       alert("Cancel");
   }       
   event.preventDefault();

});

Remove/ truncate leading zeros by javascript/jquery

You can use a regular expression that matches zeroes at the beginning of the string:

s = s.replace(/^0+/, '');

Get UTC time and local time from NSDate object

a date is independant of any timezone, so use a Dateformatter and attach a timezone for display:

swift:

let date = NSDate()
let dateFormatter = NSDateFormatter()
let timeZone = NSTimeZone(name: "UTC")

dateFormatter.timeZone = timeZone

println(dateFormatter.stringFromDate(date))

objC:

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];

[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:timeZone];       
NSLog(@"%@", [dateFormatter stringFromDate:date]);

QR Code encoding and decoding using zxing

this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters

package com.mypackage.qr;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;

public class CreateQR {

public static void main(String[] args)
{
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
        // Convert a string to UTF-8 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data;
    try {
        data = new String(b, "UTF-8");
        // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 100;
        int w = 100;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            matrix = writer.encode(data,
            com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
        } catch (com.google.zxing.WriterException e) {
            System.out.println(e.getMessage());
        }

        // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
                String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }
}

}

Python Pandas - Find difference between two data frames

import pandas as pd
# given
df1 = pd.DataFrame({'Name':['John','Mike','Smith','Wale','Marry','Tom','Menda','Bolt','Yuswa',],
    'Age':[23,45,12,34,27,44,28,39,40]})
df2 = pd.DataFrame({'Name':['John','Smith','Wale','Tom','Menda','Yuswa',],
    'Age':[23,12,34,44,28,40]})

# find elements in df1 that are not in df2
df_1notin2 = df1[~(df1['Name'].isin(df2['Name']) & df1['Age'].isin(df2['Age']))].reset_index(drop=True)

# output:
print('df1\n', df1)
print('df2\n', df2)
print('df_1notin2\n', df_1notin2)

# df1
#     Age   Name
# 0   23   John
# 1   45   Mike
# 2   12  Smith
# 3   34   Wale
# 4   27  Marry
# 5   44    Tom
# 6   28  Menda
# 7   39   Bolt
# 8   40  Yuswa
# df2
#     Age   Name
# 0   23   John
# 1   12  Smith
# 2   34   Wale
# 3   44    Tom
# 4   28  Menda
# 5   40  Yuswa
# df_1notin2
#     Age   Name
# 0   45   Mike
# 1   27  Marry
# 2   39   Bolt

animating addClass/removeClass with jQuery

Since you are not worried about IE, why not just use css transitions to provide the animation and jQuery to change the classes. Live example: http://jsfiddle.net/tw16/JfK6N/

#someDiv{
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

How to change XAMPP apache server port?

To answer the original question:

To change the XAMPP Apache server port here the procedure :

1. Choose a free port number

The default port used by Apache is 80.

Take a look to all your used ports with Netstat (integrated to XAMPP Control Panel).

Screenshot of xampp control netstat

Then you can see all used ports and here we see that the 80port is already used by System.

screenshot netstat port 80

Choose a free port number (8012, for this exemple).

2. Edit the file "httpd.conf"

This file should be found in C:\xampp\apache\conf on Windows or in bin/apache for Linux.:

Listen 80
ServerName localhost:80

Replace them by:

Listen 8012
ServerName localhost:8012

Save the file.

Access to : http://localhost:8012 for check if it's work.

If not, you must to edit the http-ssl.conf file as explain in step 3 below. ?

3. Edit the file "http-ssl.conf"

This file should be found in C:\xampp\apache\conf\extra on Windows or see this link for Linux.

Locate the following lines:

Listen 443
<VirtualHost _default_:443>
ServerName localhost:443

Replace them by with a other port number (8013 for this example) :

Listen 8013
<VirtualHost _default_:8013>
ServerName localhost:8013

Save the file.

Restart the Apache Server.

Access to : http://localhost:8012 for check if it's work.

4. Configure XAMPP Apache server settings

If your want to access localhost without specify the port number in the URL
http://localhost instead of http://localhost:8012.

  • Open Xampp Control Panel
  • Go to Config ? Service and Port Settings ? Apache
  • Replace the Main Port and SSL Port values ??with those chosen (e.g. 8012 and 8013).
  • Save Service settings
  • Save Configuration of Control Panel
  • Restart the Apache Server xampp apache setting port It should work now.

4.1. Web browser configuration

If this configuration isn't hiding port number in URL it's because your web browser is not configured for. See : Tools ? Options ? General ? Connection Settings... will allow you to choose different ports or change proxy settings.

4.2. For the rare cases of ultimate bad luck

If step 4 and Web browser configuration are not working for you the only way to do this is to change back to 80, or to install a listener on port 80 (like a proxy) that redirects all your traffic to port 8012.

To answer your problem :

If you still have this message in Control Panel Console :

Apache Started [Port 80]

  • Find location of xampp-control.exe file (probably in C:\xampp)
  • Create a file XAMPP.INI in that directory (so XAMPP.ini and xampp-control.exe are in the same directory)

Put following lines in the XAMPP.INI file:

[PORTS]
apache = 8012

Now , you will always get:

Apache started [Port 8012]

Please note that, this is for display purpose only. It has no relation with your httpd.conf.

How to write multiple line string using Bash with variables?

Below mechanism helps in redirecting multiple lines to file. Keep complete string under " so that we can redirect values of the variable.

#!/bin/bash
kernel="2.6.39"
echo "line 1, ${kernel}
line 2," > a.txt
echo 'line 2, ${kernel}
line 2,' > b.txt

Content of a.txt is

line 1, 2.6.39
line 2,

Content of b.txt is

line 2, ${kernel}
line 2,

Tools to search for strings inside files without indexing

I like AstroGrep. The results are shown in a list. A click on a row shows you the whole line as a preview highlighting the hit. It seems to be quite fast, lean and it is free. Tested on Windows 7, 8, 10 and Windows Server 2008 R2. Allows regular expressions.

Latest AstroGrep Screenshot

AstroGrep is a Microsoft Windows GUI File Searching (grep) utility. Its features include regular expressions, versatile printing options, stores most recent used paths and has a "context" feature which is very nice for looking at source code

Reference: AstroGrep

How can I get this ASP.NET MVC SelectList to work?

If you want to pass some random text to your DropDownList, for example --Select-- you can easy do this using this code:

@Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "--Select--", new { @class = "form-control" })

Combine Regexp?

Combining the regex for the fourth option with any of the others doesn't work within one regex. 4 + 1 would mean either the string starts with @ or doesn't contain @ at all. You're going to need two separate comparisons to do that.

How do I autoindent in Netbeans?

Select the lines you want to reformat (indenting), then hit Alt+Shift+F. Only the selected lines will be reformatted.

Why do python lists have pop() but not push()

Ok, personal opinion here, but Append and Prepend imply precise positions in a set.

Push and Pop are really concepts that can be applied to either end of a set... Just as long as you're consistent... For some reason, to me, Push() seems like it should apply to the front of a set...

How can I apply a function to every row/column of a matrix in MATLAB?

You may want the more obscure Matlab function bsxfun. From the Matlab documentation, bsxfun "applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled."

@gnovice stated above that sum and other basic functions already operate on the first non-singleton dimension (i.e., rows if there's more than one row, columns if there's only one row, or higher dimensions if the lower dimensions all have size==1). However, bsxfun works for any function, including (and especially) user-defined functions.

For example, let's say you have a matrix A and a row vector B. E.g., let's say:

A = [1 2 3;
     4 5 6;
     7 8 9]
B = [0 1 2]

You want a function power_by_col which returns in a vector C all the elements in A to the power of the corresponding column of B.

From the above example, C is a 3x3 matrix:

C = [1^0 2^1 3^2;
     4^0 5^1 6^2;
     7^0 8^1 9^2]

i.e.,

C = [1 2 9;
     1 5 36;
     1 8 81]

You could do this the brute force way using repmat:

C = A.^repmat(B, size(A, 1), 1)

Or you could do this the classy way using bsxfun, which internally takes care of the repmat step:

C = bsxfun(@(x,y) x.^y, A, B)

So bsxfun saves you some steps (you don't need to explicitly calculate the dimensions of A). However, in some informal tests of mine, it turns out that repmat is roughly twice as fast if the function to be applied (like my power function, above) is simple. So you'll need to choose whether you want simplicity or speed.

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Very lightweight solution could be using KeyboardAnimator.

project got the sample implementation, documentation is still in progress...

Appropriate usage :: It's have a specific implementation for UITextField & UITextView

Limitation:: It's fully on objective-c, swift version will be available soon.

Python: Converting string into decimal number

If you are converting string to float:

import re
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
float_values = [float(re.search(r'\d+.\d+',number).group()) for number in A1]
print(float_values)
>>> [29.0, 65.2, 75.2]

Simple GUI Java calculator

What you need is something that calculates the result of the infix notated calculation, have a look at the Shunting-Yard Algorithm.

There's an example in C++ on Wikipedia's page, but it shouldn't be too hard to implement it in Java.
And since it's the primary function of your calculator, I would advise you to not grab some codez from the Web in this Case (except all you want to do is building calculator GUIs).

How to check if a column exists in a SQL Server table?

I'd prefer INFORMATION_SCHEMA.COLUMNS over a system table because Microsoft does not guarantee to preserve the system tables between versions. For example, dbo.syscolumns does still work in SQL 2008, but it's deprecated and could be removed at any time in future.

Change the maximum upload file size

You need to set the value of upload_max_filesize and post_max_size in your php.ini :

; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M

After modifying php.ini file(s), you need to restart your HTTP server to use new configuration.

If you can't change your php.ini, you're out of luck. You cannot change these values at run-time; uploads of file larger than the value specified in php.ini will have failed by the time execution reaches your call to ini_set.

See the Description of core php.ini directives.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

Calculate number of hours between 2 dates in PHP

To provide another method for DatePeriod when using the UTC or GMT timezone.

Count Hours https://3v4l.org/Mu3HD

$start = new \DateTime('2006-04-12T12:30:00');
$end = new \DateTime('2006-04-14T11:30:00');

//determine what interval should be used - can change to weeks, months, etc
$interval = new \DateInterval('PT1H');

//create periods every hour between the two dates
$periods = new \DatePeriod($start, $interval, $end);

//count the number of objects within the periods
$hours = iterator_count($periods);
echo $hours . ' hours'; 

//difference between Unix Epoch
$diff = $end->getTimestamp() - $start->getTimestamp();
$hours = $diff / ( 60 * 60 );
echo $hours . ' hours (60 * 60)';

//difference between days
$diff = $end->diff($start);
$hours = $diff->h + ($diff->days * 24);
echo $hours . ' hours (days * 24)';

Result

47 hours (iterator_count)
47 hours (60 * 60)
47 hours (days * 24)

Count Hours with Daylight Savings https://3v4l.org/QBQUB

Please be advised that DatePeriod excludes an hour for DST but does not add another hour when DST ends. So its usage is subjective to your desired outcome and date range.

See the current bug report

//set timezone to UTC to disregard daylight savings
date_default_timezone_set('America/New_York');

$interval = new \DateInterval('PT1H');

//DST starts Apr. 2nd 02:00 and moves to 03:00
$start = new \DateTime('2006-04-01T12:00:00');  
$end = new \DateTime('2006-04-02T12:00:00');

$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';

//DST ends Oct. 29th 02:00 and moves to 01:00
$start = new \DateTime('2006-10-28T12:00:00');
$end = new \DateTime('2006-10-29T12:00:00'); 

$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';

Result

#2006-04-01 12:00 EST to 2006-04-02 12:00 EDT
23 hours (iterator_count)
//23 hours (60 * 60)
//24 hours (days * 24)

#2006-10-28 12:00 EDT to 2006-10-29 12:00 EST
24 hours (iterator_count)
//25 hours (60 * 60)
//24 hours (days * 24)

#2006-01-01 12:00 EST to 2007-01-01 12:00 EST
8759 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)

//------

#2006-04-01 12:00 UTC to 2006-04-02 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)

#2006-10-28 12:00 UTC to 2006-10-29 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)

#2006-01-01 12:00 UTC to 2007-01-01 12:00 UTC
8760 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)

How to extract svg as file from web page

You can download individual ones from their site like @mayerdesign has stated or you can click on the download link on the left and you can download the whole pack.

FULL PACK

Get contentEditable caret index position

Try this:

Caret.js Get caret postion and offset from text field

https://github.com/ichord/Caret.js

demo: http://ichord.github.com/Caret.js

How to toggle font awesome icon on click?

<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li> </ul>

//Jquery

$(document).ready(function() {
    $('li').click(function() {
      $('i').toggleClass('fa-plus-square fa-minus-square');
    });
  }); 

JSFiddle

jQuery - Disable Form Fields

$('input, select').attr('disabled', 'disabled');

Safe Area of Xcode 9

Apple introduced the topLayoutGuide and bottomLayoutGuide as properties of UIViewController way back in iOS 7. They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar. These layout guides are deprecated in iOS 11 and replaced by a single safe area layout guide.

Refer link for more information.

Linking static libraries to other static libraries

Note before you read the rest: The shell script shown here is certainly not safe to use and well tested. Use at your own risk!

I wrote a bash script to accomplish that task. Suppose your library is lib1 and the one you need to include some symbols from is lib2. The script now runs in a loop, where it first checks which undefined symbols from lib1 can be found in lib2. It then extracts the corresponding object files from lib2 with ar, renames them a bit, and puts them into lib1. Now there may be more missing symbols, because the stuff you included from lib2 needs other stuff from lib2, which we haven't included yet, so the loop needs to run again. If after some passes of the loop there are no changes anymore, i.e. no object files from lib2 added to lib1, the loop can stop.

Note, that the included symbols are still reported as undefined by nm, so I'm keeping track of the object files, that were added to lib1, themselves, in order to determine whether the loop can be stopped.

#! /bin/bash

lib1="$1"
lib2="$2"

if [ ! -e $lib1.backup ]; then
    echo backing up
    cp $lib1 $lib1.backup
fi

remove_later=""

new_tmp_file() {
    file=$(mktemp)
    remove_later="$remove_later $file"
    eval $1=$file
}
remove_tmp_files() {
    rm $remove_later
}
trap remove_tmp_files EXIT

find_symbols() {
    nm $1 $2 | cut -c20- | sort | uniq 
}

new_tmp_file lib2symbols
new_tmp_file currsymbols

nm $lib2 -s --defined-only > $lib2symbols

prefix="xyz_import_"
pass=0
while true; do
    ((pass++))
    echo "Starting pass #$pass"
    curr=$lib1
    find_symbols $curr "--undefined-only" > $currsymbols
    changed=0
    for sym in $(cat $currsymbols); do
        for obj in $(egrep "^$sym in .*\.o" $lib2symbols | cut -d" " -f3); do
            echo "  Found $sym in $obj."
            if [ -e "$prefix$obj" ]; then continue; fi
            echo "    -> Adding $obj to $lib1"
            ar x $lib2 $obj
            mv $obj "$prefix$obj"
            ar -r -s $lib1 "$prefix$obj"
            remove_later="$remove_later $prefix$obj"
            ((changed=changed+1))
        done
    done
    echo "Found $changed changes in pass #$pass"

    if [[ $changed == 0 ]]; then break; fi
done

I named that script libcomp, so you can call it then e.g. with

./libcomp libmylib.a libwhatever.a

where libwhatever is where you want to include symbols from. However, I think it's safest to copy everything into a separate directory first. I wouldn't trust my script so much (however, it worked for me; I could include libgsl.a into my numerics library with that and leave out that -lgsl compiler switch).

Javascript setInterval not working

Change setInterval("func",10000) to either setInterval(funcName, 10000) or setInterval("funcName()",10000). The former is the recommended method.

How do I make Java register a string input with spaces?

Instead of

Scanner in = new Scanner(System.in);
String question;
question = in.next();

Type in

Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();

This should be able to take spaces as input.

How to use ADB in Android Studio to view an SQLite DB

You can use a very nice tool called Stetho by adding this to build.gradle file:

compile 'com.facebook.stetho:stetho:1.4.1'

And initialized it inside your Application or Activity onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Stetho.initializeWithDefaults(this);
    setContentView(R.layout.activity_main);
}

Then you can view the db records in chrome in the address:

chrome://inspect/#devices

For more details you can read my post: How to view easily your db records

Identify if a string is a number

If you want to know if a string is a number, you could always try parsing it:

var numberString = "123";
int number;

int.TryParse(numberString , out number);

Note that TryParse returns a bool, which you can use to check if your parsing succeeded.

Cannot make Project Lombok work on Eclipse

I ran into this problem due to the missing:

-vmargs -javaagent:lombok.jar -Xbootclasspath/a:lombok.jar

as well. What is not explicitly said neither here nor in the Lombok popup message, and was not obvious to me as someone who never before had to fiddle with the eclipse.ini, is that you are NOT supposed to add that line, but instead add the last two parts of that line after the first part, which is already in the eclipse.ini file. To better illustrate, the end of the file should look something like this (bold is what matters for Lombok, the rest might be different for you):

-vm
C:/Program Files/Java/jdk1.7.0_02/bin
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx384m
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar

How do I write a compareTo method which compares objects?

If you using compare To method of the Comparable interface in any class. This can be used to arrange the string in Lexicographically.

public class Student() implements Comparable<Student>{

public int compareTo(Object obj){
if(this==obj){
    return 0;
}
if(obj!=null){
    String objName = ((Student)obj).getName();
    return this.name.comapreTo.(objName);
}
}

How to move/rename a file using an Ansible task on a remote system

I know it's a YEARS old topic, but I got frustrated and built a role for myself to do exactly this for an arbitrary list of files. Extend as you see fit:

main.yml

- name: created destination directory
  file:
    path: /path/to/directory
    state: directory
    mode: '0750'
- include_tasks: move.yml
  loop:
    - file1
    - file2
    - file3

move.yml

- name: stat the file
  stat:
    path: {{ item }}
  register: my_file

- name: hard link the file into directory
  file:
    src: /original/path/to/{{ item }}
    dest: /path/to/directory/{{ item }}
    state: hard
  when: my_file.stat.exists

- name: Delete the original file
  file:
    path: /original/path/to/{{ item }}
    state: absent
  when: my_file.stat.exists

Note that hard linking is preferable to copying here, because it inherently preserves ownership and permissions (in addition to not consuming more disk space for a second copy of the file).

Setting attribute disabled on a SPAN element does not prevent click events

The best method is to wrap the span inside a button and disable the button

_x000D_
_x000D_
$("#buttonD").click(function(){_x000D_
  alert("button clicked");_x000D_
})_x000D_
_x000D_
$("#buttonS").click(function(){_x000D_
  alert("span clicked");_x000D_
})
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<button class="btn btn-success" disabled="disabled" id="buttonD">_x000D_
    <span>Disabled button</span>_x000D_
</button>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
 <span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>
_x000D_
_x000D_
_x000D_

How to pass an object from one activity to another on Android

It is impossible to serialize any type of object. For Example you can not serialize delegate methods or interfaces that carry code instead of data. So I have written a 'Box' class you can use to pass any type of data without Serialization.

1- for putting Data to Intent Use:

Intent I = new Intent(this, YourActivity.class);
CustomClass Date = new CustomClass();
Box.Add(I, "Name", Data);

2- for retrieving Data from Intent:

CustomClass Data = Box.Get(getIntent(), "Name");

3- for removing data after use, add this method to your activity:

@Override
protected void onDestroy() {
    Box.Remove(getIntent());
    super.onDestroy();
}

4- and add this code to your project:

package ir.namirasoft.Utility;

import android.content.Intent;

import java.util.HashMap;
import java.util.Vector;

public class Box {
    // Number
    private static int Number = 1;

    public static int NextNumber() {
        return Number++;
    }

    //
    private static String _Intent_Identifier = "_Intent_Identifier";
    private static HashMap<Integer, Vector<Integer>> DeleteList = new HashMap<Integer, Vector<Integer>>();
    private static HashMap<Integer, HashMap<String, Object>> ObjectList = new HashMap<Integer, HashMap<String, Object>>();

    public static int GetIntent_Identifier(Intent I) {
        int Intent_Identifier = I.getIntExtra(_Intent_Identifier, 0);
        if (Intent_Identifier == 0)
            I.putExtra(_Intent_Identifier, Intent_Identifier = NextNumber());
        return Intent_Identifier;
    }

    public static void Add(Intent I, String Name, Object O) {
        int Intent_Identifier = GetIntent_Identifier(I);
        synchronized (ObjectList) {
            if (!ObjectList.containsKey(Intent_Identifier))
                ObjectList.put(Intent_Identifier, new HashMap<String, Object>());
            ObjectList.get(Intent_Identifier).put(Name, O);
        }
    }

    public static <T> T Get(Intent I, String Name) {
        int Intent_Identifier = GetIntent_Identifier(I);
        synchronized (DeleteList) {
            DeleteList.remove(Intent_Identifier);
        }
        return (T) ObjectList.get(Intent_Identifier).get(Name);
    }

    public static void Remove(final Intent I) {
        final int Intent_Identifier = GetIntent_Identifier(I);
        final int ThreadID = NextNumber();
        synchronized (DeleteList) {
            if (!DeleteList.containsKey(Intent_Identifier))
                DeleteList.put(Intent_Identifier, new Vector<Integer>());
            DeleteList.get(Intent_Identifier).add(ThreadID);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException e) {
                }
                synchronized (DeleteList) {
                    if (DeleteList.containsKey(Intent_Identifier))
                        if (DeleteList.get(Intent_Identifier).contains(ThreadID))
                            synchronized (ObjectList) {
                                ObjectList.remove(Intent_Identifier);
                            }
                }
            }
        }).start();
    }
}

** Box class is Thread-Safe.

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

Pan & Zoom Image

@ Merk

For ur solution insted of lambda expression you can use following code:

//var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
        TranslateTransform tt = null;
        TransformGroup transformGroup = (TransformGroup)grid.RenderTransform;
        for (int i = 0; i < transformGroup.Children.Count; i++)
        {
            if (transformGroup.Children[i] is TranslateTransform)
                tt = (TranslateTransform)transformGroup.Children[i];
        }

this code can be use as is for .Net Frame work 3.0 or 2.0

Hope It helps you :-)

Global Git ignore

on windows subsystem for linux I had to navigate to the subsystem root by cd ~/ then touch .gitignore and then update the global gitignore configuration in there.

I hope it helps someone.

Add new item in existing array in c#.net

That could be a solution;

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

But for dynamic sized array I would prefer list too.

The preferred way of creating a new element with jQuery

If #box is empty, nothing, but if it's not these do very different things. The former will add a div as the last child node of #box. The latter completely replaces the contents of #box with a single empty div, text and all.

Splitting a C++ std::string using tokens, e.g. ";"

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

How to use environment variables in docker compose

  1. Create a template.yml, which is your docker-compose.yml with environment variable.
  2. Suppose your environment variables are in a file 'env.sh'
  3. Put the below piece of code in a sh file and run it.

source env.sh; rm -rf docker-compose.yml; envsubst < "template.yml" > "docker-compose.yml";

A new file docker-compose.yml will be generated with the correct values of environment variables.

Sample template.yml file:

oracledb:
        image: ${ORACLE_DB_IMAGE}
        privileged: true
        cpuset: "0"
        ports:
                - "${ORACLE_DB_PORT}:${ORACLE_DB_PORT}"
        command: /bin/sh -c "chmod 777 /tmp/start; /tmp/start"
        container_name: ${ORACLE_DB_CONTAINER_NAME}

Sample env.sh file:

#!/bin/bash 
export ORACLE_DB_IMAGE=<image-name> 
export ORACLE_DB_PORT=<port to be exposed> 
export ORACLE_DB_CONTAINER_NAME=ORACLE_DB_SERVER

CustomErrors mode="Off"

I have just dealt with similar issue. In my case the default site asp.net version was 1.1 while i was trying to start up a 2.0 web app. The error was pretty trivial, but it was not immediately clear why the custom errors would not go away, and runtime never wrote to event log. Obvious fix was to match the version in Asp.Net tab of IIS.

How to exit git log or git diff

You can press q to exit.

git hist is using a pager tool so you can scroll up and down the results before returning to the console.

Copy and Paste a set range in the next empty row

Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):

EDIT: edited for pasting values only based on comments below.

Private Sub CommandButton1_Click()
  Application.ScreenUpdating = False
  Dim copySheet As Worksheet
  Dim pasteSheet As Worksheet

  Set copySheet = Worksheets("Sheet1")
  Set pasteSheet = Worksheets("Sheet2")

  copySheet.Range("A3:E3").Copy
  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
  Application.CutCopyMode = False
  Application.ScreenUpdating = True
End Sub

case statement in SQL, how to return multiple variables?

In your case you would use two case staements, one for each value you want returned.

How to remove single character from a String

By the using replace method we can change single character of string.

string= string.replace("*", "");

How to uninstall Ruby from /usr/local?

If ruby was installed in the following way:

./configure --prefix=/usr/local
make
sudo make install

You can uninstall it in the following way:

Check installed ruby version; lets assume 2.1.2

wget http://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.bz2
bunzip ...
tar xfv ...
cd ruby-2.1.2
./configure --prefix=/usr/local
make
sudo checkinstall
  # will build deb or rpm package and try to install it

After installation, you can now remove the package and it will remove the directories/files/etc.

sudo rpm -e ruby # or dpkg -P ruby (for Debian-like systems)

There might be some artifacts left:

Removing ruby ...
  warning: while removing ruby, directory '/usr/local/lib/ruby/gems/2.1.0/gems' not empty so not removed.
  ...

Remove them manually.

How can I see CakePHP's SQL dump in the controller?

Try this:

$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);

http://api.cakephp.org/2.3/class-Model.html#_getDataSource

You will have to do this for each datasource if you have more than one though.

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The error says it all actually. Your configuration tells Nginx to listen on port 80 (HTTP) and use SSL. When you point your browser to http://localhost, it tries to connect via HTTP. Since Nginx expects SSL, it complains with the error.

The workaround is very simple. You need two server sections:

server {
  listen 80;

  // other directives...
}

server {
  listen 443;

  ssl on;
  // SSL directives...

  // other directives...
}

Select2 open dropdown on focus

Probably after the selection is made a select2-focus event is triggered.

The only way I found is a combination of select2-focus and select2-blur event and the jQuery one event handler.

So the first time the element get the focus, the select2 is opened for one time (because of one), when the element is blurred the one event handler is attached again and so on.

Code:

$('#test').select2({
    data: [{
        id: 0,
        text: "enhancement"
    }, {
        id: 1,
        text: "bug"
    }, {
        id: 2,
        text: "duplicate"
    }, {
        id: 3,
        text: "invalid"
    }, {
        id: 4,
        text: "wontfix"
    }],
    width: "300px"
}).one('select2-focus', select2Focus).on("select2-blur", function () {
    $(this).one('select2-focus', select2Focus)
})

function select2Focus() {
    $(this).select2('open');
}

Demo: http://jsfiddle.net/IrvinDominin/fnjNb/

UPDATE

To let the mouse click work you must check the event that fires the handler, it must fire the open method only if the event is focus

Code:

function select2Focus() {
    if (/^focus/.test(event.type)) {
        $(this).select2('open');
    }
}

Demo: http://jsfiddle.net/IrvinDominin/fnjNb/4/

UPDATE FOR SELECT2 V 4.0

select2 v 4.0 has changed its API's and dropped the custom events (see https://github.com/select2/select2/issues/1908). So it's necessary change the way to detect the focus on it.

Code:

$('.js-select').select2({
    placeholder: "Select",
    width: "100%"
})

$('.js-select').next('.select2').find('.select2-selection').one('focus', select2Focus).on('blur', function () {
    $(this).one('focus', select2Focus)
})

function select2Focus() {
    $(this).closest('.select2').prev('select').select2('open');
}

Demo: http://jsfiddle.net/IrvinDominin/xfmgte70/

How to remove a class from elements in pure JavaScript?

Given worked for me.

document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Why am I getting ImportError: No module named pip ' right after installing pip?

Just be sure that you have include python to windows PATH variable, then run python -m ensurepip

How to get correct timestamp in C#

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

to this:

String timeStamp = GetTimestamp(DateTime.Now);

Make a link in the Android browser start up my app?

I think you'll want to look at the <intent-filter> element of your Mainfest file. Specifically, take a look at the documentation for the <data> sub-element.

Basically, what you'll need to do is define your own scheme. Something along the lines of:

<intent-filter>
    <data android:scheme="anton" />
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" /> <--Not positive if this one is needed
    ...
</intent-filter>

Then you should be able to launch your app with links that begin with the anton: URI scheme.

nginx - read custom header from upstream server

Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}

How do you completely remove the button border in wpf?

You can use Hyperlink instead of Button, like this:

        <TextBlock>
            <Hyperlink TextDecorations="{x:Null}">
            <Image Width="16"
                   Height="16"
                   Margin="3"
                   Source="/YourProjectName;component/Images/close-small.png" />
            </Hyperlink>
        </TextBlock>

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

Return multiple fields as a record in PostgreSQL with PL/pgSQL

Don't use CREATE TYPE to return a polymorphic result. Use and abuse the RECORD type instead. Check it out:

CREATE FUNCTION test_ret(a TEXT, b TEXT) RETURNS RECORD AS $$
DECLARE 
  ret RECORD;
BEGIN
  -- Arbitrary expression to change the first parameter
  IF LENGTH(a) < LENGTH(b) THEN
      SELECT TRUE, a || b, 'a shorter than b' INTO ret;
  ELSE
      SELECT FALSE, b || a INTO ret;
  END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;

Pay attention to the fact that it can optionally return two or three columns depending on the input.

test=> SELECT test_ret('foo','barbaz');
             test_ret             
----------------------------------
 (t,foobarbaz,"a shorter than b")
(1 row)

test=> SELECT test_ret('barbaz','foo');
             test_ret             
----------------------------------
 (f,foobarbaz)
(1 row)

This does wreak havoc on code, so do use a consistent number of columns, but it's ridiculously handy for returning optional error messages with the first parameter returning the success of the operation. Rewritten using a consistent number of columns:

CREATE FUNCTION test_ret(a TEXT, b TEXT) RETURNS RECORD AS $$
DECLARE 
  ret RECORD;
BEGIN
  -- Note the CASTING being done for the 2nd and 3rd elements of the RECORD
  IF LENGTH(a) < LENGTH(b) THEN
      ret := (TRUE, (a || b)::TEXT, 'a shorter than b'::TEXT);
  ELSE
      ret := (FALSE, (b || a)::TEXT, NULL::TEXT);
   END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;

Almost to epic hotness:

test=> SELECT test_ret('foobar','bar');
   test_ret    
----------------
 (f,barfoobar,)
(1 row)

test=> SELECT test_ret('foo','barbaz');
             test_ret             
----------------------------------
 (t,foobarbaz,"a shorter than b")
(1 row)

But how do you split that out in to multiple rows so that your ORM layer of choice can convert the values in to your language of choice's native data types? The hotness:

test=> SELECT a, b, c FROM test_ret('foo','barbaz') AS (a BOOL, b TEXT, c TEXT);
 a |     b     |        c         
---+-----------+------------------
 t | foobarbaz | a shorter than b
(1 row)

test=> SELECT a, b, c FROM test_ret('foobar','bar') AS (a BOOL, b TEXT, c TEXT);
 a |     b     | c 
---+-----------+---
 f | barfoobar | 
(1 row)

This is one of the coolest and most underused features in PostgreSQL. Please spread the word.

Using str_replace so that it only acts on the first match?

$str = "/property/details&id=202&test=123#tab-6p";
$position = strpos($str,"&");
echo substr_replace($str,"?",$position,1);

Using substr_replace we can replace the occurrence of first character only in string. as & is repeated multiple times but only at first position we have to replace & with ?

SELECT with a Replace()

if you want any hope of ever using an index, store the data in a consistent manner (with the spaces removed). Either just remove the spaces or add a persisted computed column, Then you can just select from that column and not have to add all the space removing overhead every time you run your query.

add a PERSISTED computed column:

ALTER TABLE Contacts ADD PostcodeSpaceFree AS Replace(Postcode, ' ', '') PERSISTED 
go
CREATE NONCLUSTERED INDEX IX_Contacts_PostcodeSpaceFree 
ON Contacts (PostcodeSpaceFree) --INCLUDE (covered columns here!!)
go

to just fix the column by removing the spaces use:

UPDATE Contacts
    SET Postcode=Replace(Postcode, ' ', '')

now you can search like this, either select can use an index:

--search the PERSISTED computed column
SELECT 
    PostcodeSpaceFree 
    FROM Contacts
    WHERE PostcodeSpaceFree  LIKE 'NW101%'

or

--search the fixed (spaces removed column)
SELECT 
    Postcode
    FROM Contacts
    WHERE PostcodeLIKE 'NW101%'

Is PowerShell ready to replace my Cygwin shell on Windows?

grep

Select-String cmdlet and -match operator work with regexes. Also you can directly make use of .NET's regex support for more advanced functionality.

sort

Sort-Object is more powerful (than I remember *nix's sort). Allowing multi-level sorting on arbitrary expressions. Here PowerShell's maintenance of underlying type helps; e.g. a DateTime property will be sorted as a DateTime without having to ensure formatting into a sortable format.

uniq

Select-Object -Unique

Perl (how close does PowerShell come to Perl capabilities?)

In terms of Perl's breadth of domain specific support libraries: nowhere close (yet).

For general programming, PowerShell is certainly more cohesive and consistent, and easier to extend. The one gap for text munging is something equivalent to Perl's .. operator.

AWK

It has been long enough since using AWK (must be >18 years, since later I just used Perl), so can't really comment.

sed

[See above]

file (the command that gives file information)

PowerShell's strength here isn't so much of what it can do with filesystem objects (and it gets full information here, dir returns FileInfo or FolderInfo objects as appropriate) is that is the whole provider model.

You can treat the registry, certificate store, SQL Server, Internet Explorer's RSS cache, etc. as an object space navigable by the same cmdlets as the filesystem.


PowerShell is definitely the way forward on Windows. Microsoft has made it part of their requirements for future non-home products. Hence rich support in Exchange, support in SQL Server. This is only going to expand.

A recent example of this is the TFS PowerToys. Many TFS client operations are done without having to startup tf.exe each time (which requires a new TFS server connection, etc.) and is notably easier to then further process the data. As well as allowing wide access to the whole TFS client API to a greater detail than exposed in either Team Explorer of TF.exe.

How to set a header for a HTTP GET request, and trigger file download?

There are two ways to download a file where the HTTP request requires that a header be set.

The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.

The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.

The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.

Solution:

        var id = 123;

        var req = ic.ajax.raw({
            type: 'GET',
            url: '/api/dowloads/'+id,
            beforeSend: function (request) {
                request.setRequestHeader('token', 'token for '+id);
            },
            processData: false
        });

        var maxSizeForBase64 = 1048576; //1024 * 1024

        req.then(
            function resolve(result) {
                var str = result.response;

                var anchor = $('.vcard-hyperlink');
                var windowUrl = window.URL || window.webkitURL;
                if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
                    var blob = new Blob([result.response], { type: 'text/bin' });
                    var url = windowUrl.createObjectURL(blob);
                    anchor.prop('href', url);
                    anchor.prop('download', id+'.bin');
                    anchor.get(0).click();
                    windowUrl.revokeObjectURL(url);
                }
                else {
                    //use base64 encoding when less than set limit or file API is not available
                    anchor.attr({
                        href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
                        download: id+'.bin',
                    });
                    anchor.get(0).click();
                }

            }.bind(this),
            function reject(err) {
                console.log(err);
            }
        );

Note that I'm not using a raw XMLHttpRequest, and instead using ic-ajax, and should be quite similar to a jQuery.ajax solution.

Note also that you should substitute text/bin and .bin with whatever corresponds to the file type being downloaded.

The implementation of FormatUtils.utf8toBase64 can be found here

What's the HTML to have a horizontal space between two objects?

Another way you can add horizontal space between elements is to set up labels to preserve spaces in css:

label {
   white-space: pre;
}

..and then add a label with as many spaces as you want:

<label>  </label>

Accessing dict keys like an attribute?

Let me post another implementation, which builds upon the answer of Kinvais, but integrates ideas from the AttributeDict proposed in http://databio.org/posts/python_AttributeDict.html.

The advantage of this version is that it also works for nested dictionaries:

class AttrDict(dict):
    """
    A class to convert a nested Dictionary into an object with key-values
    that are accessible using attribute notation (AttrDict.attribute) instead of
    key notation (Dict["key"]). This class recursively sets Dicts to objects,
    allowing you to recurse down nested dicts (like: AttrDict.attr.attr)
    """

    # Inspired by:
    # http://stackoverflow.com/a/14620633/1551810
    # http://databio.org/posts/python_AttributeDict.html

    def __init__(self, iterable, **kwargs):
        super(AttrDict, self).__init__(iterable, **kwargs)
        for key, value in iterable.items():
            if isinstance(value, dict):
                self.__dict__[key] = AttrDict(value)
            else:
                self.__dict__[key] = value

Read Excel File in Python

The approach I took reads the header information from the first row to determine the indexes of the columns of interest.

You mentioned in the question that you also want the values output to a string. I dynamically build a format string for the output from the FORMAT column list. Rows are appended to the values string separated by a new line char.

The output column order is determined by the order of the column names in the FORMAT list.

In my code below the case of the column name in the FORMAT list is important. In the question above you've got 'Pincode' in your FORMAT list, but 'PinCode' in your excel. This wouldn't work below, it would need to be 'PinCode'.

from xlrd import open_workbook
wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
    formatString = ("%s,"*len(columnIndex))[0:-1] + "\n"

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        values += formatString % tuple(currentRowValues)

print values

For the sample input you gave above this code outputs:

>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0

And because I'm a python noob, props be to: this answer, this answer, this question, this question and this answer.

How to check if a user likes my Facebook Page or URL using Facebook's API

I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.

Here's another approach.

In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.

function parsePageSignedRequest() {
    if (isset($_REQUEST['signed_request'])) {
      $encoded_sig = null;
      $payload = null;
      list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
      $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
      $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
      return $data;
    }
    return false;
  }
  if($signed_request = parsePageSignedRequest()) {
    if($signed_request->page->liked) {
      echo "This content is for Fans only!";
    } else {
      echo "Please click on the Like button to view this tab!";
    }
  }

How to convert float value to integer in php?

There is always intval() - Not sure if this is what you were looking for...

example: -

$floatValue = 4.5;
echo intval($floatValue);    // Returns 4

It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.

Here is some documentation for this: - http://php.net/manual/en/function.intval.php

How to get data from Magento System Configuration

Magento 1.x

(magento 2 example provided below)

sectionName, groupName and fieldName are present in etc/system.xml file of the module.

PHP Syntax:

Mage::getStoreConfig('sectionName/groupName/fieldName');

From within an editor in the admin, such as the content of a CMS Page or Static Block; the description/short description of a Catalog Category, Catalog Product, etc.

{{config path="sectionName/groupName/fieldName"}}

For the "Within an editor" approach to work, the field value must be passed through a filter for the {{ ... }} contents to be parsed out. Out of the box, Magento will do this for Category and Product descriptions, as well as CMS Pages and Static Blocks. However, if you are outputting the content within your own custom view script and want these variables to be parsed out, you can do so like this:

<?php
    $example = Mage::getModel('identifier/name')->load(1);
    $filter  = Mage::getModel('cms/template_filter');
    echo $filter->filter($example->getData('field'));
?>

Replacing identifier/name with the a appropriate values for the model you are loading, and field with the name of the attribute you want to output, which may contain {{ ... }} occurrences that need to be parsed out.

Magento 2.x

From any Block class that extends \Magento\Framework\View\Element\AbstractBlock

$this->_scopeConfig->getValue('sectionName/groupName/fieldName');

Any other PHP class:

If the class (and none of it's parent's) does not inject \Magento\Framework\App\Config\ScopeConfigInterface via the constructor, you'll have to add it to your class.

// ... Remaining class definition above...

/**
 * @var \Magento\Framework\App\Config\ScopeConfigInterface
 */
protected $_scopeConfig;

/**
 * Constructor
 */
public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    // ...any other injected classes the class depends on...
) {
  $this->_scopeConfig = $scopeConfig;
  // Remaining constructor logic...
}

// ...remaining class definition below...

Once you have injected it into your class, you can now fetch store configuration values with the same syntax example given above for block classes.

Note that after modifying any class's __construct() parameter list, you may have to clear your generated classes as well as dependency injection directory: var/generation & var/di

Center a column using Twitter Bootstrap 3

<div class="container">
    <div class="row row-centered">
        <div class="col-xs-6 col-centered">Column 6</div>
        <div class="col-xs-6 col-centered">Column 6</div>
        <div class="col-xs-3 col-centered">Column 3</div>
        <div class="col-xs-3 col-centered">Column 3</div>
        <div class="col-xs-3 col-centered">Column 3</div>
    </div>
</div>

CSS

/* centered columns styles */
.row-centered {
    text-align:center;
}
.col-centered {
    display:inline-block;
    float:none;
    /* reset the text-align */
    text-align:left;
    /* inline-block space fix */
    margin-right:-4px;
    text-align: center;
    background-color: #ccc;
    border: 1px solid #ddd;
}

enter image description here

How to use systemctl in Ubuntu 14.04

Ubuntu 14 and lower does not have "systemctl" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot

Configure Docker to start on boot:

Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.

1) systemd (Ubuntu 16 and above):

$ sudo systemctl enable docker

To disable this behavior, use disable instead.

$ sudo systemctl disable docker

2) upstart (Ubuntu 14 and below):

Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:

$ echo manual | sudo tee /etc/init/docker.override
chkconfig

$ sudo chkconfig docker on

Done.

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

Letter Count on a string

You have a number of problems:

  • There's a problem with your indentation as others already pointed out.
  • There's no need to have nested loops. Just one loop is enough.
  • You're using char to mean two different things, but the char variable in the for loop will overwrite the data from the parameter.

This code fixes all these errors:

def count_letters(word, char):
    count = 0
    for c in word:
        if char == c:
            count += 1
    return count

A much more concise way to write this is to use a generator expression:

def count_letters(word, char):
    return sum(char == c for c in word)

Or just use the built-in method count that does this for you:

print 'abcbac'.count('c')

How to disable keypad popup when on edittext?

Try this answer,

editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);

Note: only for API 11+

batch file to copy files to another location?

It's easy to copy a folder in a batch file.

 @echo off
 set src_folder = c:\whatever\*.*
 set dst_folder = c:\foo
 xcopy /S/E/U %src_folder% %dst_folder%

And you can add that batch file to your Windows login script pretty easily (assuming you have admin rights on the machine). Just go to the "User Manager" control panel, choose properties for your user, choose profile and set a logon script.

How you get to the user manager control panel depends on which version of Windows you run. But right clicking on My Computer and choosing manage and then choosing Local users and groups works for most versions.

The only sticky bit is "when the folder is updated". This sounds like a folder watcher, which you can't do in a batch file, but you can do pretty easily with .NET.

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

If implementation is not defined, you are writing on a wrong file. On Unity 2019+ the correct file is main template grandle and not some of the others.

How to run Java program in terminal with external library JAR

For compiling the java file having dependency on a jar

javac -cp path_of_the_jar/jarName.jar className.java

For executing the class file

java -cp .;path_of_the_jar/jarName.jar className

Detect whether current Windows version is 32 bit or 64 bit

I want to add what I use in shell scripts (but can easily be used in any language) here. The reason is, that some of the solutions here don't work an WoW64, some use things not really meant for that (checking if there is a *(x86) folder) or don't work in cmd scripts. I feel, this is the "proper" way to do it, and should be safe even in future versions of Windows.

 @echo off
 if /i %processor_architecture%==AMD64 GOTO AMD64
 if /i %PROCESSOR_ARCHITEW6432%==AMD64 GOTO AMD64
    rem only defined in WoW64 processes
 if /i %processor_architecture%==x86 GOTO x86
 GOTO ERR
 :AMD64
    rem do amd64 stuff
 GOTO EXEC
 :x86
    rem do x86 stuff
 GOTO EXEC
 :EXEC
    rem do arch independent stuff
 GOTO END
 :ERR
    rem I feel there should always be a proper error-path!
    @echo Unsupported architecture!
    pause
 :END

Get a Div Value in JQuery

if you div looks like this:

<div id="someId">Some Value</div>

you could retrieve it with jquery like this:

$('#someId').text()

Hide text within HTML?

Use the CSS property visibility and set it to hidden.

You can see more here.

Multi-line bash commands in makefile

Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo depend on itself, but of course, make is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.

GNU make knows how to run gcc to produce an executable out of a set of .c and .h files, so maybe all you really need amounts to

foo: $(wildcard *.h) $(wildcard *.c)

Android overlay a view ontop of everything?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id = "@+id/Everything"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <!-- other actual layout stuff here EVERYTHING HERE -->

   </LinearLayout>

<LinearLayout
    android:id="@+id/overlay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right" >
</LinearLayout>

Now any view you add under LinearLayout with android:id = "@+id/overlay" will appear as overlay with gravity = right on Linear Layout with android:id="@+id/Everything"

JSON.NET Error Self referencing loop detected for type

In .Net 5.x, update your ConfigureServices method in startup.cs with the below code

public void ConfigureServices(IServiceCollection services)
{
    ----------------
    ----------------
    services.AddMvc().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
    });
    ------------------
}

By default, serialization (System.Text.Json.Serialization) does not support objects with cycles and does not preserve duplicate references. Use Preserve to enable unique object reference preservation on serialization and metadata consumption to read preserved references on deserialization. MSDN Link

Format Instant to String

Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString() it:

Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z


Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):

instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763


Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):

instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664

etc.

Package signatures do not match the previously installed version

com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to finalize session : INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package [MY REACT NATIVE APP NAME HERE] signatures do not match the previously installed version; ignoring!

I got this error when trying to install my React Native Android app on a connected device using this command:

react-native run-android --variant=release

I also had an emulator running on my computer.

Once I quit the emulator, running this command succeeded.

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

Core dumped, but core file is not in the current directory?

I could think of two following possibilities:

  1. As others have already pointed out, the program might chdir(). Is the user running the program allowed to write into the directory it chdir()'ed to? If not, it cannot create the core dump.

  2. For some weird reason the core dump isn't named core.* You can check /proc/sys/kernel/core_pattern for that. Also, the find command you named wouldn't find a typical core dump. You should use find / -name "*core.*", as the typical name of the coredump is core.$PID

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

JavaScript/jQuery - "$ is not defined- $function()" error

Include jquery.js and if it is included, load it before any other JavaScript code.

How to detect online/offline event cross-browser?

you can detect offline cross-browser way easily like below

var randomValue = Math.floor((1 + Math.random()) * 0x10000)

$.ajax({
      type: "HEAD",
      url: "http://yoururl.com?rand=" + randomValue,
      contentType: "application/json",
      error: function(response) { return response.status == 0; },
      success: function() { return true; }
   });

you can replace yoururl.com by document.location.pathname.

The crux of the solution is, try to connect to your domain name, if you are not able to connect - you are offline. works cross browser.

Convert char* to string C++

Use the string's constructor

basic_string(const charT* s,size_type n, const Allocator& a = Allocator());

EDIT:

OK, then if the C string length is not given explicitly, use the ctor:

basic_string(const charT* s, const Allocator& a = Allocator());

Oracle find a constraint

To get a more detailed description (which table/column references which table/column) you can run the following query:

SELECT   uc.constraint_name||CHR(10)
   ||      '('||ucc1.TABLE_NAME||'.'||ucc1.column_name||')' constraint_source
   ,       'REFERENCES'||CHR(10)
   ||      '('||ucc2.TABLE_NAME||'.'||ucc2.column_name||')' references_column
FROM user_constraints uc ,
  user_cons_columns ucc1 ,
  user_cons_columns ucc2
WHERE uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION        = ucc2.POSITION -- Correction for multiple column primary keys.
AND uc.constraint_type   = 'R'
AND uc.constraint_name   = 'SYS_C00381400'
ORDER BY ucc1.TABLE_NAME ,
  uc.constraint_name;

From here.

Git SSH error: "Connect to host: Bad file number"

What I found is that, this happens when your connection is poor. I had it a few minutes ago when pushing to my repo, it kept failing and a while after that, the connection went down.

After it came back up, the push immediately went through.

I believe it can be caused by either a drop in connection from either your side or theirs.

What does if __name__ == "__main__": do?

Before explaining anything about if __name__ == '__main__' it is important to understand what __name__ is and what it does.

What is __name__?

__name__ is a DunderAlias - can be thought of as a global variable (accessible from modules) and works in a similar way to global.

It is a string (global as mentioned above) as indicated by type(__name__) (yielding <class 'str'>), and is an inbuilt standard for both Python 3 and Python 2 versions.

Where:

It can not only be used in scripts but can also be found in both the interpreter and modules/packages.

Interpreter:

>>> print(__name__)
__main__
>>>

Script:

test_file.py:

print(__name__)

Resulting in __main__

Module or package:

somefile.py:

def somefunction():
    print(__name__)

test_file.py:

import somefile
somefile.somefunction()

Resulting in somefile

Notice that when used in a package or module, __name__ takes the name of the file. The path of the actual module or package path is not given, but has its own DunderAlias __file__, that allows for this.

You should see that, where __name__, where it is the main file (or program) will always return __main__, and if it is a module/package, or anything that is running off some other Python script, will return the name of the file where it has originated from.

Practice:

Being a variable means that it's value can be overwritten ("can" does not mean "should"), overwriting the value of __name__ will result in a lack of readability. So do not do it, for any reason. If you need a variable define a new variable.

It is always assumed that the value of __name__ to be __main__ or the name of the file. Once again changing this default value will cause more confusion that it will do good, causing problems further down the line.

example:

>>> __name__ = 'Horrify' # Change default from __main__
>>> if __name__ == 'Horrify': print(__name__)
...
>>> else: print('Not Horrify')
...
Horrify
>>>

It is considered good practice in general to include the if __name__ == '__main__' in scripts.

Now to answer if __name__ == '__main__':

Now we know the behaviour of __name__ things become clearer:

An if is a flow control statement that contains the block of code will execute if the value given is true. We have seen that __name__ can take either __main__ or the file name it has been imported from.

This means that if __name__ is equal to __main__ then the file must be the main file and must actually be running (or it is the interpreter), not a module or package imported into the script.

If indeed __name__ does take the value of __main__ then whatever is in that block of code will execute.

This tells us that if the file running is the main file (or you are running from the interpreter directly) then that condition must execute. If it is a package then it should not, and the value will not be __main__.

Modules:

__name__ can also be used in modules to define the name of a module

Variants:

It is also possible to do other, less common but useful things with __name__, some I will show here:

Executing only if the file is a module or package:

if __name__ != '__main__':
    # Do some useful things 

Running one condition if the file is the main one and another if it is not:

if __name__ == '__main__':
    # Execute something
else:
    # Do some useful things

You can also use it to provide runnable help functions/utilities on packages and modules without the elaborate use of libraries.

It also allows modules to be run from the command line as main scripts, which can be also very useful.

Convert HttpPostedFileBase to byte[]

You can read it from the input stream:

public ActionResult ManagePhotos(ManagePhotos model)
{
    if (ModelState.IsValid)
    {
        byte[] image = new byte[model.File.ContentLength];
        model.File.InputStream.Read(image, 0, image.Length); 

        // TODO: Do something with the byte array here
    }
    ...
}

And if you intend to directly save the file to the disk you could use the model.File.SaveAs method. You might find the following blog post useful.

clearing a char array c

Nope. All you are doing is setting the first value to '\0' or 0.

If you are working with null terminated strings, then in the first example, you'll get behavior that mimics what you expect, however the memory is still set.

If you want to clear the memory without using memset, use a for loop.

Get name of current script in Python

For completeness' sake, I thought it would be worthwhile summarizing the various possible outcomes and supplying references for the exact behaviour of each:

  • __file__ is the currently executing file, as detailed in the official documentation:

    __file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

    From Python3.4 onwards, per issue 18416, __file__ is always an absolute path, unless the currently executing file is a script that has been executed directly (not via the interpreter with the -m command line option) using a relative path.

  • __main__.__file__ (requires importing __main__) simply accesses the aforementioned __file__ attribute of the main module, e.g. of the script that was invoked from the command line.

    From Python3.9 onwards, per issue 20443, the __file__ attribute of the __main__ module became an absolute path, rather than a relative path.

  • sys.argv[0] (requires importing sys) is the script name that was invoked from the command line, and might be an absolute path, as detailed in the official documentation:

    argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

    As mentioned in another answer to this question, Python scripts that were converted into stand-alone executable programs via tools such as py2exe or PyInstaller might not display the desired result when using this approach (i.e. sys.argv[0] would hold the name of the executable rather than the name of the main Python file within that executable).

  • If none of the aforementioned options seem to work, probably due to an atypical execution process or an irregular import operation, the inspect module might prove useful. In particular, invoking inspect.stack()[-1][1] should work, although it would raise an exception when running in an implementation without Python stack frame.

  • From Python3.6 onwards, and as detailed in another answer to this question, it's possible to install an external open source library, lib_programname, which is tailored to provide a complete solution to this problem.

    This library iterates through all of the approaches listed above until a valid path is returned. If all of them fail, it raises an exception. It also tries to address various pitfalls, such as invocations via the pytest framework or the pydoc module.

    import lib_programname
    # this returns the fully resolved path to the launched python program
    path_to_program = lib_programname.get_path_executed_script()  # type: pathlib.Path
    

Handling relative paths

When dealing with an approach that happens to return a relative path, it might be tempting to invoke various path manipulation functions, such as os.path.abspath(...) or os.path.realpath(...) in order to extract the full or real path.

However, these methods rely on the current path in order to derive the full path. Thus, if a program first changes the current working directory, for example via os.chdir(...), and only then invokes these methods, they would return an incorrect path.

Handling symbolic links

If the current script is a symbolic link, then all of the above would return the path of the symbolic link rather than the path of the real file and os.path.realpath(...) should be invoked in order to extract the latter.


Further manipulations that extract the actual file name

os.path.basename(...) may be invoked on any of the above in order to extract the actual file name and os.path.splitext(...) may be invoked on the actual file name in order to truncate its suffix, as in os.path.splitext(os.path.basename(...)).

From Python 3.4 onwards, per PEP 428, the PurePath class of the pathlib module may be used as well on any of the above. Specifically, pathlib.PurePath(...).name extracts the actual file name and pathlib.PurePath(...).stem extracts the actual file name without its suffix.

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

How to make google spreadsheet refresh itself every 1 minute?

If you are only looking for a refresh rate for the GOOGLEFINANCE function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).

Single-symbol refresh rate (using GoogleClock)

Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.

=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))

For example, with:

  • SYMBOL: GOOG
  • DATA DELAY: 15 (minutes)

then

=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))

Results in a dynamic data-based refresh rate of:

=GoogleClock(15)

Multi-symbol refresh rate (using GoogleClock)

If your sheet contains a number of rows of symbols, you could add a datadelay column for each symbol and use the lowest value, for example:

=GoogleClock(MIN(dataDelayValuesNamedRange))

Where dataDelayValuesNamedRange is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).

Without GoogleClock()

The GoogleClock() function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).

(This part of the answer is based on, and portions copied from, Google Docs Help)

To change how often "some" Google Sheets functions update:

  1. Open a spreadsheet. Click File > Spreadsheet settings.
  2. In the RECALCULATION section, choose a setting from the drop-down menu.
  3. Setting options are:
    • On change
    • On change and every minute
    • On change and every hour
  4. Click SAVE SETTINGS.

NOTE External data functions recalculate at the following intervals:

  • ImportRange: 30 minutes
  • ImportHtml, ImportFeed, ImportData, ImportXml: 1 hour
  • GoogleFinance: 2 minutes

The references in earlier sections to the display and use of the datadelay attribute still apply, as well as the concepts for more efficient coding of sheets.

On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.

[*] in my understanding so far (I am currently testing this)

Removing address bar from browser (to view on Android)

The problem with most of these is that the user can still scroll up and see the addressbar. To make a permanent solution, you need to add this as well.

//WHENEVER the user scrolls
$(window).scroll(function(){
    //if you reach the top
    if ($(window).scrollTop() == 0)   
    //scroll back down  
    {window.scrollTo(1,1)}
})

Git workflow and rebase vs merge questions

From what I have observed, git merge tends to keep the branches separate even after merging, whereas rebase then merge combines it into one single branch. The latter comes out much cleaner, whereas in the former, it would be easier to find out which commits belong to which branch even after merging.

How to programmatically add controls to a form in VB.NET

Yes.

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MyTextbox as New Textbox
    With MyTextbox
       .Size = New Size(100,20)
       .Location = New Point(20,20)
    End With
    AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
    Me.Controls.Add(MyTextbox)

'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.

End Sub

Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
   'Write code here.
End Sub

Determine installed PowerShell version

I would use either Get-Host or $PSVersionTable. As Andy Schneider points out, $PSVersionTable doesn't work in version 1; it was introduced in version 2.

get-host

Name             : ConsoleHost
Version          : 2.0
InstanceId       : d730016e-2875-4b57-9cd6-d32c8b71e18a
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-GB
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

$PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4200
BuildVersion                   6.0.6002.18111
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

How can I reverse a NSArray in Objective-C?

There is a easy way to do it.

    NSArray *myArray = @[@"5",@"4",@"3",@"2",@"1"];
    NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
    for(int i=0; i<[myNewArray count]; i++){
        [myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
    }
    //other way to do it
    for(NSString *eachValue in myArray){
        [myNewArray insertObject:eachValue atIndex:0];
    }

    //in both cases your new array will look like this
    NSLog(@"myNewArray: %@", myNewArray);
    //[@"1",@"2",@"3",@"4",@"5"]

I hope this helps.

Git - How to close commit editor?

After writing commit message, just press Esc Button and then write :wq or :wq! and then Enter to close the unix file.

How does the Java 'for each' loop work?

It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.

JavaScript backslash (\) in variables is causing an error

You may want to try the following, which is more or less the standard way to escape user input:

function stringEscape(s) {
    return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
    function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}

This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Copy all order entries of home folder .iml file into your /src/main/main.iml file. This will solve the problem.

What's the best way to build a string of delimited items in Java?

So a couple of things you might do to get the feel that it seems like you're looking for:

1) Extend List class - and add the join method to it. The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method)

2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class: so you could write that join method and add it as an extension method to List or even to Collection.

Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet :) But it should work just fine.

To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.

Add and Remove Views in Android Dynamically?

I need the exact same feature described in this question. Here is my solution and source code: https://github.com/laoyang/android-dynamic-views. And you can see the video demo in action here: http://www.youtube.com/watch?v=4HeqyG6FDhQ

Layout

Basically you'll two xml layout files:

  • A horizontal LinearLayout row view with a TextEdit, a Spinner and an ImageButton for deletion.
  • A vertical LinearLayout container view with just a Add new button.

Control

In the Java code, you'll add and remove row views into the container dynamically, using inflate, addView, removeView, etc. There are some visibility control for better UX in the stock Android app. You need add a TextWatcher for the EditText view in each row: when the text is empty you need to hide the Add new button and the delete button. In my code, I wrote a void inflateEditRow(String) helper function for all the logic.

Other tricks

  • Set android:animateLayoutChanges="true" in xml to enable animation
  • Use custom transparent background with pressed selector to make the buttons visually the same as the ones in the stock Android app.

Source code

The Java code of the main activity ( This explains all the logic, but quite a few properties are set in xml layout files, please refer to the Github source for complete solution):

public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row_container);
    mContainerView = (LinearLayout) findViewById(R.id.parentView);
    mAddButton = (Button) findViewById(R.id.btnAddNewItem);

    // Add some examples
    inflateEditRow("Xiaochao");
    inflateEditRow("Yang");
}

// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
    // Inflate a new row and hide the button self.
    inflateEditRow(null);
    v.setVisibility(View.GONE);
}

// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
    // remove the row by calling the getParent on button
    mContainerView.removeView((View) v.getParent());
}

// Helper for inflating a row
private void inflateEditRow(String name) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.row, null);
    final ImageButton deleteButton = (ImageButton) rowView
            .findViewById(R.id.buttonDelete);
    final EditText editText = (EditText) rowView
            .findViewById(R.id.editText);
    if (name != null && !name.isEmpty()) {
        editText.setText(name);
    } else {
        mExclusiveEmptyView = rowView;
        deleteButton.setVisibility(View.INVISIBLE);
    }

    // A TextWatcher to control the visibility of the "Add new" button and
    // handle the exclusive empty view.
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

            // Some visibility logic control here:
            if (s.toString().isEmpty()) {
                mAddButton.setVisibility(View.GONE);
                deleteButton.setVisibility(View.INVISIBLE);
                if (mExclusiveEmptyView != null
                        && mExclusiveEmptyView != rowView) {
                    mContainerView.removeView(mExclusiveEmptyView);
                }
                mExclusiveEmptyView = rowView;
            } else {
                if (mExclusiveEmptyView == rowView) {
                    mExclusiveEmptyView = null;
                }
                mAddButton.setVisibility(View.VISIBLE);
                deleteButton.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }
    });

    // Inflate at the end of all rows but before the "Add new" button
    mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}

How do I remove a substring from the end of a string in Python?

If you know it's an extension, then

url = 'abcdc.com'
...
url.rsplit('.', 1)[0]  # split at '.', starting from the right, maximum 1 split

This works equally well with abcdc.com or www.abcdc.com or abcdc.[anything] and is more extensible.

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

What does InitializeComponent() do, and how does it work in WPF?

Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.

"unmappable character for encoding" warning in Java

This worked for me -

    <?xml version="1.0" encoding="utf-8" ?>
<project name="test" default="compile">
    <target name="compile">
        <javac srcdir="src" destdir="classes" 
                           encoding="iso-8859-1" debug="true" />
    </target>
</project>

Javascript can't find element by id?

Run the code either in onload event, either just before you close body tag. You try to find an element wich is not there at the moment you do it.

Date Difference in php on days?

I would recommend to use date->diff function, as in example below:

   $dStart = new DateTime('2012-07-26');
   $dEnd  = new DateTime('2012-08-26');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater

see http://www.php.net/manual/en/datetime.diff.php