Programs & Examples On #Apache2.2

Use this tag for Apache version 2.2.x specific question.

Composer: The requested PHP extension ext-intl * is missing from your system

I encountered this using it in Mac, resolved it by using --ignore-platform-reqs option.

composer install --ignore-platform-reqs

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

Error message "Forbidden You don't have permission to access / on this server"

If you are using a WAMP server then try this:

  • Single click on the WAMP server icon at the taskbar

  • Select the option put online

  • Your server will restart automatically

  • Then try to access your localwebsite

The mysqli extension is missing. Please check your PHP configuration

  • In your Xampp folder, open php.ini file inside the PHP folder i.e xampp\php\php.ini (with a text editor).

  • Search for extension=mysqli (Ctrl+F), if there are two, look for the one that has been uncommented (without ";" behind)

  • Change the mysqli with the correct path address i.e extension=C:\xampp\php\ext\php_mysqli.dll.

  • On your Xampp control panel, stop and start apache and MySQL

How to use .htaccess in WAMP Server?

RewriteEngine on
RewriteBase /basic_test/

RewriteRule ^index.php$ test.php

Windows could not start the Apache2 on Local Computer - problem

There is some other program listening on port 80, usual suspects are

  1. Skype (Listens on port 80)
  2. NOD32 (Add Apache to the IMON exceptions' list for it to allow apache to bind)
  3. Some other antivirus (Same as above)

Way to correct it is either shutting down the program that's using the port 80 or configure it to use a different port or configure Apache to listen on a different port with the Listen directive in httpd.conf. In the case of antivirus configure the antivirus to allow Apache to bind on the port you have chosen.

Way to diagnose which app, if any, has bound to port 80 is run the netstat with those options, look for :80 next to the local IP address (second column) and find the PID (last column). Then, on the task manager you can find which process has the PID you got in the previous step. (You might need to add the PID column on the task manager)

C:\Users\vinko>netstat -ao -p tcp

Conexiones activas

  Proto  Dirección local          Dirección remota        Estado           PID
  TCP    127.0.0.1:1110         127.0.0.1:51373        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51379        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51381        ESTABLISHED     388
  TCP    127.0.0.1:1110         127.0.0.1:51382        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51479        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51481        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51483        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51485        ESTABLISHED     388
  TCP    127.0.0.1:1110         127.0.0.1:51487        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51489        ESTABLISHED     388
  TCP    127.0.0.1:51381        127.0.0.1:1110         ESTABLISHED     5168
  TCP    127.0.0.1:51485        127.0.0.1:1110         ESTABLISHED     5168
  TCP    127.0.0.1:51489        127.0.0.1:1110         ESTABLISHED     5168
  TCP    127.0.0.1:59264        127.0.0.1:59265        ESTABLISHED     5168
  TCP    127.0.0.1:59265        127.0.0.1:59264        ESTABLISHED     5168
  TCP    127.0.0.1:59268        127.0.0.1:59269        ESTABLISHED     5168
  TCP    127.0.0.1:59269        127.0.0.1:59268        ESTABLISHED     5168
  TCP    192.168.1.34:51278     192.168.1.33:445       ESTABLISHED     4
  TCP    192.168.1.34:51383     67.199.15.132:80       ESTABLISHED     388
  TCP    192.168.1.34:51486     66.102.9.18:80         ESTABLISHED     388
  TCP    192.168.1.34:51490     74.125.4.20:80         ESTABLISHED     388

If you want to Disable Skype from listening on port 80 and 443, you can follow the link http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/

How do I install cURL on Windows?

You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.

Write down the PHP ini directory path you see in the variables list now! You will probably notice that it's different from your PHP-CLI ini file.

Enable the extension

You're done :-)

javascript change background color on click

You can set the background color of an object using CSS.

You can also use JavaScript to attach click handlers to objects and they can change the style of an object using element.style.property = 'value';. In the example below I've attached it in the HTML to a button but the handler could equally have been added to the body element or defined entirely in JavaScript.

_x000D_
_x000D_
body {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<button onclick="document.body.style.backgroundColor = 'green';">Green</button>
_x000D_
_x000D_
_x000D_

What is the best way to delete a component with CLI

Answer for Angular 2+

Remove component from imports and declaration array of app.modules.ts.

Second check its reference is added in other module, if yes then remove it and

finally delete that component Manually from app and you are done.

Or you can do it in reverse order also.

Datetime in where clause

select * from tblErrorLog
where errorDate BETWEEN '12/20/2008' AND DATEADD(DAY, 1, '12/20/2008')

changing kafka retention period during runtime

The correct config key is retention.ms

$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".

Matplotlib (pyplot) savefig outputs blank image

Call plt.show() after plt.savefig(fig) and your problem should be solved.

How to return an array from a function?

"how can i return a array in a c++ method and how must i declare it? int[] test(void); ??"

template <class X>
  class Array
{
  X     *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(X* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new X [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(X));
            return m_size;
        }
       return 0;
    }
}; 

just for int

class IntArray
{
  int   *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(int* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new int [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(int));
            return m_size;
        }
       return 0;
    }
}; 

example

Array<float> array;
float  *n_data = NULL;
int     data_size;
if(data_size = array.Get(n_data))
{     // work with array    }

delete [] n_data;

example for int

IntArray   array;
int       *n_data = NULL;
int        data_size;
if(data_size = array.Get(n_data))
{  // work with array  }

delete [] n_data;

phpMyAdmin mbstring error

In Ubuntu Server I have installed a php extension. I did this with:

sudo apt-get install php-mbstring

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

How do I get the App version and build number using Swift?

My answer (as at Aug 2015), given Swift keeps evolving:

let version = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String

Vertically align an image inside a div with responsive height

Try this one

  .responsive-container{
          display:table;
  }
  .img-container{
          display:table-cell;
          vertical-align: middle;
   }

jquery append div inside div with id and manipulate

You're overcomplicating things:

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);

For example: http://jsfiddle.net/ambiguous/Dm5J2/

How do I set the rounded corner radius of a color drawable using xml?

Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

<stroke
    android:width="5dp"
    android:color="#1271BB" />

<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" /></shape>

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them
axes2.set_ylabel(...)

How can I remount my Android/system as read-write in a bash script using adb?

Probable cause that remount fails is you are not running adb as root.

Shell Script should be as follow.

# Script to mount Android Device as read/write.
# List the Devices.
adb devices;

# Run adb as root (Needs root access).
adb root;

# Since you're running as root su is not required
adb shell mount -o rw,remount /;

If this fails, you could try the below:

# List the Devices.
adb devices;

# Run adb as root
adb root;

adb remount;
adb shell su -c "mount -o rw,remount /";

To find which user you are:

$ adb shell whoami

How to set the Default Page in ASP.NET?

Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.

<add verb="GET" path="default.aspx" type="RedirectHandler"/>

Make sure Default.aspx does not exists physically at your application root. If it exists physically the HttpHandler will not be given any chance to execute. Physical file overrides HttpHandler mapping.

Moreover you can re-use this for pages other than default.aspx.

<add verb="GET" path="index.aspx" type="RedirectHandler"/>

//RedirectHandler.cs in your App_Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
    public RedirectHandler()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Redirect("CreateThings.aspx");
        context.Response.End();
    }

    #endregion
}

How to get pip to work behind a proxy server

Old thread, I know, but for future reference, the --proxy option is now passed with an "="

Example:

$ sudo pip install --proxy=http://yourproxy:yourport package_name

Get full query string in C# ASP.NET

just a moment ago, i came across with the same issue. and i resolve it in the following manner.

Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);

with reference to the this

Convert pyspark string to date format

possibly not so many answers so thinking to share my code which can help someone

from pyspark.sql import SparkSession
from pyspark.sql.functions import to_date

spark = SparkSession.builder.appName("Python Spark SQL basic example")\
    .config("spark.some.config.option", "some-value").getOrCreate()


df = spark.createDataFrame([('2019-06-22',)], ['t'])
df1 = df.select(to_date(df.t, 'yyyy-MM-dd').alias('dt'))
print df1
print df1.show()

output

DataFrame[dt: date]
+----------+
|        dt|
+----------+
|2019-06-22|
+----------+

the above code to convert to date if you want to convert datetime then use to_timestamp. let me know if you have any doubt.

Google.com and clients1.google.com/generate_204

I found this old Thread while google'ing for generate_204 as Android seems to use this to determine if the wlan is open (response 204 is received) closed (no response at all) or blocked (redirect to captive portal is present). In that case a notification is shown that a log-in to WiFi is required...enter image description here

htaccess remove index.php from url

Steps to remove index.php from url for your wordpress website.

  1. Check you should have mod_rewrite enabled at your server. To check whether it's enabled or not - Create 1 file phpinfo.php at your root folder with below command.
 <?php
   phpinfo?();
 ?>

Now run this file - www.yoursite.com/phpinfo.php and it will show mod_rewrite at Load modules section. If not enabled then perform below commands at your terminal.

sudo a2enmod rewrite
sudo service apache2 restart
  1. Make sure your .htaccess is existing in your WordPress root folder, if not create one .htaccess file Paste this code at your .htaccess file :-
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
</IfModule>  
  1. Further make permission of .htaccess to 666 so that it become writable and now you can do changes in your wordpress permalinks.

  2. Now go to Settings -> permalinks -> and change to your needed url format. Remove this code /index.php/%year%/%monthnum%/%day%/%postname%/ and insert this code on Custom Structure: /%postname%/

  3. If still not succeeded then check your hosting, mine was digitalocean server, so I cleared it myself

Edited the file /etc/apache2/sites-enabled/000-default.conf

Added this line after DocumentRoot /var/www/html

<Directory /var/www/html>
   AllowOverride All
</Directory>

Restart your apache server

Note: /var/www/html will be your document root

Big O, how do you calculate/approximate it?

great question!

Disclaimer: this answer contains false statements see the comments below.

If you're using the Big O, you're talking about the worse case (more on what that means later). Additionally, there is capital theta for average case and a big omega for best case.

Check out this site for a lovely formal definition of Big O: https://xlinux.nist.gov/dads/HTML/bigOnotation.html

f(n) = O(g(n)) means there are positive constants c and k, such that 0 = f(n) = cg(n) for all n = k. The values of c and k must be fixed for the function f and must not depend on n.


Ok, so now what do we mean by "best-case" and "worst-case" complexities?

This is probably most clearly illustrated through examples. For example if we are using linear search to find a number in a sorted array then the worst case is when we decide to search for the last element of the array as this would take as many steps as there are items in the array. The best case would be when we search for the first element since we would be done after the first check.

The point of all these adjective-case complexities is that we're looking for a way to graph the amount of time a hypothetical program runs to completion in terms of the size of particular variables. However for many algorithms you can argue that there is not a single time for a particular size of input. Notice that this contradicts with the fundamental requirement of a function, any input should have no more than one output. So we come up with multiple functions to describe an algorithm's complexity. Now, even though searching an array of size n may take varying amounts of time depending on what you're looking for in the array and depending proportionally to n, we can create an informative description of the algorithm using best-case, average-case, and worst-case classes.

Sorry this is so poorly written and lacks much technical information. But hopefully it'll make time complexity classes easier to think about. Once you become comfortable with these it becomes a simple matter of parsing through your program and looking for things like for-loops that depend on array sizes and reasoning based on your data structures what kind of input would result in trivial cases and what input would result in worst-cases.

Change DataGrid cell colour based on values

Just put instead

<Style TargetType="{x:DataGridCell}" >

But beware that this will target ALL your cells (you're aiming at all the objects of type DataGridCell ) If you want to put a style according to the cell type, I'd recommend you to use a DataTemplateSelector

A good example can be found in Christian Mosers' DataGrid tutorial:

http://www.wpftutorial.net/DataGrid.html#rowDetails

Have fun :)

View list of all JavaScript variables in Google Chrome Console

David Walsh has a nice solution for this. Here is my take on this, combining his solution with what has been discovered on this thread as well.

https://davidwalsh.name/global-variables-javascript

x = {};
var iframe = document.createElement('iframe');
iframe.onload = function() {
    var standardGlobals = Object.keys(iframe.contentWindow);
    for(var b in window) { 
      const prop = window[b];
      if(window.hasOwnProperty(b) && prop && !prop.toString().includes('native code') && !standardGlobals.includes(b)) {
        x[b] = prop;
      }
    }
    console.log(x)
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);

x now has only the globals.

Set value to an entire column of a pandas dataframe

You can do :

df['industry'] = 'yyy'

HTTPS connections over proxy servers

I had tried

  • start tunneling: ssh -N -D 12345 login@proxy_server
  • Setting the proxy in the firefox settings as localhost:12345
    • and ticking "use this proxy for all protocols"

but this resulted in the error "Insecure connection" whenever I tried to connect to an https website.

The solution was to

  • "untick" the "use this proxy for all protocols"
  • set the proxy "localhost:12345" only as a SOCKS proxy
  • and leave the HTTP proxy, SSL proxy, FTP proxy blank

Reference from digital ocean documentation

How To Route Web Traffic Securely Without a VPN Using a SOCKS Tunnel

Calling startActivity() from outside of an Activity?

This same error I have faced in case of getting Notification in latest Android devices 9 and 10.

It depends on Launch mode how you are handling it. Use below code:- android:launchMode="singleTask"

Add this flag with Intent:- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

MySQL select where column is not empty

Check for NULL and empty string values:

select phone
, phone2 
from users 
where phone like '813%' 
and trim(coalesce(phone2, '')) <>''

N.B. I think COALESCE() is SQL standard(-ish), whereas ISNULL() is not.

How do you delete an ActiveRecord object?

There is delete, delete_all, destroy, and destroy_all.

The docs are: older docs and Rails 3.0.0 docs

delete doesn't instantiate the objects, while destroy does. In general, delete is faster than destroy.

Checking Bash exit status of several commands efficiently

When I use ssh I need to distinct between problems caused by connection issues and error codes of remote command in errexit (set -e) mode. I use the following function:

# prepare environment on calling site:

rssh="ssh -o ConnectionTimeout=5 -l root $remote_ip"

function exit255 {
    local flags=$-
    set +e
    "$@"
    local status=$?
    set -$flags
    if [[ $status == 255 ]]
    then
        exit 255
    else
        return $status
    fi
}
export -f exit255

# callee:

set -e
set -o pipefail

[[ $rssh ]]
[[ $remote_ip ]]
[[ $( type -t exit255 ) == "function" ]]

rjournaldir="/var/log/journal"
if exit255 $rssh "[[ ! -d '$rjournaldir/' ]]"
then
    $rssh "mkdir '$rjournaldir/'"
fi
rconf="/etc/systemd/journald.conf"
if [[ $( $rssh "grep '#Storage=auto' '$rconf'" ) ]]
then
    $rssh "sed -i 's/#Storage=auto/Storage=persistent/' '$rconf'"
fi
$rssh systemctl reenable systemd-journald.service
$rssh systemctl is-enabled systemd-journald.service
$rssh systemctl restart systemd-journald.service
sleep 1
$rssh systemctl status systemd-journald.service
$rssh systemctl is-active systemd-journald.service

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

Just want to point out that this answer provides a better explanation.
Basically you can either have @Getter and @NoArgConstructor together
or let Lombok regenerates @ConstructorProperties using lombok.config file,
or compile your java project with -parameters flags,
or let Jackson use Lombok's @Builder

Check if a string within a list contains a specific string with Linq

Try this:

bool matchFound = myList.Any(s => s.Contains("Mdd LH"));

The Any() will stop searching the moment it finds a match, so is quite efficient for this task.

window.history.pushState refreshing the browser

As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.

If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").

But this function is not intended to reload the browser.

All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.

Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).

For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.

Hence the need for the function

history.pushState({},"Results for `Cats`",'url.html?s=cats');

It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.

When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.

If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.

As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.

See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.

Can I use Twitter Bootstrap and jQuery UI at the same time?

I have site developed using jquery ui, I just tried to plug in bootstrap for future development and styling but it breaks virtually everything.

So No they are not compatible.

How should strace be used?

I use strace all the time to debug permission issues. The technique goes like this:

$ strace -e trace=open,stat,read,write gnome-calculator

Where gnome-calculator is the command that you want to run.

Cross-Domain Cookies

As other people say, you cannot share cookies, but you could do something like this:

  1. centralize all cookies in a single domain, let's say cookiemaker.com
  2. when the user makes a request to example.com you redirect him to cookiemaker.com
  3. cookiemaker.com redirects him back to example.com with the information you need

Of course, it's not completely secure, and you have to create some kind of internal protocol between your apps to do that.

Lastly, it would be very annoying for the user if you do something like that in every request, but not if it's just the first.

But I think there is no other way...

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

You can press I twice to interrupt the kernel.

This only works if you're in Command mode. If not already enabled, press Esc to enable it.

get enum name from enum value

What you can do is

RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
                                     RelationActiveEnum.ACTIVE.name();

or

RelationActiveEnum ae = RelationActiveEnum.valueOf(
                                     RelationActiveEnum.ACTIVE.name();

or

// not recommended as the ordinal might not match the value
RelationActiveEnum ae = RelationActiveEnum.values()[
                                     RelationActiveEnum.ACTIVE.value];

By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.

public enum RelationActiveEnum {
    Invited(0),
    Active(1),
    Suspended(2);

    private final int code;

    private RelationActiveEnum(final int code) {
        this.code = code;
    }

    private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
    static {
        for (RelationActiveEnum rae : RelationActiveEnum.values()) {
            BY_CODE_MAP.put(rae.code, rae);
        }
    }

    public static RelationActiveEnum forCode(int code) {
        return BY_CODE_MAP.get(code);
    }
}

allows you to write

String name = RelationActiveEnum.forCode(RelationActiveEnum.ACTIVE.code).name();

PHP Composer behind http proxy

iconoclast's answer did not work for me.

I upgraded my php from 5.3.* (xampp 1.7.4) to 5.5.* (xampp 1.8.3) and the problem was solved.

Try iconoclast's answer first, if it doesn't work then upgrading might solve the problem.

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

Two ways:

  1. Have a bean implement ApplicationListener<ContextClosedEvent>. onApplicationEvent() will get called before the context and all the beans are destroyed.

  2. Have a bean implement Lifecycle or SmartLifecycle. stop() will get called before the context and all the beans are destroyed.

Either way you can shut down the task stuff before the bean destroying mechanism takes place.

Eg:

@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
    @Autowired ThreadPoolTaskExecutor executor;
    @Autowired ThreadPoolTaskScheduler scheduler;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        scheduler.shutdown();
        executor.shutdown();
    }       
}

(Edit: Fixed method signature)

How to remove all namespaces from XML with C#?

Slightly modified Peter's answer, this would works fine for the attribute as well, including remove the namespace and prefix. A bit sorry for the code looks a bit ugly.

 private static XElement RemoveAllNamespaces(XElement xmlDocument)
        {
            if (!xmlDocument.HasElements)
            {
                XElement xElement = new XElement(xmlDocument.Name.LocalName);
                xElement.Value = xmlDocument.Value;

                foreach (XAttribute attribute in xmlDocument.Attributes())
                {
                    xElement.Add(new XAttribute(attribute.Name.LocalName, attribute.Value));
                }

                return xElement;
            }

            else
            {
                XElement xElement = new XElement(xmlDocument.Name.LocalName,  xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));

                foreach (XAttribute attribute in xmlDocument.Attributes())
                {
                    xElement.Add(new XAttribute(attribute.Name.LocalName, attribute.Value));
                }

                return xElement;
            }

    }

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

No module named 'openpyxl' - Python 3.4 - Ubuntu

You have to install it explixitly using the python package manager as

  1. pip install openpyxl for Python 2
  2. pip3 install openpyxl for Python 3

Node.js for() loop returning the same values at each loop

  for(var i = 0; i < BoardMessages.length;i++){
        (function(j){
            console.log("Loading message %d".green, j);
            htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
        })(i);
  }

That should work; however, you should never create a function in a loop. Therefore,

  for(var i = 0; i < BoardMessages.length;i++){
        composeMessage(BoardMessages[i]);
  }

  function composeMessage(message){
      console.log("Loading message %d".green, message);
      htmlMessageboardString += MessageToHTMLString(message);
  }

How to import CSV file data into a PostgreSQL table?

Personal experience with PostgreSQL, still waiting for a faster way.

1. Create table skeleton first if the file is stored locally:

    drop table if exists ur_table;
    CREATE TABLE ur_table
    (
        id serial NOT NULL,
        log_id numeric, 
        proc_code numeric,
        date timestamp,
        qty int,
        name varchar,
        price money
    );
    COPY 
        ur_table(id, log_id, proc_code, date, qty, name, price)
    FROM '\path\xxx.csv' DELIMITER ',' CSV HEADER;

2. When the \path\xxx.csv is on the server, postgreSQL doesn't have the permission to access the server, you will have to import the .csv file through the pgAdmin built in functionality.

Right click the table name choose import.

enter image description here

If you still have problem, please refer this tutorial. http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/

Put byte array to JSON and vice versa

If your byte array may contain runs of ASCII characters that you'd like to be able to see, you might prefer BAIS (Byte Array In String) format instead of Base64. The nice thing about BAIS is that if all the bytes happen to be ASCII, they are converted 1-to-1 to a string (e.g. byte array {65,66,67} becomes simply "ABC") Also, BAIS often gives you a smaller file size than Base64 (this isn't guaranteed).

After converting the byte array to a BAIS string, write it to JSON like you would any other string.

Here is a Java class (ported from the original C#) that converts byte arrays to string and back.

import java.io.*;
import java.lang.*;
import java.util.*;

public class ByteArrayInString
{
  // Encodes a byte array to a string with BAIS encoding, which 
  // preserves runs of ASCII characters unchanged.
  //
  // For simplicity, this method's base-64 encoding always encodes groups of 
  // three bytes if possible (as four characters). This decision may 
  // unfortunately cut off the beginning of some ASCII runs.
  public static String convert(byte[] bytes) { return convert(bytes, true); }
  public static String convert(byte[] bytes, boolean allowControlChars)
  {
    StringBuilder sb = new StringBuilder();
    int i = 0;
    int b;
    while (i < bytes.length)
    {
      b = get(bytes,i++);
      if (isAscii(b, allowControlChars))
        sb.append((char)b);
      else {
        sb.append('\b');
        // Do binary encoding in groups of 3 bytes
        for (;; b = get(bytes,i++)) {
          int accum = b;
          System.out.println("i="+i);
          if (i < bytes.length) {
            b = get(bytes,i++);
            accum = (accum << 8) | b;
            if (i < bytes.length) {
              b = get(bytes,i++);
              accum = (accum << 8) | b;
              sb.append(encodeBase64Digit(accum >> 18));
              sb.append(encodeBase64Digit(accum >> 12));
              sb.append(encodeBase64Digit(accum >> 6));
              sb.append(encodeBase64Digit(accum));
              if (i >= bytes.length)
                break;
            } else {
              sb.append(encodeBase64Digit(accum >> 10));
              sb.append(encodeBase64Digit(accum >> 4));
              sb.append(encodeBase64Digit(accum << 2));
              break;
            }
          } else {
            sb.append(encodeBase64Digit(accum >> 2));
            sb.append(encodeBase64Digit(accum << 4));
            break;
          }
          if (isAscii(get(bytes,i), allowControlChars) &&
            (i+1 >= bytes.length || isAscii(get(bytes,i), allowControlChars)) &&
            (i+2 >= bytes.length || isAscii(get(bytes,i), allowControlChars))) {
            sb.append('!'); // return to ASCII mode
            break;
          }
        }
      }
    }
    return sb.toString();
  }

  // Decodes a BAIS string back to a byte array.
  public static byte[] convert(String s)
  {
    byte[] b;
    try {
      b = s.getBytes("UTF8");
    } catch(UnsupportedEncodingException e) { 
      throw new RuntimeException(e.getMessage());
    }
    for (int i = 0; i < b.length - 1; ++i) {
      if (b[i] == '\b') {
        int iOut = i++;

        for (;;) {
          int cur;
          if (i >= b.length || ((cur = get(b, i)) < 63 || cur > 126))
            throw new RuntimeException("String cannot be interpreted as a BAIS array");
          int digit = (cur - 64) & 63;
          int zeros = 16 - 6; // number of 0 bits on right side of accum
          int accum = digit << zeros;

          while (++i < b.length)
          {
            if ((cur = get(b, i)) < 63 || cur > 126)
              break;
            digit = (cur - 64) & 63;
            zeros -= 6;
            accum |= digit << zeros;
            if (zeros <= 8)
            {
              b[iOut++] = (byte)(accum >> 8);
              accum <<= 8;
              zeros += 8;
            }
          }

          if ((accum & 0xFF00) != 0 || (i < b.length && b[i] != '!'))
            throw new RuntimeException("String cannot be interpreted as BAIS array");
          i++;

          // Start taking bytes verbatim
          while (i < b.length && b[i] != '\b')
            b[iOut++] = b[i++];
          if (i >= b.length)
            return Arrays.copyOfRange(b, 0, iOut);
          i++;
        }
      }
    }
    return b;
  }

  static int get(byte[] bytes, int i) { return ((int)bytes[i]) & 0xFF; }

  public static int decodeBase64Digit(char digit)
    { return digit >= 63 && digit <= 126 ? (digit - 64) & 63 : -1; }
  public static char encodeBase64Digit(int digit)
    { return (char)((digit + 1 & 63) + 63); }
  static boolean isAscii(int b, boolean allowControlChars)
    { return b < 127 && (b >= 32 || (allowControlChars && b != '\b')); }
}

See also: C# unit tests.

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

How to access /storage/emulated/0/

Here, it is found at /mnt/shell/emulated/0

Check to see if python script is running

Using bash to look for a process with the current script's name. No extra file.

import commands
import os
import time
import sys

def stop_if_already_running():
    script_name = os.path.basename(__file__)
    l = commands.getstatusoutput("ps aux | grep -e '%s' | grep -v grep | awk '{print $2}'| awk '{print $2}'" % script_name)
    if l[1]:
        sys.exit(0);

To test, add

stop_if_already_running()
print "running normally"
while True:
    time.sleep(3)

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

I was recently faced with this problem, and with no simple solution since my fields can be prepopulated, I wanted to share an elegant hack I came up with by setting password type in the ready event.

Don't declare your input field as type password when creating it, but add a ready event listener to add it for you with jQuery:

<input type="text" name="pswd" id="password" maxlength="16" size="20" >

<script>
$(function(){
    document.getElementById('password').setAttribute('type', 'password');
});
</script>

Materialize CSS - Select Doesn't Seem to Render

For me none of the other answers worked because I am using the latest version of MaterializeCSS and Meteor and there is incompatability between the jquery versions, Meteor 1.1.10 uses jquery 1.11 (overriding this dependancy is not easy and will probably break Meteor/Blaze) and testing Materialise with jquery 2.2 works fine. See https://stackoverflow.com/a/34809976/2882279 for more info.

This is a known issue with dropdowns and selects in materialize 0.97.2 and 0.97.3; for more info see https://github.com/Dogfalo/materialize/issues/2265 and https://github.com/Dogfalo/materialize/commit/45feae64410252fe51e56816e664c09d83dc8931.

I'm using the Sass version of MaterializeCSS in Meteor and worked around the problem by using poetic:[email protected] in my meteor packages file to force the old version. The dropdowns now work, old jquery and all!

Print range of numbers on same line

[print(i, end = ' ') for i in range(10)]
0 1 2 3 4 5 6 7 8 9

This is a list comprehension method of answer same as @Anubhav

SQL Inner Join On Null Values

You have two options

INNER JOIN x
   ON x.qid = y.qid OR (x.qid IS NULL AND y.qid IS NULL)

or easier

INNER JOIN x
  ON x.qid IS NOT DISTINCT FROM y.qid

What is Join() in jQuery?

The practical use of this construct? It is a javascript replaceAll() on strings.

var s = 'stackoverflow_is_cool';  
s = s.split('_').join(' ');  
console.log(s);

will output:

stackoverflow is cool

How often should you use git-gc?

I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space

Centering image and text in R Markdown for a PDF report

I used the answer from Jonathan to google inserting images into LaTeX and if you would like to insert an image named image1.jpg and have it centered, your code might look like this in Rmarkdown

\begin{center}
\includegraphics{image1}
\end{center}

Keep in mind that LaTex is not asking for the file exention (.jpg). This question helped me get my answer. Thanks.

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

Angular 4 - Select default value in dropdown [Reactive Forms]

You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)] and further in component file assign default value to it.

In your_component_file.ts

this.selectedCountry = default;

In your_component_template.html

<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select> 

Plunker link

creating list of objects in Javascript

Going off of tbradley22's answer, but using .map instead:

var a = ["car", "bike", "scooter"];
a.map(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    return singleObj;
});

How to echo shell commands as they are executed

set -x will give you what you want.

Here is an example shell script to demonstrate:

#!/bin/bash
set -x #echo on

ls $PWD

This expands all variables and prints the full commands before output of the command.

Output:

+ ls /home/user/
file1.txt file2.txt

$(document).ready equivalent without jQuery

It's always good to use JavaScript equivalents as compared to jQuery. One reason is one fewer library to depend on and they are much faster than the jQuery equivalents.

One fantastic reference for jQuery equivalents is http://youmightnotneedjquery.com/.

As far as your question is concerned, I took the below code from the above link :) Only caveat is it only works with Internet Explorer 9 and later.

function ready(fn) {
    if (document.readyState != 'loading') {
        fn();
    }
    else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

How to randomly select rows in SQL?

In case someone wants a PostgreSQL solution:

select id, name
from customer
order by random()
limit 5;

Creating multiline strings in JavaScript

There are multiple ways to achieve this

1. Slash concatenation

  var MultiLine=  '1\
    2\
    3\
    4\
    5\
    6\
    7\
    8\
    9';

2. regular concatenation

var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';

3. Array Join concatenation

var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

Performance wise, Slash concatenation (first one) is the fastest.

Refer this test case for more details regarding the performance

Update:

With the ES2015, we can take advantage of its Template strings feature. With it, we just need to use back-ticks for creating multi line strings

Example:

 `<h1>{{title}}</h1>
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div><label>name: </label>{{hero.name}}</div>
  `

ReflectionException: Class ClassName does not exist - Laravel

For some reason I had to run composer dumpautoload -o. Notice flag -o which mean with optimization. I don't have any idea why it works only with it but give it a try. Perhaps it helps someone.

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

1) Also you can use lateinit If you sure do your initialization later on onCreate() or elsewhere.

Use this

lateinit var left: Node

Instead of this

var left: Node? = null

2) And there is other way that use !! end of variable when you use it like this

queue.add(left!!) // add !!

C compile error: Id returned 1 exit status

Just try " gcc filename.c -lm" while compiling the program ...it worked for me

Test class with a new() call in it with Mockito

Not that I know of, but what about doing something like this when you create an instance of TestedClass that you want to test:

TestedClass toTest = new TestedClass() {
    public LoginContext login(String user, String password) {
        //return mocked LoginContext
    }
};

Another option would be to use Mockito to create an instance of TestedClass and let the mocked instance return a LoginContext.

Spring Rest POST Json RequestBody Content type not supported

For the case where there are 2 getters for the same property, the deserializer fails Refer Link

How to remove array element in mongodb?

Try the following query:

collection.update(
  { _id: id },
  { $pull: { 'contact.phone': { number: '+1786543589455' } } }
);

It will find document with the given _id and remove the phone +1786543589455 from its contact.phone array.

You can use $unset to unset the value in the array (set it to null), but not to remove it completely.

Reading CSV files using C#

Another one to this list, Cinchoo ETL - an open source library to read and write CSV files

For a sample CSV file below

Id, Name
1, Tom
2, Mark

Quickly you can load them using library as below

using (var reader = new ChoCSVReader("test.csv").WithFirstLineHeader())
{
   foreach (dynamic item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

If you have POCO class matching the CSV file

public class Employee
{
   public int Id { get; set; }
   public string Name { get; set; }
}

You can use it to load the CSV file as below

using (var reader = new ChoCSVReader<Employee>("test.csv").WithFirstLineHeader())
{
   foreach (var item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

Please check out articles at CodeProject on how to use it.

Disclaimer: I'm the author of this library

Can you do a partial checkout with Subversion?

If you already have the full local copy, you can remove unwanted sub folders by using --set-depth command.

svn update --set-depth=exclude www

See: http://blogs.collab.net/subversion/sparse-directories-now-with-exclusion

The set-depth command support multipile paths.

Updating the root local copy will not change the depth of the modified folder.

To restore the folder to being recusively checkingout, you could use --set-depth again with infinity param.

svn update --set-depth=infinity www

How do I control how Emacs makes backup files?

If you've ever been saved by an Emacs backup file, you probably want more of them, not less of them. It is annoying that they go in the same directory as the file you're editing, but that is easy to change. You can make all backup files go into a directory by putting something like the following in your .emacs.

(setq backup-directory-alist `(("." . "~/.saves")))

There are a number of arcane details associated with how Emacs might create your backup files. Should it rename the original and write out the edited buffer? What if the original is linked? In general, the safest but slowest bet is to always make backups by copying.

(setq backup-by-copying t)

If that's too slow for some reason you might also have a look at backup-by-copying-when-linked.

Since your backups are all in their own place now, you might want more of them, rather than less of them. Have a look at the Emacs documentation for these variables (with C-h v).

(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)

Finally, if you absolutely must have no backup files:

(setq make-backup-files nil)

It makes me sick to think of it though.

css 100% width div not taking up full width of parent

The problem is caused by your #grid having a width:1140px.

You need to set a min-width:1140px on the body.

This will stop the body from getting smaller than the #grid. Remove width:100% as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/

html, body{
    margin:0;
    padding:0;
    min-width: 1140px; /* this is the important part*/
}
#grid-container{
    background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
    width:1140px;
    margin:0px auto;
}

Date to milliseconds and back to date in Swift

I don't understand why you're doing anything with strings...

extension Date {
    var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }

    init(milliseconds:Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}


Date().millisecondsSince1970 // 1476889390939
Date(milliseconds: 0) // "Dec 31, 1969, 4:00 PM" (PDT variant of 1970 UTC)

Your project contains error(s), please fix it before running it

Delete the .android folder from your Documents&settings\User\ on XP and \User\ on Win7. Recreate the AVD again and create a new project.

macOS on VMware doesn't recognize iOS device

Do what is suggested in the answer, but make sure you also click inside the VM so that OSX has the focus before you plug in the phone. In my case, I had to do that to make it work.

How to get .app file of a xcode application

I know as for Appium Mobile Automation you need .app file to run ios app on Simulator.So as like me many of you face this problem. So I explain how to create that .app file and where it is located.

1.Open Xcode.

2.Click on your sample project.(If you don't have then click on create new xcode project)

3.In left panel inside screen you will see products folder then click and expand that, you will see the list.

  1. Then right click on .app file and click on Show in Finder and thats your .app file. Now you can copy or use that path in capabilities for appium desktop or in framework.

Check the attached screenshot for detail

Remote debugging Tomcat with Eclipse

First of all, if you open catalina.bat with text editor, you see that: "Do not set the variables in this script....." So never change it in that script, instead you can do below steps:

  1. It advices you to create a new bat file with name "setenv.bat".
  2. Then set 2 variables in that bat file such as:

    set CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

    set JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

  3. Lastly run that at cmd that: "catalina.bat jpda start"

  4. In IDE, create remote debug configuration and set host to related server ip and port to 8000.

On localhost, how do I pick a free port number?

Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind().

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.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

Node.js Hostname/IP doesn't match certificate's altnames

After verifying that the certificate is issued by a known Certificate Authority (CA), the Subject Alternative Names will be checked, or the Common Name will be checked, to verify that the hostname matches. This is in the checkServerIdentity function. If the certificate has Subject Alternative Names and the hostname is not listed, you'll see the error message described:

Hostname/IP doesn't match certificate's altnames

If you have the CA cert that is used to generate the certificate you're using (usually the case when using self-signed certificates), this can be provided with

var r = require('request');

var opts = {
    method: "POST",
    ca: fs.readFileSync("ca.cer")
};

r('https://api.dropbox.com', opts, function (error, response, body) {
    // do something
});

This will verify that the certificate is issued by the CA provided, but hostname verification will still be performed. Just supplying the CA will be enough if the cert contains the hostname in the Subject Alternative Names. If it doesn't and you also want to skip hostname verification, you can pass a noop function for checkServerIdentity

var r = require('request');

var opts = {
    method: "POST",
    ca: fs.readFileSync("ca.cer"),
    agentOptions: { checkServerIdentity: function() {} }
};

r('https://api.dropbox.com', opts, function (error, response, body) {
    // do something
});

Oracle JDBC intermittent Connection Issue

Disabling SQL Net Banners saved us.

Field 'browser' doesn't contain a valid alias configuration

In my experience, this error was as a result of improper naming of aliases in Webpack. In that I had an alias named redux and webpack tried looking for the redux that comes with the redux package in my alias path.

To fix this, I had to rename the alias to something different like Redux.

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had similar problem while using in postman. for POST request under header section add these as

key:valuepair

Content-Type:application/json Accept:application/json

i hope it will work.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

REMOTE_ADDR can not be trusted.

Anyway, try

$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
    $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}

Edit: Also, does your server's router have port forwarding enabled? It may be possible that it's messing with the packets.

Security warning: REMOTE_ADDR can be fully trusted! It comes from your own webserver and contains the IP that was used to access it. You don't even need to quote() it for SQL inserts.
But HTTP_X_FORWARDED_FOR is taken directly from the HTTP headers, it can contain the picture of a cat, malicious code, any content. Treat it like that, never trust it.

How can I include a YAML file inside another?

Includes are not directly supported in YAML as far as I know, you will have to provide a mechanism yourself however, this is generally easy to do.

I have used YAML as a configuration language in my python apps, and in this case often define a convention like this:

>>> main.yml <<<
includes: [ wibble.yml, wobble.yml]

Then in my (python) code I do:

import yaml
cfg = yaml.load(open("main.yml"))
for inc in cfg.get("includes", []):
   cfg.update(yaml.load(open(inc)))

The only down side is that variables in the includes will always override the variables in main, and there is no way to change that precedence by changing where the "includes: statement appears in the main.yml file.

On a slightly different point, YAML doesn't support includes as its not really designed as as exclusively as a file based mark up. What would an include mean if you got it in a response to an AJAX request?

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

How do I replace a character at a particular index in JavaScript?

The methods on here are complicated. I would do it this way:

var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");

This is as simple as it gets.

set column width of a gridview in asp.net

I know this is an old Question, but it popped up when I was looking for a solution to the same issue, so I thought that I would post what worked for me.

<asp:BoundField DataField="Description" HeaderText="Bond Event" ItemStyle-Width="300px" />

I used the ItemStyle-Width attribute on my BoundField and it worked very nicely I haven't had any issues yet.

I didn't need to add anything else to the rest of the code to make this work either.

What do pty and tty mean?

tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.

pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.

How to save as a new file and keep working on the original one in Vim?

Use the :w command with a filename:

:w other_filename

C#: Limit the length of a string?

Here is another alternative answer to this issue. This extension method works quite well. This solves the issues of the string being shorter than the maximum length and also the maximum length being negative.

public static string Left( this string str, int length ) {
  if (str == null)
    return str;
  return str.Substring(0, Math.Min(Math.Abs(length), str.Length));
}

Another solution would be to limit the length to be non-negative values, and just zero-out negative values.

public static string Left( this string str, int length ) {
  if (str == null)
    return str;
  return str.Substring(0, Math.Min(Math.Max(0,length), str.Length));
}

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

If you are suffering from "ADB not responding. If you’d like to retry, then please manually kill ‘adb’ and click ‘Restart’ or terminal appear Syntax error: “)” unexpected" then perhaps you are using 32bit OS and platform-tools has updated up 23.1. The solution is to go back to the platform-tools 23.0.1.

You can download the platform-tools 23.0.1 for Linux here , for windowns here and Mac here

After the download, go to your sdk location > platform-tools folder to delete old platform-tools in sdk and paste down into the downloaded one.

Woohooo ... it should work.

This is a bug with latest ADT.

Suppress command line output

Because error messages often go to stderr not stdout.

Change the invocation to this:

taskkill /im "test.exe" /f >nul 2>&1

and all will be better.

That works because stdout is file descriptor 1, and stderr is file descriptor 2 by convention. (0 is stdin, incidentally.) The 2>&1 copies output file descriptor 2 from the new value of 1, which was just redirected to the null device.

This syntax is (loosely) borrowed from many Unix shells, but you do have to be careful because there are subtle differences between the shell syntax and CMD.EXE.

Update: I know the OP understands the special nature of the "file" named NUL I'm writing to here, but a commenter didn't and so let me digress with a little more detail on that aspect.

Going all the way back to the earliest releases of MSDOS, certain file names were preempted by the file system kernel and used to refer to devices. The earliest list of those names included NUL, PRN, CON, AUX and COM1 through COM4. NUL is the null device. It can always be opened for either reading or writing, any amount can be written on it, and reads always succeed but return no data. The others include the parallel printer port, the console, and up to four serial ports. As of MSDOS 5, there were several more reserved names, but the basic convention was very well established.

When Windows was created, it started life as a fairly thin application switching layer on top of the MSDOS kernel, and thus had the same file name restrictions. When Windows NT was created as a true operating system in its own right, names like NUL and COM1 were too widely assumed to work to permit their elimination. However, the idea that new devices would always get names that would block future user of those names for actual files is obviously unreasonable.

Windows NT and all versions that follow (2K, XP, 7, and now 8) all follow use the much more elaborate NT Namespace from kernel code and to carefully constructed and highly non-portable user space code. In that name space, device drivers are visible through the \Device folder. To support the required backward compatibility there is a special mechanism using the \DosDevices folder that implements the list of reserved file names in any file system folder. User code can brows this internal name space using an API layer below the usual Win32 API; a good tool to explore the kernel namespace is WinObj from the SysInternals group at Microsoft.

For a complete description of the rules surrounding legal names of files (and devices) in Windows, this page at MSDN will be both informative and daunting. The rules are a lot more complicated than they ought to be, and it is actually impossible to answer some simple questions such as "how long is the longest legal fully qualified path name?".

Alternative for <blink>

Blinking text with HTML and CSS only

<span class="blinking">I am blinking!!!</span>

And Now CSS code

    .blinking{
        animation:blinkingText 0.8s infinite;
    }

    @keyframes blinkingText{
        0%{     color: #000;    }
        49%{    color: transparent; }
        50%{    color: transparent; }
        99%{    color:transparent;  }
        100%{   color: #000;    }
    }

Android Fragment onAttach() deprecated

This worked for me when i have userdefined Interface 'TopSectionListener', its object activitycommander:

  //This method gets called whenever we attach fragment to the activity
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    Activity a=getActivity();
    try {
        if(context instanceof Activity)
           this.activitycommander=(TopSectionListener)a;
    }catch (ClassCastException e){
        throw new ClassCastException(a.toString());}

}

Setting unique Constraint with fluent API?

As an addition to Yorro's answer, it can also be done by using attributes.

Sample for int type unique key combination:

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }

If the data type is string, then MaxLength attribute must be added:

[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }

[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }

If there is a domain/storage model separation concern, using Metadatatype attribute/class can be an option: https://msdn.microsoft.com/en-us/library/ff664465%28v=pandp.50%29.aspx?f=255&MSPPError=-2147217396


A quick console app example:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace EFIndexTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new AppDbContext())
            {
                var newUser = new User { UniqueKeyIntPart1 = 1, UniqueKeyIntPart2 = 1, UniqueKeyStringPart1 = "A", UniqueKeyStringPart2 = "A" };
                context.UserSet.Add(newUser);
                context.SaveChanges();
            }
        }
    }

    [MetadataType(typeof(UserMetadata))]
    public class User
    {
        public int Id { get; set; }
        public int UniqueKeyIntPart1 { get; set; }
        public int UniqueKeyIntPart2 { get; set; }
        public string UniqueKeyStringPart1 { get; set; }
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class UserMetadata
    {
        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
        public int UniqueKeyIntPart1 { get; set; }

        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
        public int UniqueKeyIntPart2 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
        [MaxLength(50)]
        public string UniqueKeyStringPart1 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
        [MaxLength(50)]
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class AppDbContext : DbContext
    {
        public virtual DbSet<User> UserSet { get; set; }
    }
}

using setTimeout on promise chain

The shorter ES6 version of the answer:

const delay = t => new Promise(resolve => setTimeout(resolve, t));

And then you can do:

delay(3000).then(() => console.log('Hello'));

How to compare binary files to check if they are the same?

I found Visual Binary Diff was what I was looking for, available on:

  • Ubuntu:

    sudo apt install vbindiff
    
  • Arch Linux:

    sudo pacman -S vbindiff
    
  • Mac OS X via MacPorts:

    port install vbindiff
    
  • Mac OS X via Homebrew:

    brew install vbindiff
    

how to add picasso library in android studio

Add the Picasso library in Dependency

dependencies {
       ...
       implementation 'com.squareup.picasso:picasso:2.71828'
       ...
    }

Sync The Project Create one imageview in Layout

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

Add the Internet permission in Manifest file

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

//Initialize ImageView

ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Loading image from below url into imageView

Picasso.get()
   .load("YOUR IMAGE URL HERE")
   .into(imageView);

WPF Button with Image

Most simple approach would be using the Image tag.

<Button Name="btn" Width="26" Height="26" Click="btnClick"> 
   <Image Source="Resource/btn-icon.png"/>
</Button>

Suppose your image file is added in Resource folder

UITableView load more when scrolling to bottom like Facebook application

Use limit and offset in your queries and fill your tableview with that content. When the user scrolls down, load the next offset.

Implement the tableView:willDisplayCell:forRowAtIndexPath: method in your UITableViewDelegate and check to see if it's the last row

WinForms DataGridView font size

I think it's easiest:

First set any Label as you like (Italic, Bold, Size etc.) And:

yourDataGridView.Font = anyLabel.Font;

find . -type f -exec chmod 644 {} ;

A good alternative is this:

find . -type f | xargs chmod -v 644

and for directories:

find . -type d | xargs chmod -v 755

and to be more explicit:

find . -type f | xargs -I{} chmod -v 644 {}

Global javascript variable inside document.ready

Use window.intro inside of $(document).ready().

What is so bad about singletons?

A singleton gets implemented using a static method. Static methods are avoided by people who do unit testing because they cannot be mocked or stubbed. Most people on this site are big proponents of unit testing. The generally most accepted convention to avoid them is using the inversion of control pattern.

What's the difference between compiled and interpreted language?

Here is the Basic Difference between Compiler vs Interpreter Language.

Compiler Language

  • Takes entire program as single input and converts it into object code which is stored in the file.
  • Intermediate Object code is generated
  • e.g: C,C++
  • Compiled programs run faster because compilation is done before execution.
  • Memory requirement is more due to the creation of object code.
  • Error are displayed after the entire program is compiled
  • Source code ---Compiler ---Machine Code ---Output

Interpreter Language:

  • Takes single instruction as single input and executes instructions.
  • Intermediate Object code is NOT generated
  • e.g: Perl, Python, Matlab
  • Interpreted programs run slower because compilation and execution take place simultaneously.
  • Memory requirement is less.
  • Error are displayed for every single instruction.
  • Source Code ---Interpreter ---Output

Long press on UITableView

I've used Anna-Karenina's answer, and it works almost great with a very serious bug.

If you're using sections, long-pressing the section title will give you a wrong result of pressing the first row on that section, I've added a fixed version below (including the filtering of dummy calls based on the gesture state, per Anna-Karenina suggestion).

- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {

        CGPoint p = [gestureRecognizer locationInView:self.tableView];

        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
        if (indexPath == nil) {
            NSLog(@"long press on table view but not on a row");
        } else {
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            if (cell.isHighlighted) {
                NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
            }
        }
    }
}

Service will not start: error 1067: the process terminated unexpectedly

This is a problem related permission. Make sure that the current user has access to the folder which contains installation files.

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Which is better: <script type="text/javascript">...</script> or <script>...</script>

You need to use <script type="text/javascript"> </script> unless you're using html5. In that case you are encouraged to prefer <script> ... </script> (because type attribute is specified by default to that value)

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

laravel 5.4 upload image

Try this code. This will solve your problem.

public function fileUpload(Request $request) {
    $this->validate($request, [
        'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    if ($request->hasFile('input_img')) {
        $image = $request->file('input_img');
        $name = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $name);
        $this->save();

        return back()->with('success','Image Upload successfully');
    }
}

How to change color of Android ListView separator line?

You can also get the colors from your resources by using:

dateView.setDivider(new ColorDrawable(_context.getResources().getColor(R.color.textlight)));
dateView.setDividerHeight(1);

What are the performance characteristics of sqlite with very large database files?

Besides the usual recommendation:

  1. Drop index for bulk insert.
  2. Batch inserts/updates in large transactions.
  3. Tune your buffer cache/disable journal /w PRAGMAs.
  4. Use a 64bit machine (to be able to use lots of cache™).
  5. [added July 2014] Use common table expression (CTE) instead of running multiple SQL queries! Requires SQLite release 3.8.3.

I have learnt the following from my experience with SQLite3:

  1. For maximum insert speed, don't use schema with any column constraint. (Alter table later as needed You can't add constraints with ALTER TABLE).
  2. Optimize your schema to store what you need. Sometimes this means breaking down tables and/or even compressing/transforming your data before inserting to the database. A great example is to storing IP addresses as (long) integers.
  3. One table per db file - to minimize lock contention. (Use ATTACH DATABASE if you want to have a single connection object.
  4. SQLite can store different types of data in the same column (dynamic typing), use that to your advantage.

Question/comment welcome. ;-)

Using Eloquent ORM in Laravel to perform search of database using LIKE

Use double quotes instead of single quote eg :

where('customer.name', 'LIKE', "%$findcustomer%")

Below is my code:

public function searchCustomer($findcustomer)
{
    $customer = DB::table('customer')
                  ->where('customer.name', 'LIKE', "%$findcustomer%")
                  ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                  ->get();

    return View::make("your view here");
}

Amazon products API - Looking for basic overview and information

I agree that Amazon appears to be intentionally obfuscating even how to find the API documentation, as well as use it. I'm just speculating though.

Renaming the services from "ECS" to "Product Advertising API" was probably also not the best move, it essentially invalidated all that Google mojo they had built up over time.

It took me quite a while to 'discover' this updated link for the Product Advertising API. I don't remember being able to easily discover it through the typical 'Developer' link on the Amazon webpage. This documentation appears to valid and what I've worked from recently.

The change to authentication procedures also seems to add further complexity, but I'm sure they have a reason for it.

I use SOAP via C# to communicate with Amazon Product API.

With the REST API you have to encrypt the whole URL in a fairly specific way. The params have to be sorted, etc. There is just more to do. With the SOAP API, you just encrypt the operation+timestamp, and thats it.

Adam O'Neil's post here, How to get album, dvd, and blueray cover art from Amazon, walks through the SOAP with C# method. Its not the original sample I pulled down, and contrary to his comment, it was not an official Amazon sample I stumbled on, though the code looks identical. However, Adam does a good job at presenting all the necessary steps. I wish I could credit the original author.

How to align this span to the right of the div?

You can do this without modifying the html. http://jsfiddle.net/8JwhZ/1085/

<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>

.title span:nth-of-type(1) { float:right }
.title span:nth-of-type(2) { float:left }

Test credit card numbers for use with PayPal sandbox

If a credit card is already added to a PayPal account then it won't let you use that card to process directly with Payments Advanced. The system expects buyers to login to PayPal and just choose that credit card as their funding source if they want to pay with it.

As for testing on the sandbox, I've always used old, expired credit cards I have laying around and they seem to work fine for me.

You could always try the ones starting on page 87 of the PayFlow documentation, too. They should work.

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

Python - How to convert JSON File to Dataframe

Creating dataframe from dictionary object.

import pandas as pd
data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]
df = pd.DataFrame.from_dict(data, orient='columns')

df
Out[4]:
   age  name
0   27  vikash
1   14  Satyam

If you have nested columns then you first need to normalize the data:

data = [
  {
    'name': {
      'first': 'vikash',
      'last': 'singh'
    },
    'age': 27
  },
  {
    'name': {
      'first': 'satyam',
      'last': 'singh'
    },
    'age': 14
  }
]

df = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')

df    
Out[8]:
age name.first  name.last
0   27  vikash  singh
1   14  satyam  singh

Source:

To switch from vertical split to horizontal split fast in Vim

In VIM, take a look at the following to see different alternatives for what you might have done:

:help opening-window

For instance:

Ctrl-W s
Ctrl-W o
Ctrl-W v
Ctrl-W o
Ctrl-W s
...

Direct download from Google Drive using Google Drive API

I simply create a javascript so that it automatically capture the link and download and close the tab with the help of tampermonkey.

// ==UserScript==
// @name         Bypass Google drive virus scan
// @namespace    SmartManoj
// @version      0.1
// @description  Quickly get the download link
// @author       SmartManoj
// @match        https://drive.google.com/uc?id=*&export=download*
// @grant        none
// ==/UserScript==

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function demo() {
        await sleep(5000);
        window.close();
    }

    (function() {
        location.replace(document.getElementById("uc-download-link").href);
        demo();
    })();

Similarly you can get the html source of the url and download in java.

How to get the current location in Google Maps Android API v2?

To get the location when the user clicks on a button call this method in the onClick-

void getCurrentLocation() {
    Location myLocation  = mMap.getMyLocation();
    if(myLocation!=null)
    {
        double dLatitude = myLocation.getLatitude();
        double dLongitude = myLocation.getLongitude();
        Log.i("APPLICATION"," : "+dLatitude);
        Log.i("APPLICATION"," : "+dLongitude);
        mMap.addMarker(new MarkerOptions().position(
                new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));

    }
    else
    {
        Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
    }

}

Also make sure that the

setMyLocationEnabled

is set to true.

Try and see if this works...

How to update-alternatives to Python 3 without breaking apt?

Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode


root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0


root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.

How can I upgrade NumPy?

This works for me:

pip install numpy --upgrade

Finding three elements in an array whose sum is closest to a given number

Is there any efficient algorithm other than brute force search to find the three integers?

Yep; we can solve this in O(n2) time! First, consider that your problem P can be phrased equivalently in a slightly different way that eliminates the need for a "target value":

original problem P: Given an array A of n integers and a target value S, does there exist a 3-tuple from A that sums to S?

modified problem P': Given an array A of n integers, does there exist a 3-tuple from A that sums to zero?

Notice that you can go from this version of the problem P' from P by subtracting your S/3 from each element in A, but now you don't need the target value anymore.

Clearly, if we simply test all possible 3-tuples, we'd solve the problem in O(n3) -- that's the brute-force baseline. Is it possible to do better? What if we pick the tuples in a somewhat smarter way?

First, we invest some time to sort the array, which costs us an initial penalty of O(n log n). Now we execute this algorithm:

for (i in 1..n-2) {
  j = i+1  // Start right after i.
  k = n    // Start at the end of the array.

  while (k >= j) {
    // We got a match! All done.
    if (A[i] + A[j] + A[k] == 0) return (A[i], A[j], A[k])

    // We didn't match. Let's try to get a little closer:
    //   If the sum was too big, decrement k.
    //   If the sum was too small, increment j.
    (A[i] + A[j] + A[k] > 0) ? k-- : j++
  }
  // When the while-loop finishes, j and k have passed each other and there's
  // no more useful combinations that we can try with this i.
}

This algorithm works by placing three pointers, i, j, and k at various points in the array. i starts off at the beginning and slowly works its way to the end. k points to the very last element. j points to where i has started at. We iteratively try to sum the elements at their respective indices, and each time one of the following happens:

  • The sum is exactly right! We've found the answer.
  • The sum was too small. Move j closer to the end to select the next biggest number.
  • The sum was too big. Move k closer to the beginning to select the next smallest number.

For each i, the pointers of j and k will gradually get closer to each other. Eventually they will pass each other, and at that point we don't need to try anything else for that i, since we'd be summing the same elements, just in a different order. After that point, we try the next i and repeat.

Eventually, we'll either exhaust the useful possibilities, or we'll find the solution. You can see that this is O(n2) since we execute the outer loop O(n) times and we execute the inner loop O(n) times. It's possible to do this sub-quadratically if you get really fancy, by representing each integer as a bit vector and performing a fast Fourier transform, but that's beyond the scope of this answer.


Note: Because this is an interview question, I've cheated a little bit here: this algorithm allows the selection of the same element multiple times. That is, (-1, -1, 2) would be a valid solution, as would (0, 0, 0). It also finds only the exact answers, not the closest answer, as the title mentions. As an exercise to the reader, I'll let you figure out how to make it work with distinct elements only (but it's a very simple change) and exact answers (which is also a simple change).

How do you make a HTTP request with C++?

Windows code:

#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <vector>
#include <locale>
#include <sstream>
using namespace std;
#pragma comment(lib,"ws2_32.lib")




int main( void ){

WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount=0;
int rowCount=0;
struct hostent *host;
locale local;
char buffer[10000];
int i = 0 ;
int nDataLength;
string website_HTML;

// website url
string url = "www.google.com";

//HTTP GET
string get_http = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n";


    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
        cout << "WSAStartup failed.\n";
        system("pause");
        //return 1;
    }

    Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    host = gethostbyname(url.c_str());

    SockAddr.sin_port=htons(80);
    SockAddr.sin_family=AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

    if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
        cout << "Could not connect";
        system("pause");
        //return 1;
    }

    // send GET / HTTP
    send(Socket,get_http.c_str(), strlen(get_http.c_str()),0 );

    // recieve html
    while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){        
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'){

            website_HTML+=buffer[i];
            i += 1;
        }               
    }

    closesocket(Socket);
    WSACleanup();

    // Display HTML source 
    cout<<website_HTML;

    // pause
    cout<<"\n\nPress ANY key to close.\n\n";
    cin.ignore(); cin.get(); 


 return 0;
}

Here is a much better implementation:

#include <windows.h>
#include <string>
#include <stdio.h>

using std::string;

#pragma comment(lib,"ws2_32.lib")


HINSTANCE hInst;
WSADATA wsaData;
void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename);
SOCKET connectToServer(char *szServerName, WORD portNum);
int getHeaderLength(char *content);
char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut);


int main()
{
    const int bufLen = 1024;
    char *szUrl = "http://stackoverflow.com";
    long fileSize;
    char *memBuffer, *headerBuffer;
    FILE *fp;

    memBuffer = headerBuffer = NULL;

    if ( WSAStartup(0x101, &wsaData) != 0)
        return -1;


    memBuffer = readUrl2(szUrl, fileSize, &headerBuffer);
    printf("returned from readUrl\n");
    printf("data returned:\n%s", memBuffer);
    if (fileSize != 0)
    {
        printf("Got some data\n");
        fp = fopen("downloaded.file", "wb");
        fwrite(memBuffer, 1, fileSize, fp);
        fclose(fp);
         delete(memBuffer);
        delete(headerBuffer);
    }

    WSACleanup();
    return 0;
}


void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename)
{
    string::size_type n;
    string url = mUrl;

    if (url.substr(0,7) == "http://")
        url.erase(0,7);

    if (url.substr(0,8) == "https://")
        url.erase(0,8);

    n = url.find('/');
    if (n != string::npos)
    {
        serverName = url.substr(0,n);
        filepath = url.substr(n);
        n = filepath.rfind('/');
        filename = filepath.substr(n+1);
    }

    else
    {
        serverName = url;
        filepath = "/";
        filename = "";
    }
}

SOCKET connectToServer(char *szServerName, WORD portNum)
{
    struct hostent *hp;
    unsigned int addr;
    struct sockaddr_in server;
    SOCKET conn;

    conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (conn == INVALID_SOCKET)
        return NULL;

    if(inet_addr(szServerName)==INADDR_NONE)
    {
        hp=gethostbyname(szServerName);
    }
    else
    {
        addr=inet_addr(szServerName);
        hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
    }

    if(hp==NULL)
    {
        closesocket(conn);
        return NULL;
    }

    server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
    server.sin_family=AF_INET;
    server.sin_port=htons(portNum);
    if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
    {
        closesocket(conn);
        return NULL;
    }
    return conn;
}

int getHeaderLength(char *content)
{
    const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r";
    char *findPos;
    int ofset = -1;

    findPos = strstr(content, srchStr1);
    if (findPos != NULL)
    {
        ofset = findPos - content;
        ofset += strlen(srchStr1);
    }

    else
    {
        findPos = strstr(content, srchStr2);
        if (findPos != NULL)
        {
            ofset = findPos - content;
            ofset += strlen(srchStr2);
        }
    }
    return ofset;
}

char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut)
{
    const int bufSize = 512;
    char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize];
    char *tmpResult=NULL, *result;
    SOCKET conn;
    string server, filepath, filename;
    long totalBytesRead, thisReadSize, headerLen;

    mParseUrl(szUrl, server, filepath, filename);

    ///////////// step 1, connect //////////////////////
    conn = connectToServer((char*)server.c_str(), 80);

    ///////////// step 2, send GET request /////////////
    sprintf(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str());
    strcpy(sendBuffer, tmpBuffer);
    strcat(sendBuffer, "\r\n");
    sprintf(tmpBuffer, "Host: %s", server.c_str());
    strcat(sendBuffer, tmpBuffer);
    strcat(sendBuffer, "\r\n");
    strcat(sendBuffer, "\r\n");
    send(conn, sendBuffer, strlen(sendBuffer), 0);

//    SetWindowText(edit3Hwnd, sendBuffer);
    printf("Buffer being sent:\n%s", sendBuffer);

    ///////////// step 3 - get received bytes ////////////////
    // Receive until the peer closes the connection
    totalBytesRead = 0;
    while(1)
    {
        memset(readBuffer, 0, bufSize);
        thisReadSize = recv (conn, readBuffer, bufSize, 0);

        if ( thisReadSize <= 0 )
            break;

        tmpResult = (char*)realloc(tmpResult, thisReadSize+totalBytesRead);

        memcpy(tmpResult+totalBytesRead, readBuffer, thisReadSize);
        totalBytesRead += thisReadSize;
    }

    headerLen = getHeaderLength(tmpResult);
    long contenLen = totalBytesRead-headerLen;
    result = new char[contenLen+1];
    memcpy(result, tmpResult+headerLen, contenLen);
    result[contenLen] = 0x0;
    char *myTmp;

    myTmp = new char[headerLen+1];
    strncpy(myTmp, tmpResult, headerLen);
    myTmp[headerLen] = NULL;
    delete(tmpResult);
    *headerOut = myTmp;

    bytesReturnedOut = contenLen;
    closesocket(conn);
    return(result);
}

javascript get x and y coordinates on mouse click

Like this.

_x000D_
_x000D_
function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

Should MySQL have its timezone set to UTC?

How about making your app agnostic of the server's timezone?

Owing to any of these possible scenarios:

  • You might not have control over the web/database server's timezone settings
  • You might mess up and set the settings incorrectly
  • There are so many settings as described in the other answers, and so many things to keep track of, that you might miss something
  • An update on the server, or a software reset, or another admin, might unknowing reset the servers' timezone to the default - thus breaking your application

All of the above scenarios give rise to breaking of your application's time calculations. Thus it appears that the better approach is to make your application work independent of the server's timezone.

The idea is simply to always create dates in UTC before storing them into the database, and always re-create them from the stored values in UTC as well. This way, the time calculations won't ever be incorrect, because they're always in UTC. This can be achieved by explicity stating the DateTimeZone parameter when creating a PHP DateTime object.

On the other hand, the client side functionality can be configured to convert all dates/times received from the server to the client's timezone. Libraries like moment.js make this super easy to do.

For example, when storing a date in the database, instead of using the NOW() function of MySQL, create the timestamp string in UTC as follows:

// Storing dates
$date = new DateTime('now', new DateTimeZone('UTC'));
$sql = 'insert into table_name (date_column) values ("' . $date . '")';

// Retreiving dates
$sql = 'select date_column from table_name where condition';
$dateInUTC = new DateTime($date_string_from_db, new DateTimeZone('UTC'));

You can set the default timezone in PHP for all dates created, thus eliminating the need to initialize the DateTimeZone class every time you want to create a date.

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

How to install pip in CentOS 7?

Below are the steps I followed to install python34 and pip

yum update -y
yum -y install yum-utils
yum -y groupinstall development
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum makecache
yum -y install python34u  python34u-pip
python3.6 -v
echo "alias python=/usr/bin/python3.4" >> ~/.bash_profile
source ~/.bash_profile
pip3 install --upgrade pip

# if yum install python34u-pip doesnt work, try 

curl https://bootstrap.pypa.io/get-pip.py | python

Using Python 3 in virtualenv

I tried all the above stuff, it still didn't work. So as a brute force, I just re-installed the anaconda, re-installed the virtualenv... and it worked.

Amans-MacBook-Pro:~ amanmadan$ pip install virtualenv
You are using pip version 6.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting virtualenv
  Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 3.5MB 114kB/s 
Installing collected packages: virtualenv
Successfully installed virtualenv-15.0.3
Amans-MacBook-Pro:python amanmadan$ virtualenv my_env
New python executable in /Users/amanmadan/Documents/HadoopStuff/python/my_env/bin/python
Installing setuptools, pip, wheel...done.
Amans-MacBook-Pro:python amanmadan$ 

Export to xls using angularjs

A cheap way to do this is to use Angular to generate a <table> and use FileSaver.js to output the table as an .xls file for the user to download. Excel will be able to open the HTML table as a spreadsheet.

<div id="exportable">
    <table width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>DoB</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items">
                <td>{{item.name}}</td>
                <td>{{item.email}}</td>
                <td>{{item.dob | date:'MM/dd/yy'}}</td>
            </tr>
        </tbody>
    </table>
</div>

Export call:

var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    saveAs(blob, "Report.xls");
};

Demo: http://jsfiddle.net/TheSharpieOne/XNVj3/1/

Updated demo with checkbox functionality and question's data. Demo: http://jsfiddle.net/TheSharpieOne/XNVj3/3/

How to implement the Android ActionBar back button?

Building on Jared's answer, I had to enable and implement the action bar back button behavior in several activities and created this helper class to reduce code duplication.

public final class ActionBarHelper {
    public static void enableBackButton(AppCompatActivity context) {
        if(context == null) return;

        ActionBar actionBar = context.getSupportActionBar();
        if (actionBar == null) return;

        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

Usage in an activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    ActionBarHelper.enableBackButton(this);
}

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Swapping pointers in C (char, int)

You need to understand the different between pass-by-reference and pass-by-value.

Basically, C only support pass-by-value. So you can't reference a variable directly when pass it to a function. If you want to change the variable out a function, which the swap do, you need to use pass-by-reference. To implement pass-by-reference in C, need to use pointer, which can dereference to the value.

The function:

void intSwap(int* a, int* b)

It pass two pointers value to intSwap, and in the function, you swap the values which a/b pointed to, but not the pointer itself. That's why R. Martinho & Dan Fego said it swap two integers, not pointers.

For chars, I think you mean string, are more complicate. String in C is implement as a chars array, which referenced by a char*, a pointer, as the string value. And if you want to pass a char* by pass-by-reference, you need to use the ponter of char*, so you get char**.

Maybe the code below more clearly:

typedef char* str;
void strSwap(str* a, str* b);

The syntax swap(int& a, int& b) is C++, which mean pass-by-reference directly. Maybe some C compiler implement too.

Hope I make it more clearly, not comfuse.

appending array to FormData and send via AJAX

You can also send an array via FormData this way:

var formData = new FormData;
var arr = ['this', 'is', 'an', 'array'];
for (var i = 0; i < arr.length; i++) {
    formData.append('arr[]', arr[i]);
}

So you can write arr[] the same way as you do it with a simple HTML form. In case of PHP it should work.

You may find this article useful: How to pass an array within a query string?

How to delete from multiple tables in MySQL?

Use this

DELETE FROM `articles`, `comments` 
USING `articles`,`comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

or

DELETE `articles`, `comments` 
FROM `articles`, `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

ARM compilation error, VFP registers used by executable, not object file

I encountered the issue using Atollic for ARM on STM32F4 (I guess it applies to all STM32 with FPU).

Using SW floating point didn't worked well for me (thus compiling correctly).

When STM32cubeMX generates code for TrueStudio (Atollic), it doesn't set an FPU unit in C/C++ build settings (not sure about generated code for other IDEs).

Set a FPU in "Target" for (under project Properties build settings):

  • Assembler
  • C Compiler
  • C Linker

Then you have the choice to Mix HW/SW fp or use HW.

Generated command lines are added with this for the intended target:

-mfloat-abi=hard -mfpu=fpv4-sp-d16

How to force two figures to stay on the same page in LaTeX?

try [h!] first but else you can do it the ugly way.

LateX is a bit hard in placing images with such constraints as it manages placing itself. What I usually do if I want a figure right in that spot is do something like|:

text in front of image here

 \newpage 
 \figure1 
 \figure2

text after images here

I know it may not be the correct way to do it but it works like a charm :).

//edit

You can do the same if you want a little text at top of the page but then just use /clearpage. Of course you can also scale them a bit smaller so it does not happen anymore. Maybe the non-seen whitespace is a bit larger than you suspect, I always try to scale down my image until they do appear on the same page, just to know for sure there is not like 1% overlap only making all of this not needed.

Breaking up long strings on multiple lines in Ruby without stripping newlines

Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.

class Subscription
  def warning_message
    <<~HEREDOC
      Subscription expiring soon!
      Your free trial will expire in #{days_until_expiration} days.
      Please update your billing information.
    HEREDOC
  end
end

Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

The indentation of the least-indented line will be removed from each line of the content.

Sequence contains more than one element

SingleOrDefault method throws an Exception if there is more than one element in the sequence.

Apparently, your query in GetCustomer is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.

Where can I view Tomcat log files in Eclipse?

Go to the "Server" view, then double-click the Tomcat server you're running. The access log files are stored relative to the path in the "Server path" field, which itself is relative to the workspace path.

Removing object properties with Lodash

Lodash unset is suitable for removing a few unwanted keys.

_x000D_
_x000D_
const myObj = {
    keyOne: "hello",
    keyTwo: "world"
}

unset(myObj, "keyTwo");

console.log(myObj); /// myObj = { keyOne: "hello" }
_x000D_
_x000D_
_x000D_

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

Difference between StringBuilder and StringBuffer

StringBuffer is mutable. It can change in terms of length and content. StringBuffers are thread-safe, meaning that they have synchronized methods to control access so that only one thread can access a StringBuffer object's synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.

StringBuilder The StringBuilder class is very similar to StringBuffer, except that its access is not synchronized so that it is not thread-safe. By not being synchronized, the performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance. This is also true of other situations such as a StringBuilder local variable (ie, a variable within a method) where only one thread will be accessing a StringBuilder object.

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

jQuery datepicker set selected date, on the fly

Noted that for DatePicker by Keith Wood (http://keith-wood.name/datepickRef.html) the following works - note that the setting of the default date is last:

    $('#datepicker').datepick({
        minDate: 0,
        maxDate: '+145D',
        multiSelect: 7,
        renderer: $.datepick.themeRollerRenderer,
        ***defaultDate: new Date('1 January 2008')***
    });

no target device found android studio 2.1.1

This happened to me on android studio version 4 after doing an update to the IDE. The "invalidate caches and restart" option fixed it.

What does '?' do in C++?

The question mark is the conditional operator. The code means that if f==r then 1 is returned, otherwise, return 0. The code could be rewritten as

int qempty()
{
  if(f==r)
    return 1;
  else
    return 0;
}

which is probably not the cleanest way to do it, but hopefully helps your understanding.

Are there best practices for (Java) package organization?

I organize packages by feature, not by patterns or implementation roles. I think packages like:

  • beans
  • factories
  • collections

are wrong.

I prefer, for example:

  • orders
  • store
  • reports

so I can hide implementation details through package visibility. Factory of orders should be in the orders package so details about how to create an order are hidden.

How do I specify "close existing connections" in sql script

I tryed what hgmnz saids on SQL Server 2012.

Management created to me:

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'MyDataBase'
GO
USE [master]
GO
/****** Object:  Database [MyDataBase]    Script Date: 09/09/2014 15:58:46 ******/
DROP DATABASE [MyDataBase]
GO

What is the best (idiomatic) way to check the type of a Python variable?

type(dict()) says "make a new dict, and then find out what its type is". It's quicker to say just dict. But if you want to just check type, a more idiomatic way is isinstance(x, dict).

Note, that isinstance also includes subclasses (thanks Dustin):

class D(dict):
    pass

d = D()
print("type(d) is dict", type(d) is dict)  # -> False
print("isinstance (d, dict)", isinstance(d, dict))  # -> True

How to analyze a JMeter summary report?

Short explanation looks like:

  1. Sample - number of requests sent
  2. Avg - an Arithmetic mean for all responses (sum of all times / count)
  3. Minimal response time (ms)
  4. Maximum response time (ms)
  5. Deviation - see Standard Deviation article
  6. Error rate - percentage of failed tests
  7. Throughput - how many requests per second does your server handle. Larger is better.
  8. KB/Sec - self expalanatory
  9. Avg. Bytes - average response size

If you having troubles with interpreting results you could try BM.Sense results analysis service

How do I exclude Weekend days in a SQL Server query?

The answer depends on your server's week-start set up, so it's either

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (7,1)

if Sunday is the first day of the week for your server

or

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (6,7)

if Monday is the first day of the week for your server

Comment if you've got any questions :-)

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;

It works and it's cross browser compatible.

Check out the code below, you probably get a better explanation:

_x000D_
_x000D_
jQuery('.close a, .bg', '#message').on('click', function() {_x000D_
  jQuery('#message').fadeOut();_x000D_
  return false;_x000D_
});
_x000D_
html, body {_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
#message {_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#message .container {_x000D_
  height: 60%;_x000D_
  left: 50%;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  z-index: 10;_x000D_
  width: 60%;_x000D_
}_x000D_
_x000D_
#message .container .text {_x000D_
  background: #fff;_x000D_
  height: 100%;_x000D_
  left: -50%;_x000D_
  position: absolute;_x000D_
  top: -50%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#message .bg {_x000D_
  background: rgba(0, 0, 0, 0.5);_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
  z-index: 9;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
  <div class="container">_x000D_
    <div class="text">_x000D_
      <h2>Warning</h2>_x000D_
      <p>The message</p>_x000D_
      <p class="close"><a href="#">Close Window</a></p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="bg"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Equivalent of .bat in mac os

I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:

  • Make a bash (shell) script version of your .bat file (like other
    answers, with \ changed to / in file paths). For example:

    # File "example.command":
    #!/bin/bash
    java -cp  ".;./supportlibraries/Framework_Core.jar; ...etc.
    
  • Then rename it to have the Mac OS file extension .command.
    That should make the script run using the Terminal app.

  • If the app user is going to use a bash script version of the file on Linux
    or run it from the command line, they need to add executable rights
    (change mode bits) using this command, in the folder that has the file:

    chmod +rx [filename].sh
    #or:# chmod +rx [filename].command
    

The forum page question:

Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.

Info from some answers after the question:

Write a shell script, and give it the extension ".command". For example:

#!/bin/bash 
printf "Hello World\n" 

- Mar 23, 2010, Tony T1.

The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.

However, OS X adds the feature that if you give the file the suffix .command, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).

Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]

#!/bin/sh
echo Hello World

- Mar 23, 2010, J D McIninch.

Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:

On mac, there is a specific extension for executing shell
scripts by double clicking them: this is .command.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

protocol://hostname:port/...

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

Examples

Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

  • In your main page:

    const frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
    

    The second argument to postMessage() can be '*' to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

  • In your <iframe> (contained in the main page):

    window.addEventListener('message', event => {
        // IMPORTANT: check the origin of the data! 
        if (event.origin.startsWith('http://your-first-site.com')) { 
            // The data was sent from your site.
            // Data sent with postMessage is stored in event.data:
            console.log(event.data); 
        } else {
            // The data was NOT sent from your site! 
            // Be careful! Do not use it. This else branch is
            // here just for clarity, you usually shouldn't need it.
            return; 
        } 
    }); 
    

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.

Disabling same-origin policy in your browser

There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).

Platform.runLater and Task in JavaFX

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

Code using Platform.runLater(...):

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();

it suffers from none of the flaws exhibited in the previous code

Reference : Worker Threading in JavaFX 2.0

Read SQL Table into C# DataTable

var table = new DataTable();    
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{      
    da.Fill(table);
}

Getting the last argument passed to a shell script

Use indexing combined with length of:

echo ${@:${#@}} 

Note that this is bash-only.

How do I get JSON data from RESTful service using Python?

If you desire to use Python 3, you can use the following:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

No matching bean of type ... found for dependency

Add this to you applicationContext:

 <bean id="userService" class="com.example.my.services.user.UserServiceImpl ">

Importing variables from another file?

Import file1 inside file2:

To import all variables from file1 without flooding file2's namespace, use:

import file1

#now use file1.x1, file2.x2, ... to access those variables

To import all variables from file1 to file2's namespace( not recommended):

from file1 import *
#now use x1, x2..

From the docs:

While it is valid to use from module import * at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.

CASE .. WHEN expression in Oracle SQL

You could use an IN clause

Something like

SELECT
  status,
  CASE
    WHEN STATUS IN('a1','a2','a3')
    THEN 'Active'
    WHEN STATUS = 'i'
    THEN 'Inactive'
    WHEN STATUS = 't'
    THEN 'Terminated'
  END AS STATUSTEXT
FROM
  STATUS

Have a look at this demo

SQL Fiddle DEMO

Simple InputBox function

It would be something like this

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript" 
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
$_userInput = $inputObject.eval("getInput") 

return $_userInput
}

Then you can call the function similar to this.

$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null ) 
{
 echo "Input was [$userInput]"
}
else
{
 echo "User cancelled the form!"
}

This is the most simple way to do this that I can think of.

How can I stop python.exe from closing immediately after I get an output?

Python files are executables, which means that you can run them directly from command prompt(assuming you have windows). You should be able to just enter in the directory, and then run the program. Also, (assuming you have python 3), you can write:

input("Press enter to close program")

and you can just press enter when you've read your results.

How to handle ETIMEDOUT error?

In case if you are using node js, then this could be the possible solution

const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;

https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

Change event on select with knockout binding, how can I know if it is a real change?

Try this one:

self.GetHierarchyNodeList = function (data, index, event)
{
    debugger;
    if (event.type != "change") {
        return;
    }        
} 

event.type == "change"
event.type == "load" 

What is the purpose of "&&" in a shell command?

command_1 && command_2: execute command_2 only when command_1 is executed successfully.

command_1 || command_2: execute command_2 only when command_1 is not successful executed.

Feels similar as how an 'if' condition is executed in a mainstream programming language, like, in if (condition_1 && condition_2){...} condition_2 will be omitted if condition_1 is false and in if (condition_1 || condition_2){...} condition_2 will be omitted if condition_1 is true. See, it's the same trick you use for coding :)

How to add an element at the end of an array?

You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :

public static void main(String[] args) {
    int[] array = new int[] {1, 2, 3};
    System.out.println(Arrays.toString(array));
    array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
    array[array.length - 1] = 4;
    System.out.println(Arrays.toString(array));
}

I would still recommend to drop working with an array and use a List.

C++ String Declaring

using the standard <string> header

std::string Something = "Some Text";

http://www.dreamincode.net/forums/topic/42209-c-strings/

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.

SQL Server SELECT INTO @variable?

I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.

So far what I do is concatenate the entire SQL code with the variables to use. Like this:

declare @table_name as varchar(30)
select @table_name = CONVERT(varchar(30), getdate(), 112)
set @table_name = 'DAILY_SNAPSHOT_' + @table_name

EXEC('
        SELECT var1, var2, var3
        INTO '+@table_name+'
        FROM my_view
        WHERE string = ''Strings must use double apostrophe''
    ');

I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!

How to execute .sql file using powershell?

Try to see if SQL snap-ins are present:

get-pssnapin -Registered

Name        : SqlServerCmdletSnapin100
PSVersion   : 2.0
Description : This is a PowerShell snap-in that includes various SQL Server cmdlets.

Name        : SqlServerProviderSnapin100
PSVersion   : 2.0
Description : SQL Server Provider

If so

Add-PSSnapin SqlServerCmdletSnapin100 # here lives Invoke-SqlCmd
Add-PSSnapin SqlServerProviderSnapin100

then you can do something like this:

invoke-sqlcmd -inputfile "c:\mysqlfile.sql" -serverinstance "servername\serverinstance" -database "mydatabase" # the parameter -database can be omitted based on what your sql script does.

How do I look inside a Python object?

import pprint

pprint.pprint(obj.__dict__)

or

pprint.pprint(vars(obj))

Running PHP script from the command line

UPDATE:

After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?

Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that, start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(so you can paste/write code in the console)

php -a

To make it parse file and output to console:

php -f file.php

Parse file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running linux then do man php at console.

if you need/want to run php through fpm, use cli fcgi

SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

Convert JSON String To C# Object

Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.

  public class Student
{
   public string FirstName {get;set:}
   public string LastName {get;set:}
   public int[] Grades {get;set:}
}

public static Student ConvertToStudent(string std)
{
  var serializer = new JavaScriptSerializer();

  Return serializer.Deserialize<Student>(std);
 }

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

Check whether user has a Chrome extension installed

If you're trying to detect any extension from any website, This post helped: https://ide.hey.network/post/5c3b6c7aa7af38479accc0c7

Basically, the solution would be to simply try to get a specific file (manifest.json or an image) from the extension by specifying its path. Here's what I used. Definitely working:

const imgExists = function(_f, _cb) {
    const __i = new Image();
    __i.onload = function() {
        if (typeof _cb === 'function') {
            _cb(true);
        }
    }
    __i.onerror = function() {
        if (typeof _cb === 'function') {
            _cb(false);
        }
    }
    __i.src = _f;
    __i = null;
});

try {
    imgExists("chrome-extension://${CHROME_XT_ID}/xt_content/assets/logo.png", function(_test) {
        console.log(_test ? 'chrome extension installed !' : 'chrome extension not installed..');
        ifrm.xt_chrome = _test;
        // use that information
    });
} catch (e) {
    console.log('ERROR', e)
}

SQL Update with row_number()

With UpdateData  As
(
SELECT RS_NOM,
ROW_NUMBER() OVER (ORDER BY [RS_NOM] DESC) AS RN
FROM DESTINATAIRE_TEMP
)
UPDATE DESTINATAIRE_TEMP SET CODE_DEST = RN
FROM DESTINATAIRE_TEMP
INNER JOIN UpdateData ON DESTINATAIRE_TEMP.RS_NOM = UpdateData.RS_NOM

Having a UITextField in a UITableViewCell

Here's a drop-in subclass for UITableViewCell which replaces the detailTextLabel with an editable UITextField (or, in case of UITableViewCellStyleDefault, replaces the textLabel). This has the benefit that it allows you to re-use all the familiar UITableViewCellStyles, accessoryViews, etc, just now the detail is editable!

@interface GSBEditableTableViewCell : UITableViewCell <UITextFieldDelegate>
@property UITextField *textField;
@end

@interface GSBEditableTableViewCell ()
@property UILabel *replace;
@end

@implementation GSBEditableTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _replace = (style == UITableViewCellStyleDefault)? self.textLabel : self.detailTextLabel;
        _replace.hidden = YES;

        // Impersonate UILabel with an identical UITextField
        _textField = UITextField.new;
        [self.contentView addSubview:_textField];
        _textField.translatesAutoresizingMaskIntoConstraints = NO;
        [_textField.leftAnchor constraintEqualToAnchor:_replace.leftAnchor].active = YES;
        [_textField.rightAnchor constraintEqualToAnchor:_replace.rightAnchor].active = YES;
        [_textField.topAnchor constraintEqualToAnchor:_replace.topAnchor].active = YES;
        [_textField.bottomAnchor constraintEqualToAnchor:_replace.bottomAnchor].active = YES;
        _textField.font = _replace.font;
        _textField.textColor = _replace.textColor;
        _textField.textAlignment = _replace.textAlignment;

        // Dont want to intercept UITextFieldDelegate, so use UITextFieldTextDidChangeNotification instead
        [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(textDidChange:)
                                               name:UITextFieldTextDidChangeNotification
                                             object:_textField];

        // Also need KVO because UITextFieldTextDidChangeNotification not fired when change programmatically
        [_textField addObserver:self forKeyPath:@"text" options:0 context:nil];
    }
    return self;
}

- (void)textDidChange:(NSNotification*)notification
{
    // Update (hidden) UILabel to ensure correct layout
    if (_textField.text.length) {
        _replace.text = _textField.text;
    } else if (_textField.placeholder.length) {
        _replace.text = _textField.placeholder;
    } else {
        _replace.text = @" "; // otherwise UILabel removed from cell (!?)
    }
    [self setNeedsLayout];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ((object == _textField) && [keyPath isEqualToString:@"text"]) [self textDidChange:nil];
}

- (void)dealloc
{
    [_textField removeObserver:self forKeyPath:@"text"];
}

@end

Simple to use - just create your cell as before, but now use cell.textField instead of cell.detailTextLabel (or cell.textLabel in case of UITableViewCellStyleDefault). eg

GSBEditableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (!cell) cell = [GSBEditableTableViewCell.alloc initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"Cell"];

cell.textLabel.text = @"Name";
cell.textField.text = _editablename;
cell.textField.delegate = self; // to pickup edits
...

Inspired by, and improved upon, FD's answer

How to bind RadioButtons to an enum?

You could use a more generic converter

public class EnumBooleanConverter : IValueConverter
{
  #region IValueConverter Members
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
      return DependencyProperty.UnsetValue;

    if (Enum.IsDefined(value.GetType(), value) == false)
      return DependencyProperty.UnsetValue;

    object parameterValue = Enum.Parse(value.GetType(), parameterString);

    return parameterValue.Equals(value);
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
        return DependencyProperty.UnsetValue;

    return Enum.Parse(targetType, parameterString);
  }
  #endregion
}

And in the XAML-Part you use:

<Grid>
    <Grid.Resources>
      <l:EnumBooleanConverter x:Key="enumBooleanConverter" />
    </Grid.Resources>
    <StackPanel >
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
    </StackPanel>
</Grid>

Detect click outside element

I'm not sure if someone will ever see this answer but here it is. The idea here is to simply detect if any click was done outside the element itself.

I first start by giving an id to the main div of my "dropdown".

<template>
  <div class="relative" id="dropdown">
    <div @click="openDropdown = !openDropdown" class="cursor-pointer">
      <slot name="trigger" />
    </div>

    <div
      class="absolute mt-2 w-48 origin-top-right right-0 text-red  bg-tertiary text-sm text-black"
      v-show="openDropdown"
      @click="openDropdown = false"
    >
      <slot name="content" />
    </div>
  </div>
</template>

And then I just loop thru the path of the mouse event and see if the div with my id "dropdown" is there. If it is, then we good, if it is no, then we close the dropdown.

<script>
export default {
  data() {
    return {
      openDropdown: false,
    };
  },
  created() {
    document.addEventListener("click", (e) => {
      let me = false;
      for (let index = 0; index < e.path.length; index++) {
        const element = e.path[index];

        if (element.id == "dropdown") {
          me = true;
          return;
        }
      }

      if (!me) this.openDropdown = false;
    });
  }
};
</script>

I'm pretty sure this can bring performance issues if you have many nested elements, but I found this as the most lazy-friendly way of doing it.

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

Center-align a HTML table

<table align="center"></table>

This works for me.

Deny access to one specific folder in .htaccess

We will set the directory to be very secure, denying access for all file types. Below is the code you want to insert into the .htaccess file.

Order Allow,Deny 
Deny from all 

Since we have now set the security, we now want to allow access to our desired file types. To do that, add the code below to the .htaccess file under the security code you just inserted.

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

your final .htaccess file will look like

Order Allow,Deny 
Deny from all 

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

Source from Allow access to specific file types in a protected directory

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

Test a weekly cron job

I'd use a lock file and then set the cron job to run every minute. (use crontab -e and * * * * * /path/to/job) That way you can just keep editing the files and each minute they'll be tested out. Additionally, you can stop the cronjob by just touching the lock file.

    #!/bin/sh
    if [ -e /tmp/cronlock ]
    then
        echo "cronjob locked"
        exit 1
    fi

    touch /tmp/cronlock
    <...do your regular cron here ....>
    rm -f /tmp/cronlock

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

Connect Java to a MySQL database

You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.

Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA

offsetTop vs. jQuery.offset().top

This is what jQuery API Doc says about .offset():

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

This is what MDN Web API says about .offsetTop:

offsetTop returns the distance of the current element relative to the top of the offsetParent node

This is what jQuery v.1.11 .offset() basically do when getting the coords:

var box = { top: 0, left: 0 };

// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
  box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
  top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
  left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
  • pageYOffset intuitively says how much was the page scrolled
  • docElem.scrollTop is the fallback for IE<9 (which are BTW unsupported in jQuery 2)
  • docElem.clientTop is the width of the top border of an element (the document in this case)
  • elem.getBoundingClientRect() gets the coords relative to the document viewport (see comments). It may return fraction values, so this is the source of your bug. It also may cause a bug in IE<8 when the page is zoomed. To avoid fraction values, try to calculate the position iteratively

Conclusion

  • If you want coords relative to the parent node, use element.offsetTop. Add element.scrollTop if you want to take the parent scrolling into account. (or use jQuery .position() if you are fan of that library)
  • If you want coords relative to the viewport use element.getBoundingClientRect().top. Add window.pageYOffset if you want to take the document scrolling into account. You don't need to subtract document's clientTop if the document has no border (usually it doesn't), so you have position relative to the document
  • Subtract element.clientTop if you don't consider the element border as the part of the element

Installing specific laravel version with composer create-project

To install specific version of laravel try this & simply command on terminal

composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}