Programs & Examples On #Oracle

Oracle Database is a Multi-Model Database Management System created by Oracle Corporation. Do NOT use this tag for other products owned by Oracle, such as Java and MySQL.

How to catch a unique constraint error in a PL/SQL block?


PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE AND table2.item=table1.item);

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

How to find Oracle Service Name

Connect to the server as "system" using SID. Execute this query:

select value from v$parameter where name like '%service_name%';

It worked for me.

sqldeveloper error message: Network adapter could not establish the connection error

Check The port 1521 in your server. May be its blocked by firewall. Or disable firewall and try.

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

You could use RAISE_APPLICATION_ERROR like this:

    ex_custom       EXCEPTION;
    RAISE ex_custom;
    WHEN ex_custom THEN
        RAISE_APPLICATION_ERROR(-20001,'My exception was raised');

That will raise an exception that looks like:

ORA-20001: My exception was raised

The error number can be anything between -20001 and -20999.

What is the Oracle equivalent of SQL Server's IsNull() function?

coalesce is supported in both Oracle and SQL Server and serves essentially the same function as nvl and isnull. (There are some important differences, coalesce can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull matches the type of the first argument, that is not true for coalesce, at least on SQL Server.)

How to get first and last day of week in Oracle?

SELECT NEXT_DAY (TO_DATE ('01/01/'||SUBSTR('201118',1,4),'MM/DD/YYYY')+(TO_NUMBER(SUBSTR('201118',5,2))*7)-3,'SUNDAY')-7 first_day_wk,
    NEXT_DAY (TO_DATE ('01/01/'||SUBSTR('201118',1,4),'MM/DD/YYYY')+(TO_NUMBER(SUBSTR('201118',5,2))*7)-3,'SATURDAY') last_day_wk FROM dual

Oracle listener not running and won't start

Same happened to me after I changed computer name. To fix that, just locate listener.ora file and replace old computer name with the new one

ORA-28001: The password has expired

I have fixed the problem, just need to check:

open_mode from v$database

and then check:

check account_status to get mode information

and then use:

alter user myuser identified by mynewpassword account unlock;

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);


alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);


update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);


alter table EVAPP_FEES drop column AMOUNT_TEMP;

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Try this:

select * from T_PARTNER 
translate(C_PARTNER_ID, '.1234567890', '.') is null;

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

How to create an Oracle sequence starting with max value from a table?

If you can use PL/SQL, try (EDIT: Incorporates Neil's xlnt suggestion to start at next higher value):

SELECT 'CREATE SEQUENCE transaction_sequence MINVALUE 0 START WITH '||MAX(trans_seq_no)+1||' INCREMENT BY 1 CACHE 20'
  INTO v_sql
  FROM transaction_log;


Another point to consider: By setting the CACHE parameter to 20, you run the risk of losing up to 19 values in your sequence if the database goes down. CACHEd values are lost on database restarts. Unless you're hitting the sequence very often, or, you don't care that much about gaps, I'd set it to 1.

One final nit: the values you specified for CACHE and INCREMENT BY are the defaults. You can leave them off and get the same result.

How to replace specific values in a oracle database column?

I'm using Version with Build 15.21

For me I needed this:

UPDATE table_name SET column_name = REPLACE(column_name,"search str","replace str");

Putting t.column_name in the first argument of replace did not work.

Updating a date in Oracle SQL table

If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.

In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..

Oracle SQL update based on subquery between two tables

Try it ..

SET (name, count) = (
SELECT name, count
        FROM STAGING b
        WHERE a.ID = b.ID)
    WHERE a.ID=b.ID

Inner join vs Where

In PostgreSQL, there's definitely no difference - they both equate to the same query plan. I'm 99% sure that's also the case for Oracle.

What is the difference between Views and Materialized Views in Oracle?

Adding to Mike McAllister's pretty-thorough answer...

Materialized views can only be set to refresh automatically through the database detecting changes when the view query is considered simple by the compiler. If it's considered too complex, it won't be able to set up what are essentially internal triggers to track changes in the source tables to only update the changed rows in the mview table.

When you create a materialized view, you'll find that Oracle creates both the mview and as a table with the same name, which can make things confusing.

How to find top three highest salary in emp table in oracle?

SELECT  Name, Salary
    SELECT  Name, Salary
    FROM         emp 
    ORDER BY Salary desc
WHERE rownum <= 3
ORDER BY Salary ;

How to get the employees with their managers

Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr) thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)

have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)

SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;

Oracle Not Equals Operator

They are the same, but i've heard people say that Developers use != while BA's use <>

Oracle client ORA-12541: TNS:no listener

You need to set oracle to listen on all ip addresses (by default, it listens only to localhost connections.)

Step 1 - Edit listener.ora

This file is located in:

  • Windows: %ORACLE_HOME%\network\admin\listener.ora.
  • Linux: $ORACLE_HOME/network/admin/listener.ora

Replace localhost with

# ...

      (ADDRESS = (PROTOCOL = TCP)(HOST = = 1521))

# ...

Step 2 - Restart Oracle services

  • Windows: WinKey + r

  • Linux (CentOs):

    sudo systemctl restart oracle-xe

enter image description here

PL/SQL print out ref cursor returned by a stored procedure

If you want to print all the columns in your select clause you can go with the autoprint command.

CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
  OPEN v_refcur FOR 'select * from dummy_table';

SET autoprint on;

--calling the procedure
VAR vcur refcursor;

Hope this gives you an alternate solution

SQL Error: ORA-00942 table or view does not exist

Here is an answer:

An Oracle synonym basically allows you to create a pointer to an object that exists somewhere else. You need Oracle synonyms because when you are logged into Oracle, it looks for all objects you are querying in your schema (account). If they are not there, it will give you an error telling you that they do not exist.

Oracle - Insert New Row with Auto Incremental ID

This is a simple way to do it without any triggers or sequences:

insert into WORKQUEUE (ID, facilitycode, workaction, description)
  values ((select max(ID)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES')

It worked for me but would not work with an empty table, I guess.

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

SQL> sqlplus "/ as sysdba"

SQL> startup

  Oracle instance started
  Database mounted.
  Database opened.

SQL> Quit

I also got same problem.I tried above mentioned steps and then it worked for me.You can try.

Oracle - How to create a readonly user

It is not strictly possible in default db due to the many public executes that each user gains automatically through public.

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SPOOL test.log
EXEC dbms_output.put_line('&1 &2');

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!


In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!

so that your login/password won't be visible with another session's ps

Why do I have ORA-00904 even when the column is present?

I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.

For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'. This query may give you a ORA-00904 error:

select * from table_name where x='test';

Prefixing the table_name with the table owner eliminated the error and gives results:

select * from 

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:


Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

ORA-00060: deadlock detected while waiting for resource

I was testing a function that had multiple UPDATE statements within IF-ELSE blocks.

I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE statements each time before running the function again.

I noticed that the issue would happen just after those UPDATE statements;

I added a COMMIT; after the UPDATE statement I used to reset the tables and that solved the problem.

So, caution, the problem was not the function itself...

Calculate difference between 2 date / times in Oracle SQL

select days||' '|| time from (
SELECT to_number( to_char(to_date('1','J') +
    (CLOSED_DATE - CREATED_DATE), 'J') - 1)  days,
   to_char(to_date('00:00:00','HH24:MI:SS') +
      (CLOSED_DATE - CREATED_DATE), 'HH24:MI:SS') time
 FROM  request  where REQUEST_ID=158761088 );

Declaring & Setting Variables in a Select Statement

Coming from SQL Server as well, and this really bugged me. For those using Toad Data Point or Toad for Oracle, it's extremely simple. Just putting a colon in front of your variable name will prompt Toad to open a dialog where you enter the value on execute.

SELECT * FROM some_table WHERE some_column = :var_name;

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

You might also consider removing the need for duplicated parameter names in your Sql by changing your Sql to

table.Variable2 LIKE '%' || :VarB || '%'

and then getting your client to provide '%' for any value of VarB instead of null. In some ways I think this is more natural.

You could also change the Sql to

table.Variable2 LIKE '%' || IfNull(:VarB, '%') || '%'

Oracle Add 1 hour in SQL

The calculation is simple

if you want to add 1 hour in the date .

every day have 24 hour , you can add .

select sysdate + 1/24 from dual; 

if you want 1 day to add

select sysdate + 24/24 from dual; 


select sysdate + 1 from dual; 

same as for 2, 3 , 4 day

For static date you have the answer below.

LEFT function in Oracle

There is no documented LEFT() function in Oracle. Find the full set here.

Probably what you have is a user-defined function. You can check that easily enough by querying the data dictionary:

select * from all_objects
where object_name = 'LEFT'

But there is the question of why the stored procedure works and the query doesn't. One possible solution is that the stored procedure is owned by another schema, which also owns the LEFT() function. They have granted rights on the procedure but not its dependencies. This works because stored procedures run with DEFINER privileges by default, so you run the stored procedure as if you were its owner.

If this is so then the data dictionary query I listed above won't help you: it will only return rows for objects you have rights on. In which case you will need to run the query as the stored procedure's owner or connect as a user with the rights to query DBA_OBJECTS instead.

How can I confirm a database is Oracle & what version it is using SQL?

Run this SQL:

select * from v$version;

And you'll get a result like:

Oracle Database 10g Release - 64bit Production
PL/SQL Release - Production
CORE      Production
TNS for Solaris: Version - Production
NLSRTL Version - Production

How do I get column datatype in Oracle with PL-SQL with low privileges?

select t.data_type 
  from user_tab_columns t 
 where t.TABLE_NAME = 'xxx' 
   and t.COLUMN_NAME='aaa'

Removing duplicate rows from table in Oracle

5. solution

delete from emp where rowid in 
      select  rid from
         select rowid rid,rank() over (partition by emp_id order by rowid)rn from emp     
     where rn > 1

How can I find which tables reference a given table in Oracle SQL Developer?

How about something like this:

SELECT c.constraint_name, c.constraint_type, c2.constraint_name, c2.constraint_type, c2.table_name
  FROM dba_constraints c JOIN dba_constraints c2 ON (c.r_constraint_name = c2.constraint_name)
 WHERE c.table_name = <TABLE_OF_INTEREST>
   AND c.constraint_TYPE = 'R';

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

-- (BLOB)

FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

How can I list ALL grants a user received?

The most comprehensive and reliable method I know is still by using DBMS_METADATA:

select dbms_metadata.get_granted_ddl( 'SYSTEM_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'OBJECT_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'ROLE_GRANT', :username ) from dual;

(username must be written all uppercase)

Interesting answers though.

Splitting comma separated string in a PL/SQL stored proc

   p_errcode        OUT   NUMBER,
   p_errmesg        OUT   VARCHAR2,
   p_rowsaffected   OUT   INTEGER
   v_param0   VARCHAR2 (30) := '0.25,2.25,33.689, abc, 99';
   v_param1   VARCHAR2 (30) := '2.65,66.32, abc-def, 21.5';
               FROM TABLE (SPLIT (v_param0, ',')))
      INSERT INTO tempo

               FROM TABLE (SPLIT (v_param1, ',')))
      INSERT INTO tempo

What is the difference between primary, unique and foreign key constraints, and indexes?

1)A primary key is a set of one or more attributes that uniquely identifies tuple within relation.

2)A foreign key is a set of attributes from a relation scheme which can be uniquely identify tuples fron another relation scheme.

Oracle date function for the previous month

Getting last nth months data retrieve


Windows cannot find 'http:/.'. Make sure you typed the name correctly, and then try again

TLDR; Uninstall and re-install using admin account.

I encountered this error after installing Oracle Express 11g 64 bit using a standard account. After looking for a fix on various sites I realized that the issue was most likely caused by an incorrect setting. Different people suggested editing various files which I was not interested in doing. I found one person who claimed that the issue was a registry setting. Since I used a standard account to install I thought that maybe the registry setting could not be altered using a standard account. So I uninstalled and re-installed using an admin account and it just worked.

how to insert date and time in oracle?

create table Customer(
       CustId int primary key,
       CustName varchar(20),
       DOB date);

insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Since SELECT INTO assumes that a single row will be returned, you can use a statement of the form:

SELECT MAX(column)
  INTO var
  FROM table
 WHERE conditions;

THEN ...

The SELECT will give you the value if one is available, and a value of NULL instead of a NO_DATA_FOUND exception. The overhead introduced by MAX() will be minimal-to-zero since the result set contains a single row. It also has the advantage of being compact relative to a cursor-based solution, and not being vulnerable to concurrency issues like the two-step solution in the original post.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

The order of precedence for resolving TNS names in ODP.NET, Managed Driver is this (see here):

  1. data source alias in the 'dataSources' section under section in the .NET config file.
  2. data source alias in the tnsnames.ora file at the location specified by 'TNS_ADMIN' in the .NET config file.
  3. data source alias in the tnsnames.ora file present in the same directory as the .exe.
  4. data source alias in the tnsnames.ora file present at %TNS_ADMIN% (where %TNS_ADMIN% is an environment variable setting).
  5. data source alias in the tnsnames.ora file present at %ORACLE_HOME%\network\admin (where %ORACLE_HOME% is an environment variable setting).

I believe the reason your sample works with Oracle.DataAccess but not with Oracle.ManagedDataAccess is that Windows registry based configuration is not supported for the latter (see documentation) - the ODP.NET installation sets an ORACLE_HOME registry key (HLKM\SOFTWARE\Oracle\Key_NAME\ORACLE_HOME) which is recognized only by the unmanaged part.

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:


Checking oracle sid and database name

The V$ views are mainly dynamic views of system metrics. They are used for performance tuning, session monitoring, etc. So access is limited to DBA users by default, which is why you're getting ORA-00942.

The easiest way of finding the database name is:

select * from global_name;

This view is granted to PUBLIC, so anybody can query it.

Get list of all tables in Oracle?

Try the below data dictionary views.


'NOT LIKE' in an SQL query

You have missed out the field name id in the second NOT LIKE. Try:

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

The AND in the where clause joins 2 full condition expressions such as id NOT LIKE '1%' and can't be used to list multiple values that the id is 'not like'.

Dropping connected users in Oracle database

Here's how I "automate" Dropping connected users in Oracle database:

# A shell script to Drop a Database Schema, forcing off any Connected Sessions (for example, before an Import) 
# Warning! With great power comes great responsibility.
# It is often advisable to take an Export before Dropping a Schema

if [ "$1" = "" ] 
    echo "Which Schema?"
    read schema
    echo "Are you sure? (y/n)"
    read reply
    [ ! $reply = y ] && return 1

sqlplus / as sysdba <<EOF
set echo on
alter user $schema account lock;
-- Exterminate all sessions!
  for x in ( select sid, serial# from v\$session where username=upper('$schema') )
   execute immediate ( 'alter system kill session '''|| x.Sid || ',' || x.Serial# || ''' immediate' );  
  end loop;  
  dbms_lock.sleep( seconds => 2 ); -- Prevent ORA-01940: cannot drop a user that is currently connected
drop user $schema cascade;

Get the difference between two dates both In Months and days in sql

Find out Year - Month- Day between two Days in Orale Sql

trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12) years ,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))) 
(trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12))*12
             round(To_date('20120101', 'YYYYMMDD')-add_months(to_date('19910228','YYYYMMDD'),
                           trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))))) days
        from dual;

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

Oracle: How to filter by date and time in a where clause

Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.


You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.

How to increase buffer size in Oracle SQL Developer to view all records?

Tools-> Preferences -> Database ->Worksheet

Enter desired size in "Max rows to print in a script"

Save changes.

How to select only 1 row from oracle sql?

If any row would do, try:

select max(user)  
from table;

No where clause.

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Oracle error : ORA-00905: Missing keyword

Unless there is a single row in the ASSIGNMENT table and ASSIGNMENT_20081120 is a local PL/SQL variable of type ASSIGNMENT%ROWTYPE, this is not what you want.

Assuming you are trying to create a new table and copy the existing data to that new table

CREATE TABLE assignment_20081120
  FROM assignment

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

How to check for null/empty/whitespace values with a single test?

SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''

ISNULL(column_name, '') will return '' if column_name is NULL, otherwise it will return column_name.


In Oracle, you can use NVL to achieve the same results.

SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''

Boolean Field in Oracle

A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number type):

ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))

This creates a new column in my_table_name called my_new_boolean_column with default values of 0. The column will not accept NULL values and restricts the accepted values to either 0 or 1.

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread:

Why is the GETDATE() an invalid identifier

I think you want SYSDATE, not GETDATE(). Try it:


Sleep function in ORACLE

From Oracle 18c you could use DBMS_SESSION.SLEEP procedure:

This procedure suspends the session for a specified period of time.


DBMS_SESSION.sleep is available to all sessions with no additional grants needed. Please note that DBMS_LOCK.sleep is deprecated.

If you need simple query sleep you could use WITH FUNCTION:

    RETURN i;
SELECT my_sleep(3) FROM dual;

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

There are a couple of things you could look at. Based on your question, it looks like the function owner is different from the table owner.

1) Grants via a role : In order to create stored procedures and functions on another user's objects, you need direct access to the objects (instead of access through a role).


By default, stored procedures and SQL methods execute with the privileges of their owner, not their current user.

If you created a table in Schema A and the function in Schema B, you should take a look at Oracle's Invoker/Definer Rights concepts to understand what might be causing the issue.

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

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

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

when in doubt, use VARCHAR2(1 CHAR)

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

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

in Oracle, don't use VARCHAR

Oracle: how to add minutes to a timestamp?

Oracle now has new built in functions to do this:

select systimestamp START_TIME, systimestamp + NUMTODSINTERVAL(30, 'minute') end_time from dual

UNION with WHERE clause

i think it will depend on many things - run EXPLAIN PLAN on each one to see what your optimizer selects. Otherwise - as @rayman suggests - run them both and time them.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

To insert a VARCHAR2 into a BLOB column you can rely on the function utl_raw.cast_to_raw as next:

insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));

It will cast your input VARCHAR2 into RAW datatype without modifying its content, then it will insert the result into your BLOB column.

More details about the function utl_raw.cast_to_raw

Generating sql insert into for Oracle

I have been searching for a solution for this and found it today. Here is how you can do it.

  1. Open Oracle SQL Developer Query Builder

  2. Run the query

  3. Right click on result set and export

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

Even though you are using ASMM, you can set a minimum size for the large pool (MMAN will not shrink it below that value). You can also try pinning some objects and increasing SGA_TARGET.

How to kill all active and inactive oracle sessions for user

The KILL SESSION command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.

Check the status to confirm:

SELECT sid, serial#, status, username FROM v$session;

You could also use IMMEDIATE clause:


The IMMEDIATE clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.

Update If you want to kill all the sessions, you could just prepare a small script.

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;

Spool the above to a .sql file and execute it, or, copy paste the output and run it.

Paging with Oracle

Something like this should work: From Frans Bouma's Blog

    SELECT a.*, rownum r__
        ORDER BY OrderDate DESC, ShippingDate DESC
    ) a
    WHERE rownum < ((pageNumber * pageSize) + 1 )
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)

How to see the actual Oracle SQL statement that is being executed

I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

  myname varchar2(20) := 'tom';
  for result_cursor in (select * from mytable where first_name = myname) loop
  end loop;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

  myname varchar2(20);
  select first_name into myname 
    from mytable 
    where person_id = 123;

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

  • It did not work so i switched to oracle sql developer and it worked with no problems (making connection under 1 minute).
  • This link gave me an idea connect to MS Access so i created a user in oracle sql developer and the tried to connect to it in Toad and it worked.

Or second solution

you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad

Java: How to insert CLOB into oracle database

This code worked for me. I use ojdbc6-

java.sql.Connection con;
javax.xml.bind.Marshaller marshaller;

Clob xmlClob = con.createClob();
try {
  try (Writer xmlClobWriter = xmlClob.setCharacterStream(1)) {
    m.marshal(jaxbObject, xmlClobWriter);
  } // xmlClobWriter.close();
  try (PreparedStatement stmt = con.prepareStatement("INSERT INTO table (xml) values(?)")) {
    stmt.setClob(1, xmlClob);
} finally {;

How can I combine multiple rows into a comma-delimited list in Oracle?

The WM_CONCAT function (if included in your database, pre Oracle 11.2) or LISTAGG (starting Oracle 11.2) should do the trick nicely. For example, this gets a comma-delimited list of the table names in your schema:

select listagg(table_name, ', ') within group (order by table_name) 
  from user_tables;


select wm_concat(table_name) 
  from user_tables;

More details/options

Link to documentation

How do I get a list of locked users in an Oracle database?

Found it!

SELECT username, 
  FROM dba_users;

How to Select a substring in Oracle SQL up to a specific character?


is the right answer, as posted by user1717270

If you use INSTR, it will give you the position for a string that assumes it contains "_" in it. What if it doesn't? Well the answer will be 0. Therefore, when you want to print the string, it will print a NULL. Example: If you want to remove the domain from a "host.domain". In some cases you will only have the short name, i.e. "host". Most likely you would like to print "host". Well, with INSTR it will give you a NULL because it did not find any ".", i.e. it will print from 0 to 0. With REGEXP_SUBSTR you will get the right answer in all cases:

SELECT REGEXP_SUBSTR('HOST.DOMAIN','[^.]+',1,1)  from dual;



SELECT REGEXP_SUBSTR('HOST','[^.]+',1,1)  from dual;


if (select count(column) from table) > 0 then

not so elegant but you dont need to declare any variable:

for k in (select max(1) from table where 1 = 1) loop
    update x where column = value;
end loop;

SQL recursive query on self referencing table (Oracle)

Using the new nested query syntax

with q(name, id, parent_id, parent_name) as (
      null as parent_id, null as parent_name 
    from t1
    where = 1
  union all
    select,, as parent_id, as parent_name 
    from t1, q
    where t1.parent_id =
select * from q

How do I import a .dmp file into Oracle?

.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.

If you have an oracle client intalled on your machine, you can executed the command

imp help=y

to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')


For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

                ,'DD/Month/YYYY,HH:MI AM')

What is the best way to search the Long datatype within an Oracle database?

First convert LONG type column to CLOB type then use LIKE condition, for example:

   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices

For more information on the format models you can use with TO_CHAR on a date, see

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You need to use dynamic SQL to achieve this; something like:

    TYPE cur_type IS REF CURSOR;

    CURSOR client_cur IS
        SELECT DISTING username
        FROM all_users
        WHERE length(username) = 3;

    emails_cur cur_type;
    l_cur_string VARCHAR2(128);
    l_email_id <type>;
    l_name <type>;
    FOR client IN client_cur LOOP
        dbms_output.put_line('Client is '|| client.username);
        l_cur_string := 'SELECT id, name FROM '
            || client.username || '.org';
        OPEN emails_cur FOR l_cur_string;
            FETCH emails_cur INTO l_email_id, l_name;
            EXIT WHEN emails_cur%NOTFOUND;
            dbms_output.put_line('Org id is ' || l_email_id
                || ' org name ' || l_name);
        END LOOP;
        CLOSE emails_cur;

Edited to correct two errors, and to add links to 10g documentation for OPEN-FOR and an example. Edited to make the inner cursor query a string variable.

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Quote (read [here][1])-

When you use CAST to convert a CLOB value into a character datatype or a BLOB value into the RAW datatype, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target datatype.

So, something like this should work-

report := CAST(report_clob AS VARCHAR2(100));

Or better yet use it as CAST(report_clob AS VARCHAR2(100)) where ever you are trying to use the BLOB as VARCHAR [1]:

Dismissing a Presented View Controller

Quote from View Controller Programming Guide, "How View Controllers Present Other View Controllers".

Each view controller in a chain of presented view controllers has pointers to the other objects surrounding it in the chain. In other words, a presented view controller that presents another view controller has valid objects in both its presentingViewController and presentedViewController properties. You can use these relationships to trace through the chain of view controllers as needed. For example, if the user cancels the current operation, you can remove all objects in the chain by dismissing the first presented view controller. Dismissing a view controller dismisses not only that view controller but also any view controllers it presented.

So on one hand it makes for a nice balanced design, good de-coupling, etc... But on the other hand it's very practical, because you can quickly get back to a certain point in navigation.

Although, I personally would rather use unwinding segues than try to traverse backwards the presenting view controllers tree, which is what Apple talks about in this chapter where the quote is from.

MySQLi prepared statements error reporting

Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)

Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.

$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
  // and since all the following operations need a valid/ready statement object
  // it doesn't make sense to go on
  // you might want to use a more sophisticated mechanism than die()
  // but's it's only an example
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));

$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));


Just a few notes six years later...

The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....


     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

Why does javascript replace only first instance when using replace?

Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the g?lobal flag, which is not on by default, to replace all matches in one go.

If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:

var id= 'c_'+date.split('/').join('');

Update row with data from another row in the same table

Update MyTable
Set Value = (
                Select Min( T2.Value )
                From MyTable As T2
                Where T2.Id <> MyTable.Id
                    And T2.Name = MyTable.Name
Where ( Value Is Null Or Value = '' )
    And Exists  (
                Select 1
                From MyTable As T3
                Where T3.Id <> MyTable.Id
                    And T3.Name = MyTable.Name

CSS3 Transparency + Gradient

The following is the one that I'm using to generate a vertical gradient from completely opaque (top) to 20% in transparency (bottom) for the same color:

background: linear-gradient(to bottom, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
background: -o-linear-gradient(top, rgba(0, 64, 122, 1) 0%, rgba(0, 64, 122, 0.8) 100%); /* Opera 11.10+ */
background: -moz-linear-gradient(top, rgba(0, 64, 122, 1) 0%, rgba(0, 64, 122, 0.8) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(top, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* Chrome10-25,Safari5.1-6 */
background: -ms-linear-gradient(top, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* IE10+ */
-ms-filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00407a', endColorstr='#cc00407a',GradientType=0 ); /* IE8 */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00407a', endColorstr='#cc00407a',GradientType=0 ); /* IE 5.5 - 9 */

Hadoop: «ERROR : JAVA_HOME is not set»

In some distributives(CentOS/OpenSuSe,...) will work only if you set JAVA_HOME in the /etc/environment.

Combine Regexp?

If a string must not contain @, every character must be another character than @:


This will match any string of any length that does not contain @.

Another possible solution would be to invert the boolean result of /@/.

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
  <div id="main">
      <div class="pull-right">
  <div>MOVED BELOW Z</div>

see this demo

Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

Go Back to Previous Page

Try this:

$previous = "javascript:history.go(-1)";
if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];

in html:

<a href="<?= $previous ?>">Back</a>

The JavaScript code is initialize as fallback for HTTP_REFERER variable sometimes not work.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

Saving images in Python at a very high quality

You can save to a figure that is 1920x1080 (or 1080p) using:

fig = plt.figure(figsize=(19.20,10.80))

You can also go much higher or lower. The above solutions work well for printing, but these days you want the created image to go into a PNG/JPG or appear in a wide screen format.

Django DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

Web colors in an Android color xml resource file

Here is the improved answer from submitted by Lars: this works with the new android "L" (preview)

<?xml version="1.0" encoding="utf-8"?>
 <item name="White" type="color">#FFFFFFFF</item>
 <item name="Ivory" type="color">#FFFFFFF0</item>
 <item name="LightYellow" type="color">#FFFFFFE0</item>
 <item name="Yellow" type="color">#FFFFFF00</item>
 <item name="Snow" type="color">#FFFFFAFA</item>
 <item name="FloralWhite" type="color">#FFFFFAF0</item>
 <item name="LemonChiffon" type="color">#FFFFFACD</item>
 <item name="Cornsilk" type="color">#FFFFF8DC</item>
 <item name="Seashell" type="color">#FFFFF5EE</item>
 <item name="LavenderBlush" type="color">#FFFFF0F5</item>
 <item name="PapayaWhip" type="color">#FFFFEFD5</item>
 <item name="BlanchedAlmond" type="color">#FFFFEBCD</item>
 <item name="MistyRose" type="color">#FFFFE4E1</item>
 <item name="Bisque" type="color">#FFFFE4C4</item>
 <item name="Moccasin" type="color">#FFFFE4B5</item>
 <item name="NavajoWhite" type="color">#FFFFDEAD</item>
 <item name="PeachPuff" type="color">#FFFFDAB9</item>
 <item name="Gold" type="color">#FFFFD700</item>
 <item name="Pink" type="color">#FFFFC0CB</item>
 <item name="LightPink" type="color">#FFFFB6C1</item>
 <item name="Orange" type="color">#FFFFA500</item>
 <item name="LightSalmon" type="color">#FFFFA07A</item>
 <item name="DarkOrange" type="color">#FFFF8C00</item>
 <item name="Coral" type="color">#FFFF7F50</item>
 <item name="HotPink" type="color">#FFFF69B4</item>
 <item name="Tomato" type="color">#FFFF6347</item>
 <item name="OrangeRed" type="color">#FFFF4500</item>
 <item name="DeepPink" type="color">#FFFF1493</item>
 <item name="Fuchsia" type="color">#FFFF00FF</item>
 <item name="Magenta" type="color">#FFFF00FF</item>
 <item name="Red" type="color">#FFFF0000</item>
 <item name="OldLace" type="color">#FFFDF5E6</item>
 <item name="LightGoldenrodYellow" type="color">#FFFAFAD2</item>
 <item name="Linen" type="color">#FFFAF0E6</item>
 <item name="AntiqueWhite" type="color">#FFFAEBD7</item>
 <item name="Salmon" type="color">#FFFA8072</item>
 <item name="GhostWhite" type="color">#FFF8F8FF</item>
 <item name="MintCream" type="color">#FFF5FFFA</item>
 <item name="WhiteSmoke" type="color">#FFF5F5F5</item>
 <item name="Beige" type="color">#FFF5F5DC</item>
 <item name="Wheat" type="color">#FFF5DEB3</item>
 <item name="SandyBrown" type="color">#FFF4A460</item>
 <item name="Azure" type="color">#FFF0FFFF</item>
 <item name="Honeydew" type="color">#FFF0FFF0</item>
 <item name="AliceBlue" type="color">#FFF0F8FF</item>
 <item name="Khaki" type="color">#FFF0E68C</item>
 <item name="LightCoral" type="color">#FFF08080</item>
 <item name="PaleGoldenrod" type="color">#FFEEE8AA</item>
 <item name="Violet" type="color">#FFEE82EE</item>
 <item name="DarkSalmon" type="color">#FFE9967A</item>
 <item name="Lavender" type="color">#FFE6E6FA</item>
 <item name="LightCyan" type="color">#FFE0FFFF</item>
 <item name="BurlyWood" type="color">#FFDEB887</item>
 <item name="Plum" type="color">#FFDDA0DD</item>
 <item name="Gainsboro" type="color">#FFDCDCDC</item>
 <item name="Crimson" type="color">#FFDC143C</item>
 <item name="PaleVioletRed" type="color">#FFDB7093</item>
 <item name="Goldenrod" type="color">#FFDAA520</item>
 <item name="Orchid" type="color">#FFDA70D6</item>
 <item name="Thistle" type="color">#FFD8BFD8</item>
 <item name="LightGrey" type="color">#FFD3D3D3</item>
 <item name="Tan" type="color">#FFD2B48C</item>
 <item name="Chocolate" type="color">#FFD2691E</item>
 <item name="Peru" type="color">#FFCD853F</item>
 <item name="IndianRed" type="color">#FFCD5C5C</item>
 <item name="MediumVioletRed" type="color">#FFC71585</item>
 <item name="Silver" type="color">#FFC0C0C0</item>
 <item name="DarkKhaki" type="color">#FFBDB76B</item>
 <item name="RosyBrown" type="color">#FFBC8F8F</item>
 <item name="MediumOrchid" type="color">#FFBA55D3</item>
 <item name="DarkGoldenrod" type="color">#FFB8860B</item>
 <item name="FireBrick" type="color">#FFB22222</item>
 <item name="PowderBlue" type="color">#FFB0E0E6</item>
 <item name="LightSteelBlue" type="color">#FFB0C4DE</item>
 <item name="PaleTurquoise" type="color">#FFAFEEEE</item>
 <item name="GreenYellow" type="color">#FFADFF2F</item>
 <item name="LightBlue" type="color">#FFADD8E6</item>
 <item name="DarkGray" type="color">#FFA9A9A9</item>
 <item name="Brown" type="color">#FFA52A2A</item>
 <item name="Sienna" type="color">#FFA0522D</item>
 <item name="YellowGreen" type="color">#FF9ACD32</item>
 <item name="DarkOrchid" type="color">#FF9932CC</item>
 <item name="PaleGreen" type="color">#FF98FB98</item>
 <item name="DarkViolet" type="color">#FF9400D3</item>
 <item name="MediumPurple" type="color">#FF9370DB</item>
 <item name="LightGreen" type="color">#FF90EE90</item>
 <item name="DarkSeaGreen" type="color">#FF8FBC8F</item>
 <item name="SaddleBrown" type="color">#FF8B4513</item>
 <item name="DarkMagenta" type="color">#FF8B008B</item>
 <item name="DarkRed" type="color">#FF8B0000</item>
 <item name="BlueViolet" type="color">#FF8A2BE2</item>
 <item name="LightSkyBlue" type="color">#FF87CEFA</item>
 <item name="SkyBlue" type="color">#FF87CEEB</item>
 <item name="Gray" type="color">#FF808080</item>
 <item name="Olive" type="color">#FF808000</item>
 <item name="Purple" type="color">#FF800080</item>
 <item name="Maroon" type="color">#FF800000</item>
 <item name="Aquamarine" type="color">#FF7FFFD4</item>
 <item name="Chartreuse" type="color">#FF7FFF00</item>
 <item name="LawnGreen" type="color">#FF7CFC00</item>
 <item name="MediumSlateBlue" type="color">#FF7B68EE</item>
 <item name="LightSlateGray" type="color">#FF778899</item>
 <item name="SlateGray" type="color">#FF708090</item>
 <item name="OliveDrab" type="color">#FF6B8E23</item>
 <item name="SlateBlue" type="color">#FF6A5ACD</item>
 <item name="DimGray" type="color">#FF696969</item>
 <item name="MediumAquamarine" type="color">#FF66CDAA</item>
 <item name="CornflowerBlue" type="color">#FF6495ED</item>
 <item name="CadetBlue" type="color">#FF5F9EA0</item>
 <item name="DarkOliveGreen" type="color">#FF556B2F</item>
 <item name="Indigo" type="color">#FF4B0082</item>
 <item name="MediumTurquoise" type="color">#FF48D1CC</item>
 <item name="DarkSlateBlue" type="color">#FF483D8B</item>
 <item name="SteelBlue" type="color">#FF4682B4</item>
 <item name="RoyalBlue" type="color">#FF4169E1</item>
 <item name="Turquoise" type="color">#FF40E0D0</item>
 <item name="MediumSeaGreen" type="color">#FF3CB371</item>
 <item name="LimeGreen" type="color">#FF32CD32</item>
 <item name="DarkSlateGray" type="color">#FF2F4F4F</item>
 <item name="SeaGreen" type="color">#FF2E8B57</item>
 <item name="ForestGreen" type="color">#FF228B22</item>
 <item name="LightSeaGreen" type="color">#FF20B2AA</item>
 <item name="DodgerBlue" type="color">#FF1E90FF</item>
 <item name="MidnightBlue" type="color">#FF191970</item>
 <item name="Aqua" type="color">#FF00FFFF</item>
 <item name="Cyan" type="color">#FF00FFFF</item>
 <item name="SpringGreen" type="color">#FF00FF7F</item>
 <item name="Lime" type="color">#FF00FF00</item>
 <item name="MediumSpringGreen" type="color">#FF00FA9A</item>
 <item name="DarkTurquoise" type="color">#FF00CED1</item>
 <item name="DeepSkyBlue" type="color">#FF00BFFF</item>
 <item name="DarkCyan" type="color">#FF008B8B</item>
 <item name="Teal" type="color">#FF008080</item>
 <item name="Green" type="color">#FF008000</item>
 <item name="DarkGreen" type="color">#FF006400</item>
 <item name="Blue" type="color">#FF0000FF</item>
 <item name="MediumBlue" type="color">#FF0000CD</item>
 <item name="DarkBlue" type="color">#FF00008B</item>
 <item name="Navy" type="color">#FF000080</item>
 <item name="Black" type="color">#FF000000</item>

 <integer-array name="androidcolors">




Get domain name from given url

All the above are good. This one seems really simple to me and easy to understand. Excuse the quotes. I wrote it for Groovy inside a class called DataCenter.

static String extractDomainName(String url) {
    int start = url.indexOf('://')
    if (start < 0) {
        start = 0
    } else {
        start += 3
    int end = url.indexOf('/', start)
    if (end < 0) {
        end = url.length()
    String domainName = url.substring(start, end)

    int port = domainName.indexOf(':')
    if (port >= 0) {
        domainName = domainName.substring(0, port)

And here are some junit4 tests:

void shouldFindDomainName() {
    assert DataCenter.extractDomainName('') == ''
    assert DataCenter.extractDomainName('') == ''
    assert DataCenter.extractDomainName('') == ''
    assert DataCenter.extractDomainName('') == ''
    assert DataCenter.extractDomainName('') == ''
    assert DataCenter.extractDomainName('') == ''

Simple working Example of in

In Place of using this


You can also use


Return char[]/string from a function

Notice you're not dynamically allocating the variable, which pretty much means the data inside str, in your function, will be lost by the end of the function.

You should have:

char * createStr() {

    char char1= 'm';
    char char2= 'y';

    char *str = malloc(3);
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return str;


Then, when you call the function, the type of the variable that will receive the data must match that of the function return. So, you should have:

char *returned_str = createStr();

It worths mentioning that the returned value must be freed to prevent memory leaks.

char *returned_str = createStr();



How to make a JFrame Modal in Swing java

As others mentioned, you could use JDialog. If you don't have access to the parent frame or you want to freeze the hole application just pass null as a parent:

final JDialog frame = new JDialog((JFrame)null, frameTitle, true); frame.setModal(true);

How can I style the border and title bar of a window in WPF?

I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:

  1. download the sample project here
  2. edit the generic.xaml file to customize the layout.
  3. enjoy :).

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    Click Me

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href=""
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */

but it was never implemented in the release of the spec as far as I know.

Create Pandas DataFrame from a string

Split Method

data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])

Update statement with inner join on Oracle

This following syntax works for me.

(SELECT A.utl_id,
    FROM trb_pi_joint A
    JOIN trb_tpr B
    ON A.tp_id=B.tp_id Where A.pij_type=2 and a.utl_id is null
SET utl_id=utl1_id;

switch case statement error: case expressions must be constant expression

Simple solution for this problem is :

Click on the switch and then press CTL+1, It will change your switch to if-else block statement, and will resolve your problem

lexical or preprocessor issue file not found occurs while archiving?

Just adding another thing that worked for me :

react-native link

Evidently my ReactNative files were no longer there. I could figure that out by clicking on

Build Phases -> Link Binary with Libraries ->

Then right clicking a file I knew was responsible for React, and clicking Show In Finder .

But nothing opened. So assuming the library went missing, I just ran the above command which relinked everything again.

Also if you havn't, try :

rm -rf node_modules/ && npm install

JSON to PHP Array using file_get_contents

Check some typo ','

$jsonD = '{
                    "adate":"2 Hours ago",
                    "adesc":"test desc",
                    "adate":"20 Hours ago",
                    "adesc":"test desc1",
                    "adate":"1 Days ago",
                    "adesc":"test123 desc",
                    "adate":"2 Days ago",
                    "adesc":"test12345 desc",

$parseJ = json_decode($jsonD,true);


Running Python code in Vim

Keep in mind that you're able to repeat the last used command with @:, so that's all you'd need to repeat are those two character.

Or you could save the string w !python into one of the registers (like "a for example) and then hit :<C-R>a<CR> to insert the contents of register a into the commandline and run it.

Or you can do what I do and map <leader>z to :!python %<CR> to run the current file.

Styling of Select2 dropdown select boxes

Thanks for the suggestions in the comments. I made a bit of a dirty hack to get what I want without having to create my own image. With javascript I first hide the default tag that's being used for the down arrow, like so:


I then included font-awesome in my page and add my own down arrow, again with a line of javascript, to replace the default one:

$('.select2-arrow').append('<i class="fa fa-angle-down"></i>');

Then with CSS I style the select boxes. I set the height, change the background color of the arrow area to a gradient black, change the width, font-size and also the color of the down arrow to white:

.select2-container .select2-choice {
    padding: 5px 10px;
    height: 40px;
    width: 132px; 
    font-size: 1.2em;  

.select2-container .select2-choice .select2-arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;

The result is the styling the way I want it:


Update 5/6/2015 As @Katie Lacy mentioned in the other answer the classnames have been changed in version 4 of Select2. The updated CSS with the new classnames should look like this:

.select2-container--default .select2-selection--single{
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;


$('.select2-selection__arrow').append('<i class="fa fa-angle-down"></i>');

Multiple actions were found that match the request in Web Api

Make sure you do NOT decorate your Controller methods for the default GET|PUT|POST|DELETE actions with [HttpPost/Put/Get/Delete] attribute. I had added this attibute to my vanilla Post controller action and it caused a 404.

Hope this helps someone as it can be very frustrating and bring progress to a halt.

Token Authentication vs. Cookies

For Googlers:

  • DO NOT mix statefulness with state transfer mechanisms


  • Stateful = save authorization info on server side, this is the traditional way
  • Stateless = save authorization info on client side, along with a signature to ensure integrity


  • Cookie = a special header with special treatment (access, storage, expiration, security, auto-transfer) by browsers
  • Custom Headers = e.g. Authorization, are just headers without any special treatment, client has to manage all aspects of the transfer
  • Other. Other transfer mechanisms may be utilized, e.g. query string was a choice to transfer auth ID for a while but was abandoned for its insecurity


  • "Stateful authorization" means the server stores and maintains user authorization info on server, making authorizations part of the application state
  • This means client only need to keep an "auth ID" and the server can read auth detail from its database
  • This implies that server keeps a pool of active auths (users that are logged in) and will query this info for every request
  • "Stateless authorization" means the server does not store and maintain user auth info, it simply does not know which users are signed in, and rely on the client to produce auth info
  • Client will store complete auth info like who you are (user ID), and possibly permissions, expiration time, etc., this is more than just auth ID, so it is given a new name token
  • Obviously client cannot be trusted, so auth data is stored along with a signature generated from hash(data + secret key), where secret key is only known to server, so the integrity of token data can be verified
  • Note that token mechanism merely ensures integrity, but not confidentiality, client has to implement that
  • This also means for every request client has to submit a complete token, which incurs extra bandwidth


  • "Cookie" is just a header, but with some preloaded operations on browsers
  • Cookie can be set by server and auto-saved by client, and will auto-send for same domain
  • Cookie can be marked as httpOnly thus prevent client JavaScript access
  • Preloaded operations may not be available on platforms other than browsers (e.g. mobile), which may lead to extra efforts
  • "Custom headers" are just custom headers without preloaded operations
  • Client is responsible to receive, store, secure, submit and update the custom header section for each requests, this may help prevent some simple malicious URL embedding


  • There is no magic, auth state has to be stored somewhere, either at server or client
  • You may implement stateful/stateless with either cookie or other custom headers
  • When people talk about those things their default mindset is mostly: stateless = token + custom header, stateful = auth ID + cookie; these are NOT the only possible options
  • They have pros and cons, but even for encrypted tokens you should not store sensitive info


CRC32 C or C++ implementation

using zlib.h (

#include <zlib.h>
unsigned long  crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const unsigned char*)data_address, data_len);

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

If your environment is using both Guice and Spring and using the constructor @Inject, for example, with Play Framework, you will also run into this issue if you have mistakenly auto-completed the import with an incorrect choice of:


Then you get the same missing default constructor error even though the rest of your source with @Inject looks exactly the same way as other working components in your project and compile without an error.

Correct that with:

import javax.inject.Inject;

Do not write a default constructor with construction time injection.

Python progression path - From apprentice to guru

If you're in and using python for science (which it seems you are) part of that will be learning and understanding scientific libraries, for me these would be

  • numpy
  • scipy
  • matplotlib
  • mayavi/mlab
  • chaco
  • Cython

knowing how to use the right libraries and vectorize your code is essential for scientific computing.

I wanted to add that, handling large numeric datasets in common pythonic ways(object oriented approaches, lists, iterators) can be extremely inefficient. In scientific computing, it can be necessary to structure your code in ways that differ drastically from how most conventional python coders approach data.

?: ?? Operators Instead Of IF|ELSE

Refering to ?: Operator (C# Reference)

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

Refering to ?? Operator (C# Reference)

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

That means:

[Part 1]

return source ?? String.Empty;

[Part 2] is not applicable ...

Running Selenium WebDriver python bindings in chrome

There are 2 ways to run Selenium python tests in Google Chrome. I'm considering Windows (Windows 10 in my case):

Prerequisite: Download the latest Chrome Driver from:

Way 1:

i) Extract the downloaded zip file in a directory/location of your choice
ii) Set the executable path in your code as below:

self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')

Way 2:

i) Simply paste the chromedriver.exe under /Python/Scripts/ (In my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:

self.driver = webdriver.Chrome()

javascript multiple OR conditions in IF statement

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

How to draw vertical lines on a given plot in matplotlib

Calling axvline in a loop, as others have suggested, works, but can be inconvenient because

  1. Each line is a separate plot object, which causes things to be very slow when you have many lines.
  2. When you create the legend each line has a new entry, which may not be what you want.

Instead you can use the following convenience functions which create all the lines as a single plot object:

import matplotlib.pyplot as plt
import numpy as np

def axhlines(ys, ax=None, lims=None, **plot_kwargs):
    Draw horizontal lines across plot
    :param ys: A scalar, list, or 1D array of vertical offsets
    :param ax: The axis (or none to use gca)
    :param lims: Optionally the (xmin, xmax) of the lines
    :param plot_kwargs: Keyword arguments to be passed to plot
    :return: The plot object corresponding to the lines.
    if ax is None:
        ax = plt.gca()
    ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
    if lims is None:
        lims = ax.get_xlim()
    y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
    x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
    plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
    return plot

def axvlines(xs, ax=None, lims=None, **plot_kwargs):
    Draw vertical lines on plot
    :param xs: A scalar, list, or 1D array of horizontal offsets
    :param ax: The axis (or none to use gca)
    :param lims: Optionally the (ymin, ymax) of the lines
    :param plot_kwargs: Keyword arguments to be passed to plot
    :return: The plot object corresponding to the lines.
    if ax is None:
        ax = plt.gca()
    xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
    if lims is None:
        lims = ax.get_ylim()
    x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
    y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
    plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
    return plot

webpack: Module not found: Error: Can't resolve (with relative path)

I had a different problem. some of my includes were set to 'app/src/xxx/yyy' instead of '../xxx/yyy'

How to properly make a http web GET request

Simpliest way for my opinion

  var web = new WebClient();
  var url = $"{hostname}/LoadDataSync?systemID={systemId}";
  var responseString = web.DownloadString(url);


 var bytes = web.DownloadData(url);

Setting DEBUG = False causes 500 Error

I know this is late but I ended up here with a search for my error 500 with DEBUG=False, in my case it did turn out to be the ALLOWED_HOSTS but I was using os.environ.get('variable') to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False:

    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        'simple': {
            'format': '%(levelname)s %(message)s'
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
    'loggers': {
        'django': {
            'propagate': True,
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',

How to group pandas DataFrame entries by date in a non-unique column

This should work:

data.groupby(lambda x: data['date'][x].year)

How to get element value in jQuery

$("#list li").click(function() {
        var selected = $(this).html();

Class has no member named

Most of the time, the problem is due to some error on the human side. In my case, I was using some classes whose names are similar. I have added the empty() method under one class; however, my code was calling the empty() method from another class. At that moment, the mind was stuck. I was running make clean, and remake thinking that it was some older version of the header got used. After walking away for a moment, I found that problem right away. We programmers tends to blame others first. Maybe we should insist on ourselves to be wrong first.

Sometimes, I forget to write the latest update to disk and looking at the correct version of the code, but the compiler is seeing the wrong version of the code. This situation may be less a issue on IDE (I use vi to do coding).

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    width: auto !important;

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

How can I exclude one word with grep?

The -v option will show you all the lines that don't match the pattern.

grep -v ^unwanted_word

Passing multiple values for a single parameter in Reporting Services

Modification of great John solution, solve:

  • "2 quotes" error
  • space after one of piece in parameter

    ALTER FUNCTION [dbo].[fn_MVParam]
    (@RepParam nvarchar(4000), @Delim char(1)= ',')
    RETURNS @Values TABLE (Param nvarchar(4000))AS
    //2 quotes error
    set @RepParam = replace(@RepParam,char(39)+char(39),CHAR(39))
    DECLARE @chrind INT
    DECLARE @Piece nvarchar(100)
    SELECT @chrind = 1 
    WHILE @chrind > 0
      SELECT @chrind = CHARINDEX(@Delim,@RepParam)
      IF @chrind  > 0
        SELECT @Piece = LEFT(@RepParam,@chrind - 1)
        SELECT @Piece = @RepParam
      INSERT  @Values(Param) VALUES(CAST(@Piece AS VARCHAR(300)))
      //space after one of piece in parameter: LEN(@RepParam + '1')-1
      SELECT @RepParam = RIGHT(@RepParam,LEN(@RepParam + '1')-1 - @chrind)
      IF LEN(@RepParam) = 0 BREAK

What is an optional value in Swift?

You can't have a variable that points to nil in Swift — there are no pointers, and no null pointers. But in an API, you often want to be able to indicate either a specific kind of value, or a lack of value — e.g. does my window have a delegate, and if so, who is it? Optionals are Swift's type-safe, memory-safe way to do this.

Multiple left joins on multiple tables in one query

This kind of query should work - after rewriting with explicit JOIN syntax:

SELECT something
FROM   master      parent
JOIN   master      child ON child.parent_id =
LEFT   JOIN second parentdata ON = parent.secondary_id
LEFT   JOIN second childdata ON = child.secondary_id
WHERE  parent.parent_id = 'rootID'

The tripping wire here is that an explicit JOIN binds before "old style" CROSS JOIN with comma (,). I quote the manual here:

In any case JOIN binds more tightly than the commas separating FROM-list items.

After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.

Just to make my point, this would work, too:

SELECT something
FROM   master parent
LEFT   JOIN second parentdata ON = parent.secondary_id
,      master child
LEFT   JOIN second childdata ON = child.secondary_id
WHERE  child.parent_id =
AND    parent.parent_id = 'rootID'

But explicit JOIN syntax is generally preferable, as your case illustrates once again.

And be aware that multiple (LEFT) JOIN can multiply rows:

How to get a list of column names

SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

Then parse this value with Reg Exp (it's easy) which could looks similar to this: [(.*?)]

Alternatively you can use:

PRAGMA table_info(table_name)

Syntax for a for loop in ruby

['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}

Thymeleaf using path variables to th:href

I was trying to go through a list of objects, display them as rows in a table, with each row being a link. This worked for me. Hope it helps.

// CUSTOMER_LIST is a model attribute
    <th:block th:each="customer : ${CUSTOMER_LIST}">
            <td><a th:href="@{'/main?id=' + ${}}" th:text="${customer.fullName}" /></td>

Add carriage return to a string

string s2 = s1.Replace(",", ",\n");

How to send and retrieve parameters using $state.go toParams and $stateParams?

If you want to pass non-URL state, then you must not use url when setting up your state. I found the answer on a PR and did some monkeying around to better understand.

$stateProvider.state('toState', {
  params: {
    'referer': 'some default', 
    'param2': 'some default', 
    'etc': 'some default'

Then you can navigate to it like so:

$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });


var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);

And in HTML thusly:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.

batch script - run command on each file in directory

Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES

in your case

forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"

the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway

How to access a RowDataPacket object

Hi try this 100% works:


Overriding interface property type defined in Typescript d.ts file

Omit the property when extending the interface:

interface A {
  a: number;
  b: number;

interface B extends Omit<A, 'a'> {
  a: boolean;

Space between two divs

You can try something like the following:


or instead of the first h1 rule:


or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:

div + div{

Respectively, h1 + div would control the first div after your header, giving you additional styling options.

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:


Start a package


npm start [-- <args>]


This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

Convert object of any type to JObject with Json.NET

If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial);

like this :

Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,

JObject o = (JObject)JToken.FromObject(pocionDeVida);
// {"tipo": "vida", "duracion": 32,}

Can anyone explain me StandardScaler?

The answers above are great, but I needed a simple example to alleviate some concerns that I have had in the past. I wanted to make sure it was indeed treating each column separately. I am now reassured and can't find what example had caused me concern. All columns ARE scaled separately as described by those above.


import pandas as pd
import scipy.stats as ss
from sklearn.preprocessing import StandardScaler

data= [[1, 1, 1, 1, 1],[2, 5, 10, 50, 100],[3, 10, 20, 150, 200],[4, 15, 40, 200, 300]]

df = pd.DataFrame(data, columns=['N0', 'N1', 'N2', 'N3', 'N4']).astype('float64')

sc_X = StandardScaler()
df = sc_X.fit_transform(df)

num_cols = len(df[0,:])
for i in range(num_cols):
    col = df[:,i]
    col_stats = ss.describe(col)


DescribeResult(nobs=4, minmax=(-1.3416407864998738, 1.3416407864998738), mean=0.0, variance=1.3333333333333333, skewness=0.0, kurtosis=-1.3599999999999999)
DescribeResult(nobs=4, minmax=(-1.2828087129930659, 1.3778315806221817), mean=-5.551115123125783e-17, variance=1.3333333333333337, skewness=0.11003776770595125, kurtosis=-1.394993095506219)
DescribeResult(nobs=4, minmax=(-1.155344148338584, 1.53471088361394), mean=0.0, variance=1.3333333333333333, skewness=0.48089217736510326, kurtosis=-1.1471008824318165)
DescribeResult(nobs=4, minmax=(-1.2604572012883055, 1.2668071116222517), mean=-5.551115123125783e-17, variance=1.3333333333333333, skewness=0.0056842140599118185, kurtosis=-1.6438177182479734)
DescribeResult(nobs=4, minmax=(-1.338945389819976, 1.3434309690153527), mean=5.551115123125783e-17, variance=1.3333333333333333, skewness=0.005374558840039456, kurtosis=-1.3619131970819205)


The scipy.stats module is correctly reporting the "sample" variance, which uses (n - 1) in the denominator. The "population" variance would use n in the denominator for the calculation of variance. To understand better, please see the code below that uses scaled data from the first column of the data set above:


import scipy.stats as ss

sc_Data = [[-1.34164079], [-0.4472136], [0.4472136], [1.34164079]]
col_stats = ss.describe([-1.34164079, -0.4472136, 0.4472136, 1.34164079])

mean_by_hand = 0
for row in sc_Data:
    for element in row:
        mean_by_hand += element
mean_by_hand /= 4

variance_by_hand = 0
for row in sc_Data:
    for element in row:
        variance_by_hand += (mean_by_hand - element)**2
sample_variance_by_hand = variance_by_hand / 3
sample_std_dev_by_hand = sample_variance_by_hand ** 0.5

pop_variance_by_hand = variance_by_hand / 4
pop_std_dev_by_hand = pop_variance_by_hand ** 0.5

print("Sample of Population Calcs:")
print(mean_by_hand, sample_variance_by_hand, sample_std_dev_by_hand, '\n')
print("Population Calcs:")
print(mean_by_hand, pop_variance_by_hand, pop_std_dev_by_hand)


DescribeResult(nobs=4, minmax=(-1.34164079, 1.34164079), mean=0.0, variance=1.3333333422778562, skewness=0.0, kurtosis=-1.36000000429325)

Sample of Population Calcs:
0.0 1.3333333422778562 1.1547005422523435

Population Calcs:
0.0 1.000000006708392 1.000000003354196

Get filename in batch for loop

or Just %~F will give you the full path and full file name.

For example, if you want to register all *.ax files in the current directory....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

Invalid default value for 'create_date' timestamp field

I was able to resolve this issue on OS X by installing MySQL from Homebrew

brew install mysql

by adding the following to /usr/local/etc/my.cnf


and restarting MySQL

brew tap homebrew/services
brew services restart mysql

How to import a .cer certificate into a java keystore?

  • If you want to authenticate you need the private key - there is no other option.
  • A certificate is a public key with extra properties (like company name, country,...) that is signed by some Certificate authority that guarantees that the attached properties are true.
  • .CER files are certificates and don't have the private key. The private key is provided with a .PFX keystore file normally. If you really authenticate is because you already had imported the private key.
  • You normally can import .CER certificates without any problems with

    keytool -importcert -file certificate.cer -keystore keystore.jks -alias "Alias" 

Stop Excel from automatically converting certain text values to dates

While creating the string to be written to my CSV file in C# I had to format it this way:

"=\"" + myVariable + "\""

How to remove index.php from URLs?

Hi I'm late to the party.. just wanted to point out that the instructions from were really useful.

I had Ubuntu server installed with Apache, MySql and Php so I thought I could jump to the heading Creating the directory from which Magento will be served from and I reached the same problem as the OP, i.e. I had 'index.php' needed in all the URLs (or I would get 404 not found). I then went back to Installing and configuring the Apache HTTP server and after restarting apache it works perfectly.

For reference, I was missing:

sudo bash -c "cat >> /etc/apache2/conf.d/servername.conf <<EOF
ServerName localhost

... and

sudo a2enmod rewrite
sudo service apache2 restart

Hope this helps

How to change background color in android app

You can change the value after '#' according to your own specification or need depending on how you want to use them.
Here is a sample code:

        android:background="#D4E157"  />

Thank you :)

Shared folder between MacOSX and Windows on Virtual Box

Using a Windows 10 guest, after I performed steps 1 through 3 from @xinampc's answer, I had to open a new File Explorer and navigated to This PC > CD Drive (D:) VirtualBox Guest Additions to run VBoxWindowsAdditions. After I ran that and went through the command prompts, Windows rebooted and I was able to see VBOXSVR under Network.

Passing data between controllers in Angular JS?

I don't know if it will help anyone, but based on Charx (thanks!) answer I have created simple cache service. Feel free to use, remix and share:

angular.service('cache', function() {
    var _cache, _store, _get, _set, _clear;
    _cache = {};

    _store = function(data) {
        angular.merge(_cache, data);

    _set = function(data) {
        _cache = angular.extend({}, data);

    _get = function(key) {
        if(key == null) {
            return _cache;
        } else {
            return _cache[key];

    _clear = function() {
        _cache = {};

    return {
        get: _get,
        set: _set,
        store: _store,
        clear: _clear

Magento: Set LIMIT on collection

You can Implement this also:- setPage(1, n); where, n = any number.

$products = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect(array('name', 'price', 'small_image'))
                ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //visible only catalog & searchable product
                ->addAttributeToFilter('status', 1) // enabled
                ->setOrder('created_at', 'desc')
                ->setPage(1, 6);

How do I get a class instance of generic type T?

As explained in other answers, to use this ParameterizedType approach, you need to extend the class, but that seems like extra work to make a whole new class that extends it...

So, making the class abstract it forces you to extend it, thus satisfying the subclassing requirement. (using lombok's @Getter).

public abstract class ConfigurationDefinition<T> {

    private Class<T> type;

    public ConfigurationDefinition(...) {
        this.type = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

Now to extend it without defining a new class. (Note the {} on the end... extended, but don't overwrite anything - unless you want to).

private ConfigurationDefinition<String> myConfigA = new ConfigurationDefinition<String>(...){};
private ConfigurationDefinition<File> myConfigB = new ConfigurationDefinition<File>(...){};
Class stringType = myConfigA.getType();
Class fileType = myConfigB.getType();

What killed my process and why?

This is the Linux out of memory manager (OOM). Your process was selected due to 'badness' - a combination of recentness, resident size (memory in use, rather than just allocated) and other factors.

sudo journalctl -xb

You'll see a message like:

Jul 20 11:05:00 someapp kernel: Mem-Info:
Jul 20 11:05:00 someapp kernel: Node 0 DMA per-cpu:
Jul 20 11:05:00 someapp kernel: CPU    0: hi:    0, btch:   1 usd:   0
Jul 20 11:05:00 someapp kernel: Node 0 DMA32 per-cpu:
Jul 20 11:05:00 someapp kernel: CPU    0: hi:  186, btch:  31 usd:  30
Jul 20 11:05:00 someapp kernel: active_anon:206043 inactive_anon:6347 isolated_anon:0
                                    active_file:722 inactive_file:4126 isolated_file:0
                                    unevictable:0 dirty:5 writeback:0 unstable:0
                                    free:12202 slab_reclaimable:3849 slab_unreclaimable:14574
                                    mapped:792 shmem:12802 pagetables:1651 bounce:0
Jul 20 11:05:00 someapp kernel: Node 0 DMA free:4576kB min:708kB low:884kB high:1060kB active_anon:10012kB inactive_anon:488kB active_file:4kB inactive_file:4kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present
Jul 20 11:05:00 someapp kernel: lowmem_reserve[]: 0 968 968 968
Jul 20 11:05:00 someapp kernel: Node 0 DMA32 free:44232kB min:44344kB low:55428kB high:66516kB active_anon:814160kB inactive_anon:24900kB active_file:2884kB inactive_file:16500kB unevictable:0kB isolated(anon):0kB isolated
Jul 20 11:05:00 someapp kernel: lowmem_reserve[]: 0 0 0 0
Jul 20 11:05:00 someapp kernel: Node 0 DMA: 17*4kB (UEM) 22*8kB (UEM) 15*16kB (UEM) 12*32kB (UEM) 8*64kB (E) 9*128kB (UEM) 2*256kB (UE) 3*512kB (UM) 0*1024kB 0*2048kB 0*4096kB = 4580kB
Jul 20 11:05:00 someapp kernel: Node 0 DMA32: 216*4kB (UE) 601*8kB (UE) 448*16kB (UE) 311*32kB (UEM) 135*64kB (UEM) 74*128kB (UEM) 5*256kB (EM) 0*512kB 0*1024kB 1*2048kB (R) 0*4096kB = 44232kB
Jul 20 11:05:00 someapp kernel: Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=2048kB
Jul 20 11:05:00 someapp kernel: 17656 total pagecache pages
Jul 20 11:05:00 someapp kernel: 0 pages in swap cache
Jul 20 11:05:00 someapp kernel: Swap cache stats: add 0, delete 0, find 0/0
Jul 20 11:05:00 someapp kernel: Free swap  = 0kB
Jul 20 11:05:00 someapp kernel: Total swap = 0kB
Jul 20 11:05:00 someapp kernel: 262141 pages RAM
Jul 20 11:05:00 someapp kernel: 7645 pages reserved
Jul 20 11:05:00 someapp kernel: 264073 pages shared
Jul 20 11:05:00 someapp kernel: 240240 pages non-shared
Jul 20 11:05:00 someapp kernel: [ pid ]   uid  tgid total_vm      rss nr_ptes swapents oom_score_adj name
Jul 20 11:05:00 someapp kernel: [  241]     0   241    13581     1610      26        0             0 systemd-journal
Jul 20 11:05:00 someapp kernel: [  246]     0   246    10494      133      22        0         -1000 systemd-udevd
Jul 20 11:05:00 someapp kernel: [  264]     0   264    29174      121      26        0         -1000 auditd
Jul 20 11:05:00 someapp kernel: [  342]     0   342    94449      466      67        0             0 NetworkManager
Jul 20 11:05:00 someapp kernel: [  346]     0   346   137495     3125      88        0             0 tuned
Jul 20 11:05:00 someapp kernel: [  348]     0   348    79595      726      60        0             0 rsyslogd
Jul 20 11:05:00 someapp kernel: [  353]    70   353     6986       72      19        0             0 avahi-daemon
Jul 20 11:05:00 someapp kernel: [  362]    70   362     6986       58      18        0             0 avahi-daemon
Jul 20 11:05:00 someapp kernel: [  378]     0   378     1621       25       8        0             0 iprinit
Jul 20 11:05:00 someapp kernel: [  380]     0   380     1621       26       9        0             0 iprupdate
Jul 20 11:05:00 someapp kernel: [  384]    81   384     6676      142      18        0          -900 dbus-daemon
Jul 20 11:05:00 someapp kernel: [  385]     0   385     8671       83      21        0             0 systemd-logind
Jul 20 11:05:00 someapp kernel: [  386]     0   386    31573      153      15        0             0 crond
Jul 20 11:05:00 someapp kernel: [  391]   999   391   128531     2440      48        0             0 polkitd
Jul 20 11:05:00 someapp kernel: [  400]     0   400     9781       23       8        0             0 iprdump
Jul 20 11:05:00 someapp kernel: [  419]     0   419    27501       32      10        0             0 agetty
Jul 20 11:05:00 someapp kernel: [  855]     0   855    22883      258      43        0             0 master
Jul 20 11:05:00 someapp kernel: [  862]    89   862    22926      254      44        0             0 qmgr
Jul 20 11:05:00 someapp kernel: [23631]     0 23631    20698      211      43        0         -1000 sshd
Jul 20 11:05:00 someapp kernel: [12884]     0 12884    81885     3754      80        0             0 firewalld
Jul 20 11:05:00 someapp kernel: [18130]     0 18130    33359      291      65        0             0 sshd
Jul 20 11:05:00 someapp kernel: [18132]  1000 18132    33791      748      64        0             0 sshd
Jul 20 11:05:00 someapp kernel: [18133]  1000 18133    28867      122      13        0             0 bash
Jul 20 11:05:00 someapp kernel: [18428]    99 18428   208627    42909     151        0             0 node
Jul 20 11:05:00 someapp kernel: [18486]    89 18486    22909      250      46        0             0 pickup
Jul 20 11:05:00 someapp kernel: [18515]  1000 18515   352905   141851     470        0             0 npm
Jul 20 11:05:00 someapp kernel: [18520]     0 18520    33359      291      66        0             0 sshd
Jul 20 11:05:00 someapp kernel: [18522]  1000 18522    33359      294      64        0             0 sshd
Jul 20 11:05:00 someapp kernel: [18523]  1000 18523    28866      115      12        0             0 bash
Jul 20 11:05:00 someapp kernel: Out of memory: Kill process 18515 (npm) score 559 or sacrifice child
Jul 20 11:05:00 someapp kernel: Killed process 18515 (npm) total-vm:1411620kB, anon-rss:567404kB, file-rss:0kB

Flutter: RenderBox was not laid out

Wrap your ListView in an Expanded widget


mysql query result in php variable

$query="SELECT * FROM contacts";

How to keep indent for second line in ordered lists via CSS?

I believe this will do what you are looking for.

.cssClass li {
    list-style-type: disc;
    list-style-position: inside;
    text-indent: -1em;
    padding-left: 1em;


enter image description here

Is there a label/goto in Python?

I have my own way of doing gotos. I use separate python scripts.

If I want to loop:

print("test test")
a = a + 1

if a == 10:

print(a + " equals 10")

(NOTE: This technique only works on Python 2.x versions)

Moving Panel in Visual Studio Code to right side

"Wokbench.panel.defaultLocation": "right"

Open settings using CTRL+., search for terminal and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.

enter image description here

JOptionPane Yes or No window

You are always checking for a true condition, hence your message will always show.

You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

When one of the showXxxDialog methods returns an integer, the possible values are:


From here

How can I remove specific rules from iptables?

Execute the same commands but replace the "-A" with "-D". For example:

iptables -A ...


iptables -D ...

ComboBox.SelectedText doesn't give me the SelectedText

or try this code

 String status = "The status of my combobox is " + comboBoxTest.SelectedItem.ToString();

Can a JSON value contain a multiline string

I believe it depends on what json interpreter you're using... in plain javascript you could use line terminators

  "testCases" :
    "case.1" :
      "scenario" : "this the case 1.",
      "result" : "this is a very long line which is not easily readble. \
                  so i would like to write it in multiple lines. \
                  but, i do NOT require any new lines in the output."

How to randomly pick an element from an array

package io.github.baijifeilong.tmp;

import java.util.concurrent.ThreadLocalRandom;

 * Created by [email protected] at 2019/1/3 ??7:34
public class Bar {
    public static void main(String[] args) {
        Stream.generate(() -> null).limit(10).forEach($ -> {
            System.out.println(new String[]{"hello", "world"}[ThreadLocalRandom.current().nextInt(2)]);

Saving an image in OpenCV

I suggest you run OpenCV sanity check

Its a serie of small executables located in the bin directory of opencv.

It will check if your camera is ok

Where is the IIS Express configuration / metabase file found?

To come full circle and include all versions of Visual Studio, @Myster originally stated that;

Pre Visual Studio 2015 the paths to applicationhost.config were:

%userprofile%\my documents\iisexpress\config\applicationhost.config

Visual Studio 2015/2017 path can be found at: (credit: @Talon)


Visual Studio 2019 path can be found at: (credit: @Talon)


But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)

So, if you make a change in the applicationhost.config you also have to make sure your changes match here:


The two important settings should look like:



VWDPort = "Port#"

What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.

Making text bold using attributed string in swift

edit/update: Xcode 8.3.2 • Swift 3.1

If you know HTML and CSS you can use it to easily control the font style, color and size of your attributed string as follow:

extension String {
    var html2AttStr: NSAttributedString? {
        return try? NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)

"<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2AttStr

Android: How to enable/disable option menu item on button click?

What I did was save a reference to the Menu at onCreateOptionsMenu. This is similar to nir's answer except instead of saving each individual item, I saved the entire menu.

Declare a Menu Menu toolbarMenu;.

Then in onCreateOptionsMenusave the menu to your variable

public boolean onCreateOptionsMenu(Menu menu)
    getMenuInflater().inflate(, menu);
    toolbarMenu = menu;
    return true;

Now you can access your menu and all of its items anytime you want. toolbarMenu.getItem(0).setEnabled(false);

FIFO class in Java

Try ArrayDeque or LinkedList, which both implement the Queue interface.

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Python - TypeError: 'int' object is not iterable

If the case is:


Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

Getting distance between two points based on latitude/longitude

I arrived at a much simpler and robust solution which is using geodesic from geopy package since you'll be highly likely using it in your project anyways so no extra package installation needed.

Here is my solution:

from geopy.distance import geodesic

origin = (30.172705, 31.526725)  # (latitude, longitude) don't confuse
dist = (30.288281, 31.732326)

print(geodesic(origin, dist).meters)  # 23576.805481751613
print(geodesic(origin, dist).kilometers)  # 23.576805481751613
print(geodesic(origin, dist).miles)  # 14.64994773134371


How do I check if an integer is even or odd?

Modulus operator '%' can be used to check whether a number is odd or even.That is when a number is divided by 2 and if the remainder is 0 then its an even number else its an odd number.

#include <stdio.h>
int main()
    int n;//using modulus operator
    scanf("%d",&n);//take input n from STDIN 
    printf("%s",n%2==0?"Even":"Odd");//prints Even/Odd depending on n to STDOUT
    return 0;

But using Bit manipulation is quite faster than the above method,so if you take a number and apply logically AND '&' to it ,if the answer is 1 then its even else its odd.That is basically we have to check the last bit of the number n in binary.If the last bit is 0 then n is even else its odd.

for example : suppose N = 15 , in binary N = 1111 , now we AND it with 1


Since the result is 1 the number N=15 is Odd.

Again,suppose N = 8 , in binary N = 1000 , now we AND it with 1


Since the result is 0 the number N=8 is Even.

#include <stdio.h>

int main()
    int n;//using AND operator
    scanf("%d",&n);//take input n from STDIN 
    printf("%s",n&1?"Odd":"Even");//prints Even/Odd depending on n to STDOUT
    return 0;

CSS to make table 100% of max-width

Like this




Center-align a HTML table

margin-left: auto;
margin-right: auto;

This will definitely work. Cheers

Save and load weights in keras

For loading weights, you need to have a model first. It must be:


If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model = load_model('filename')

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

Peak memory usage of a linux/unix process

Here's a one-liner that doesn't require any external scripts or utilities and doesn't require you to start the process via another program like Valgrind or time, so you can use it for any process that's already running:

grep VmPeak /proc/$PID/status

(replace $PID with the PID of the process you're interested in)

How can I enable the MySQLi extension in PHP 7?

In Ubuntu, you need to uncomment this line in file php.ini which is located at /etc/php/7.0/apache2/php.ini:

Reading all files in a directory, store them in objects, and send the object

If you have Node.js 8 or later, you can use the new util.promisify. (I'm marking as optional the parts of the code that have to do with reformatting as an object, which the original post requested.)

  const fs = require('fs');
  const { promisify } = require('util');

  let files; // optional
  promisify(fs.readdir)(directory).then((filenames) => {
    files = filenames; // optional
    return Promise.all( => {
      return promisify(fs.readFile)(directory + filename, {encoding: 'utf8'});
  }).then((strArr) => {
    // optional:
    const data = {};
    strArr.forEach((str, i) => {
      data[files[i]] = str;
    // send data here
  }).catch((err) => {

maxReceivedMessageSize and maxBufferSize in app.config

Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available


        <binding name="Service1Soap"/>

After Edit/Update

        <binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>

How do I empty an input value with jQuery?

Usual way to empty textbox using jquery is:


If above code is not working than please check that you are able to get the input element.

console.log($('#txtInput')); // should return element in the console.

If still facing the same problem, please post your code.

Lists in ConfigParser

So another way, which I prefer, is to just split the values, for example:

first_row = 1,2,4,8,12,24,36,48

Could be loaded like this into a list of strings or integers, as follows:

import configparser

config = configparser.ConfigParser()'/path/to/config.cfg')

# Load into a list of strings
first_row_strings = config.get('Numbers', 'first_row').split(',')

# Load into a list of integers
first_row_integers = [int(x) for x in config.get('Numbers', 'first_row').split(',')]

This method prevents you from needing to wrap your values in brackets to load as JSON.

Show/Hide Table Rows using Javascript classes

AngularJS directives ng-show, ng-hide allows to display and hide a row:

   <tr ng-show="rw.isExpanded">

A row will be visible when rw.isExpanded == true and hidden when rw.isExpanded == false. ng-hide performs the same task but requires inverse condition.

Xcode 7.2 no matching provisioning profiles found

For me none of the solution worked, but If i disconnect the phone from laptop and then run the build, it succeeds and then I connect and run on the phone. I still couldn't figure out the final fix.

"Debug certificate expired" error in Eclipse Android plugins

It's a pain to have to delete all your development .apk files, because the new certificate doesn't match so you can't upgrade them in all your AVDs. You have to get another development MAP-API key as well. There's another solution.

You can create your own debug certificate in debug.keystore with whatever expiration you want. Do this in the .android folder under your HOME directory:

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 14000

keytool.exe can be found in the JDK bin folder (e.g. C:\Program Files\Java\jdk1.6.0_31\bin\ on Windows).

ADT sets the first and last name on the certificate as "Android Debug", the organizational unit as "Android" and the two-letter country code as "US". You can leave the organization, city, and state values as "Unknown". This example uses a validity of 14000 days. You can use whatever value you like.

Powershell command to hide user from exchange address lists

For Office 365 users or Hybrid exchange, go to using Internet Explorer or Edge, go to the exchange admin center, choose hybrid, setup, chose the right button for hybrid or exchange online.

To connect:


To see the relevant mailboxes:

Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientType -eq 'UserMailbox' -and RecipientTypeDetails -ne 'SharedMailbox' }

To block based on the above idea of 0KB size:

Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientTypeDetails -ne 'SharedMailbox' -and RecipientType -eq 'UserMailbox' } | Set-Mailbox -MaxReceiveSize 0KB -HiddenFromAddressListsEnabled $true

how to query for a list<String> in jdbctemplate

Is there a way to have placeholders, like ? for column names? For example SELECT ? FROM TABLEA GROUP BY ?

Use dynamic query as below:

String queryString = "SELECT "+ colName+ " FROM TABLEA GROUP BY "+ colName;

If I want to simply run the above query and get a List what is the best way?

List<String> data = getJdbcTemplate().query(query, new RowMapper<String>(){
                            public String mapRow(ResultSet rs, int rowNum) 
                                                         throws SQLException {
                                    return rs.getString(1);

EDIT: To Stop SQL Injection, check for non word characters in the colName as :

          Pattern pattern = Pattern.compile("\\W");
               //throw exception as invalid column name

Get textarea text with javascript or Jquery

Get textarea text with JavaScript:

<!DOCTYPE html>
<form id="form1">
        <textarea id="area1" rows="5">Yes</textarea>
        <input type="button" value="get txt" onclick="go()" />
        <br />
        <p id="as">Now what</p>

function go() {
    var c1 = document.getElementById('area1').value;
    var d1 = document.getElementById('as');
    d1.innerHTML = c1;

Changing .gitconfig location on Windows

Change HOME directory for this is wrong. Better is create symbolic link for gitconfig to HOME directory.

  1. Move your .gitconfig from user home directory, to the directory where you want.
  2. Run command line as Administrator
  3. Go to your user home directory
  4. Enter mklink .gitconfig \PathForNewLocationOfConfig.gitconfig

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

As far as I remember, in the current JDBC, Resultsets and statements implement the AutoCloseable interface. That means they are closed automatically upon being destroyed or going out of scope.

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

When using $_SERVER["REMOTE_ADDR"], I get the server's IP address rather than the visitor's.

Then something is wrong, or odd, with your configuration.

  • Are you using some sort of reverse proxy? In that case, @simshaun's suggestion may work.

  • Do you have anything else out of the ordinary in your web server config?

  • Can you show the PHP code you are using?

  • Can you show what the address looks like. Is it a local one, or a Internet address?

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

On windows Power Shell, you can use the following command:

New-Item <filename.extension>


New-Item <filename.extension> -type file

Note: New-Item can be replaced with its alias ni

Python List & for-each access (Find/Replace in built-in list)

You could replace something in there by getting the index along with the item.

>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
...     print(index, item)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
...     if item in ('a', 'A'):
...         foo[index] = 'replaced!'
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']

Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.


>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
...     if isinstance(item, int):
...         foo.remove(item)
>>> foo 
['a', 'b', 'c', 2]

The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:

>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
...     if isinstance(item, int):
...         foo.remove(item)
>>> foo 
['a', 'b', 'c']

How to use jQuery in AngularJS

The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.

    ['$timeout', function($timeout) {
        return {
            scope: true,
            template: '<div id="{{ id }}"></div>',
            link: function($scope) {
                $ = String(Math.random()).substr(2, 8);

                $timeout(function() {

bash export command

Are you certain that the software (and not yourself, since your test actually only shows the shell used as default for your user) uses /bin/bash ?

Pass react component as props

As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:

Make sure you are actually passing a component and not an object (this tripped me up initially).

The code is simply this:

const Parent = () => { 
  return (
    <Child  componentToPassDown={<SomeComp />}  />

const Child = ({ componentToPassDown }) => { 
  return (

How can I get a collection of keys in a JavaScript dictionary?

With a modern JavaScript engine you can use Object.keys(driversCounter).

Best way to parse command-line parameters?

Here is mine 1-liner

    def optArg(prefix: String) = args.drop(3).find { _.startsWith(prefix) }.map{_.replaceFirst(prefix, "")}
    def optSpecified(prefix: String) = optArg(prefix) != None
    def optInt(prefix: String, default: Int) = optArg(prefix).map(_.toInt).getOrElse(default)

It drops 3 mandatory arguments and gives out the options. Integers are specified like notorious -Xmx<size> java option, jointly with the prefix. You can parse binaries and integers as simple as

val cacheEnabled = optSpecified("cacheOff")
val memSize = optInt("-Xmx", 1000)

No need to import anything.

git: fatal: Could not read from remote repository

Make sure ssh-agent is running by executing the following command on your terminal:

eval $(ssh-agent -s)

Source: Github documentation

From an array of objects, extract value of a property as array

Easily extracting multiple properties from array of objects:

let arrayOfObjects = [
  {id:1, name:'one', desc:'something'},
  {id:2, name:'two', desc:'something else'}

//below will extract just the id and name
let result ={id, name}) => ({id, name}));

result will be [{id:1, name:'one'},{id:2, name:'two'}]

Add or remove properties as needed in the map function

Fastest way to check if a string matches a regexp in ruby?

To complete Wiktor Stribizew and Dougui answers I would say that /regex/.match?("string") about as fast as "string".match?(/regex/).

Ruby 2.4.0 (10 000 000 ~2 sec)

2.4.0 > require 'benchmark'
 => true 
2.4.0 > Benchmark.measure{ 10000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
 => #<Benchmark::Tms:0x005563da1b1c80 @label="", @real=2.2060338060000504, @cstime=0.0, @cutime=0.0, @stime=0.04000000000000001, @utime=2.17, @total=2.21> 
2.4.0 > Benchmark.measure{ 10000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
 => #<Benchmark::Tms:0x005563da139eb0 @label="", @real=2.260814556000696, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=2.2500000000000004, @total=2.2600000000000007> 

Ruby 2.6.2 (100 000 000 ~20 sec)

irb(main):001:0> require 'benchmark'
=> true
irb(main):005:0> Benchmark.measure{ 100000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
=> #<Benchmark::Tms:0x0000562bc83e3768 @label="", @real=24.60139879199778, @cstime=0.0, @cutime=0.0, @stime=0.010000999999999996, @utime=24.565644999999996, @total=24.575645999999995>
irb(main):004:0> Benchmark.measure{ 100000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
=> #<Benchmark::Tms:0x0000562bc846aee8 @label="", @real=24.634255946999474, @cstime=0.0, @cutime=0.0, @stime=0.010046, @utime=24.598276, @total=24.608321999999998>

Note: times varies, sometimes /regex/.match?("string") is faster and sometimes "string".match?(/regex/), the differences maybe only due to the machine activity.

OpenSSL: unable to verify the first certificate for Experian URL

I came across the same issue installing my signed certificate on an Amazon Elastic Load Balancer instance.

All seemed find via a browser (Chrome) but accessing the site via my java client produced the exception

What I had not done was provide a "certificate chain" file when installing my certificate on my ELB instance (see

We were only sent our signed public key from the signing authority so I had to create my own certificate chain file. Using my browser's certificate viewer panel I exported each certificate in the signing chain. (The order of the certificate chain in important, see

htaccess <Directory> deny from all

You can use from root directory:

RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html


RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');

How to sort a List<Object> alphabetically using Object name field

I found another way to do the type.

if(listAxu.size() > 0){
    Collections.sort(listAxu, Comparator.comparing(IdentityNamed::getDescricao));

Remove and Replace Printed items

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

Similar to the answer given by Abdul.

   <img src="..." class="img-responsive" width="100%" />

It works properly in FF 29, Opera 12.17, Chromium 34 and in IE9. Yes, it's a weird set of browsers!

How can I trigger a Bootstrap modal programmatically?

I wanted to do this the angular (2/4) way, here is what I did:

<div []="visible" []="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">

Important things to note:

  • visible is a variable (boolean) in the component which governs modal's visibility.
  • show and in are bootstrap classes.

An example component & html


@ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
@HostListener('document:keydown.escape', ['$event'])
  onEscapeKey(event: KeyboardEvent) {
  hideRsvpModal(event?: Event) {
    if (!event || ( as Element).classList.contains('modal')) {
      this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
      this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
      this.renderer.addClass(document.body, 'modal-open');
  showRsvpModal() {
    this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
    this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
    this.renderer.removeClass(document.body, 'modal-open');


<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="niviteRsvpModalTitle">

                <button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
            <div class="modal-body">

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary bg-white text-dark"

How to add color to Github's file

As of writing, Github Markdown renders color codes like `#ffffff` (note the backticks!) with a color preview. Just use a color code and surround it with backticks.

For example:

GitHub markdown with color codes


rendered GitHub markdown with color codes

How should I set the default proxy to use default credentials?

In my deployment I can't use app.config neither to embed what Andrew Webb suggested.
So I'm doing this:

    IWebProxy proxy = WebRequest.GetSystemWebProxy();
    proxy.Credentials = CredentialCache.DefaultCredentials;

    WebClient wc = new WebClient();
    wc.UseDefaultCredentials = true;
    wc.Proxy = proxy;

Just in case you want to check my IE settings:

enter image description here

SQL Sum Multiple rows into one

You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.

This will return the sum of bills per account number:

SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber

You could add more clauses like WHERE, ORDER BY etc as needed.

Python: Open file in zip without temporarily extracting it

In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfile
archive = zipfile.ZipFile('', 'r')
imgfile ='img_01.png')
    image = pygame.image.load(imgfile, 'img_01.png')

How to replace a whole line with sed?

Like this:

sed 's/aaa=.*/aaa=xxx/'

If you want to guarantee that the aaa= is at the start of the line, make it:

sed 's/^aaa=.*/aaa=xxx/'

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())

         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         success: function (result) {
         async: true,
         processData: false

Leave out quotes when copying from cell

  • if formula having multi line (means having line break in formula) then copy paste will work in that way
  • if can remove multi line then no quotes will appear while copy paste.
  • else use CLEAN function as said by @greg in previous answer

Using Intent in an Android application to show another activity

<activity android:name="[packagename optional].ActivityClassName"></activity>

Simply adding the activity which we want to switch to should be placed in the manifest file

JavaFX and OpenJDK

According to Oracle integration of OpenJDK & javaFX will be on Q1-2014 ( see roadmap : ). So, for the 1st question the answer is that you have to wait until then. For the 2nd question there is no other way. So, for now go with java swing or start javaFX and wait

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

Bootstrap 3 with remote Modal

Regarding the remote option for modals, from the docs:

If a remote URL is provided, content will be loaded via jQuery's load method and injected into the root of the modal element.

That means your remote file should provide the complete modal structure, not just what you want to display on the body.

Bootstrap 3.1 Update:

In v3.1 the above behavior was changed and now the remote content is loaded into .modal-content

See this Demo fiddle

Boostrap 3.3 Update:

This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.

How do I install PyCrypto on Windows?

  1. Go to "Microsoft Visual C++ Compiler for Python 2.7" and continue based on "System Requirements" (this is what I did to put below steps together).

  2. Install setuptools (setuptools 6.0 or later is required for Python to automatically detect this compiler package) either by: pip install setuptools or download "Setuptools bootstrapping installer" source from, save this file somwhere on your filestystem as "" and install with: python

  3. Install wheel (wheel is recommended for producing pre-built binary packages). You can install it with: pip install wheel

  4. Open Windows elevated Command Prompt cmd.exe (with "Run as administrator") to install "Microsoft Visual C++ Compiler for Python 2.7" for all users. You can use following command to do so: msiexec /i C:\users\jozko\download\VCForPython27.msi ALLUSERS=1 just use your own path to file: msiexec /i <path to MSI> ALLUSERS=1

  5. Now you should be able to install pycrypto with: pip install pycrypto

What is the difference between DTR/DSR and RTS/CTS flow control?

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

If else on WHERE clause

You want to use coalesce():

where coalesce(email, email2) like '%[email protected]%'

If you want to handle empty strings ('') versus NULL, a case works:

where (case when email is NULL or email = '' then email2 else email end) like '%[email protected]%'

And, if you are worried about the string really being just spaces:

where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%[email protected]%'

As an aside, the sample if statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, '[email protected]' would fail, because the string would convert as 0. As would '[email protected]'. But, '[email protected]' and '[email protected]' would succeed.

Common MySQL fields and their appropriate data types

In my experience, first name/last name fields should be at least 48 characters -- there are names from some countries such as Malaysia or India that are very long in their full form.

Phone numbers and postcodes you should always treat as text, not numbers. The normal reason given is that there are postcodes that begin with 0, and in some countries, phone numbers can also begin with 0. But the real reason is that they aren't numbers -- they're identifiers that happen to be made up of numerical digits (and that's ignoring countries like Canada that have letters in their postcodes). So store them in a text field.

In MySQL you can use VARCHAR fields for this type of information. Whilst it sounds lazy, it means you don't have to be too concerned about the right minimum size.

How can I dynamically add a directive in AngularJS?

Dynamically adding directives on angularjs has two styles:

Add an angularjs directive into another directive

  • inserting a new element(directive)
  • inserting a new attribute(directive) to element

inserting a new element(directive)

it's simple. And u can use in "link" or "compile".

var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
$element.parent().append( newElement );

inserting a new attribute to element

It's hard, and make me headache within two days.

Using "$compile" will raise critical recursive error!! Maybe it should ignore the current directive when re-compiling element.

$element.$set("myDirective", "expression");
var newElement = $compile( $element )( $scope ); // critical recursive error.
var newElement = angular.copy(element);          // the same error too.
$element.replaceWith( newElement );

So, I have to find a way to call the directive "link" function. It's very hard to get the useful methods which are hidden deeply inside closures.

compile: (tElement, tAttrs, transclude) ->
   links = []
   myDirectiveLink = $injector.get('myDirective'+'Directive')[0] #this is the way
   links.push myDirectiveLink
   myAnotherDirectiveLink = ($scope, $element, attrs) ->
   links.push myAnotherDirectiveLink
   return (scope, elm, attrs, ctrl) ->
       for link in links
           link(scope, elm, attrs, ctrl)       

Now, It's work well.

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());'/myaction', function(req, res) {
  res.send('You sent the name "' + + '".');

app.listen(8080, function() {
  console.log('Server running at');

You can make your form point to it using:

<form action="" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

How can I get log4j to delete old rotating log files?

Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:

<param name="MaxBackupIndex" value="20"/>

The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.

Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)

log4j.appender.[appenderName].MaxBackupIndex = 15

How to set DialogFragment's width and height?

I don't see a compelling reason to override onResume or onStart to set the width and height of the Window within DialogFragment's Dialog -- these particular lifecycle methods can get called repeatedly and unnecessarily execute that resizing code more than once due to things like multi window switching, backgrounding then foregrounding the app, and so on. The consequences of that repetition are fairly trivial, but why settle for that?

Setting the width/height instead within an overridden onActivityCreated() method will be an improvement because this method realistically only gets called once per instance of your DialogFragment. For example:

public void onActivityCreated(Bundle savedInstanceState) {

    Window window = getDialog().getWindow();
    assert window != null;

    WindowManager.LayoutParams layoutParams = window.getAttributes();
    layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;

Above I just set the width to be match_parent irrespective of device orientation. If you want your landscape dialog to not be so wide, you can do a check of whether getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT beforehand.

Team Build Error: The Path ... is already mapped to workspace

Use the command line utility TF - Team Foundation Version Control Tool (tf).

You can get a list of all workspaces by bringing up a Visual Studio Command Prompt then changing to your workspace folder and issuing the following commands:

C:\YourWorkspaceFolder>tf workspaces /owner:*

You should see your problem workspace in the list as well as it's owner.

You can delete the workspace with the following command:

C:\YourWorkspaceFolder>tf workspace /delete /server:BUILDSERVER WORKSPACENAME;OWNERNAME

How do I set a cookie on HttpClient's HttpRequestMessage

Here's how you could set a custom cookie value for the request:

var baseAddress = new Uri("");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
    var content = new FormUrlEncodedContent(new[]
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = await client.PostAsync("/test", content);

Adding gif image in an ImageView in android

Based on Ahmad Dwaik 'Warlock's comment, I have tried the following code and it worked.

  1. Use a webview in your xml file, and adjust its position to the place where exactly you were trying to show you .gif image.
  2. In your activity initialise this small piece of webview like other views.
  3. place the .gif image in assets folder
  4. now load the image as if you are loading a url into webview like "diyaWebView1.loadUrl("file:///android_asset/www/diya.gif");"
  5. you can see your .gif image when you launch the application.

P.S : this things works if you .gif image fits your webview or viceversa else if the image is bigger than the webview the scrollbar gets enabled and user can scroll the image AKA webview. So we need to be careful when we use this, to give proper size to the webview as per image or edit the image that fits your webview.

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

How to Access Hive via Python?

You could use python JayDeBeApi package to create DB-API connection from Hive or Impala JDBC driver and then pass the connection to pandas.read_sql function to return data in pandas dataframe.

import jaydebeapi
# Apparently need to load the jar files for the first time for impala jdbc driver to work 
conn = jaydebeapi.connect('com.cloudera.hive.jdbc41.HS2Driver',
['jdbc:hive2://host:10000/db;AuthMech=1;;KrbServiceName=hive;KrbRealm=xxx.COM', "",""],
jars=['/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/HiveJDBC41.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/TCLIServiceClient.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-codec-1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_metastore.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_service.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/log4j-1.2.14.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/ql.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/zookeeper-3.4.6.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/ImpalaJDBC41.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/TCLIServiceClient.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/commons-codec-1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/hive_metastore.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/hive_service.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/log4j-1.2.14.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/ql.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/zookeeper-3.4.6.jar'

# the previous call have initialized the jar files, technically this call needs not include the required jar files
impala_conn = jaydebeapi.connect('com.cloudera.impala.jdbc41.Driver',
jars=['/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/HiveJDBC41.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/TCLIServiceClient.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-codec-1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_metastore.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_service.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/log4j-1.2.14.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/ql.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/ GA/Cloudera_HiveJDBC41_2.5.18.1050/zookeeper-3.4.6.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/ImpalaJDBC41.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/TCLIServiceClient.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/commons-codec-1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/hive_metastore.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/hive_service.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/log4j-1.2.14.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/ql.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/ GA/Cloudera_ImpalaJDBC41_2.5.35/zookeeper-3.4.6.jar'

import pandas as pd
df1 = pd.read_sql("SELECT * FROM tablename", conn)
df2 = pd.read_sql("SELECT * FROM tablename", impala_conn)


C# version of java's synchronized keyword?

First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).

For the method-level stuff, there is [MethodImpl]:

public void SomeMethod() {/* code */}

This can also be used on accessors (properties and events):

private int i;
public int SomeProperty
    get { return i; }
    set { i = value; }

Note that field-like events are synchronized by default, while auto-implemented properties are not:

public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized

Personally, I don't like the implementation of MethodImpl as it locks this or typeof(Foo) - which is against best practice. The preferred option is to use your own locks:

private readonly object syncLock = new object();
public void SomeMethod() {
    lock(syncLock) { /* code */ }

Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this) / lock(Type) - however, in more recent compilers it uses Interlocked updates - so thread-safe without the nasty parts.

This allows more granular usage, and allows use of Monitor.Wait/Monitor.Pulse etc to communicate between threads.

A related blog entry (later revisited).

Using jQuery to programmatically click an <a> link

Try this:


It works for me.

Inner Joining three tables

try the following code

select * from TableA A 
inner join TableB B on A.Column=B.Column 
inner join TableC C on A.Column=C.Column

Add CSS to <head> with JavaScript?

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  # other stuff..

This way you avoid firing an extra HTTP request.

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!

How do I run pip on python for windows?

First go to the pip documentation if not install before:

and follow the install pip which is first download from

Then run the following (which may require administrator access): python

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

HTML event handler code behaves like the body of a JavaScript function. Many languages such as C or Perl implicitly return the value of the last expression evaluated in the function body. JavaScript doesn't, it discards it and returns undefined unless you write an explicit returnEXPR.

How to clear textarea on click?

The best solution what I know so far:

<textarea name="message" onblur="if (this.value == '') {this.value = 'text here';}"   onfocus="if (this.value == 'text here') {this.value = '';}">text here</textarea>

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

Get time of specific timezone

before you get too excited this was written in 2011

if I were to do this these days I would use Intl.DateTimeFormat. Here is a link to give you an idea of what type of support this had in 2011

original answer now (very) outdated


The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.

For example, If your time zone is GMT+2, -120 will be returned.

Note: This method is always used in conjunction with a Date object.

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11

Java - How do I make a String array with values?

Another way is with Arrays.setAll, or Arrays.fill:

String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]

Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]

This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.

What is the simplest way to convert array to vector?

Pointers can be used like any other iterators:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

It may be obvious, but it still was surprising to me, that SET NAMES utf8 is not compatible with utf8mb4 encoding. So for some apps changing table/column encoding was not enough. I had to change encoding in app configuration.

Redmine (ruby, ROR)

In config/database.yml:

  adapter: mysql2
  database: redmine
  host: localhost
  username: redmine
  password: passowrd
  encoding: utf8mb4

Custom Yii application (PHP)

In config/db.php:

return [
    'class' => yii\db\Connection::class,
    'dsn' => 'mysql:host=localhost;dbname=yii',
    'username' => 'yii',
    'password' => 'password',
    'charset' => 'utf8mb4',

If you have utf8mb4 as a column/table encoding and still getting errors like this, make sure that you have configured correct charset for DB connection in your application.

What are the differences between Mustache.js and Handlebars.js?

One more subtle difference is the treatment of falsy values in {{#property}}...{{/property}} blocks. Most mustache implementations will just obey JS falsiness here, not rendering the block if property is '' or '0'.

Handlebars will render the block for '' and 0, but not other falsy values. This can cause some trouble when migrating templates.

How can we draw a vertical line in the webpage?

<hr> is not from struts. It is just an HTML tag.

So, take a look here: This link will give you a couple of tips.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

My IIS 7.5 does not understand tag in web.config In VS 2010 it is underline that tag also. Check your config file accurate to find all underlined tags. I put it in the comment and error goes away.

Replace multiple strings with multiple other strings

by using prototype function we can replace easily by passing object with keys and values and replacable text

 const keys=keydata.split('key');
 return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)

const data='hids dv sdc sd ${yathin} ${ok}'

AngularJS $watch window resize inside directive

You shouldn't need a $watch. Just bind to resize event on window:


'use strict';

var app = angular.module('plunker', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){

         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular



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

artejera, do you mean Selenium as plugin to your browser (Selenium IDE)? Here is something for automation in Google Chrome.

But if you want to work with Selenium RC, just set up browser in your test script. There is setBrowser() method in Selenium.

Can't install gems on OS X "El Capitan"

Looks like when upgrading to OS X El Capitain, the /usr/local directory is modified in multiple ways :

  1. user permissions are reset (this is also a problem for people using Homebrew)
  2. binaries and symlinks might have been deleted or altered

[Edit] There's also a preliminary thing to do : upgrade Xcode...

Solution for #1 :

$ sudo chown -R $(whoami):admin /usr/local

This will fix permissions on the /usr/local directory which will then help both gem install and brew install|link|... commands working properly.

Solution to #2 :

Ruby based issues

Make sure you have fixed the permissions of the /usr/local directory (see #1 above)

First try to reinstall your gem using :

sudo gem install <gemname>

Note that it will install the latest version of the specified gem.

If you don't want to face backward-compatibility issues, I suggest that you first determine which version of which gem you want to get and then reinstall it with the -v version. See an exemple below to make sure that the system won't get a new version of capistrano.

$ gem list | grep capistrano
capistrano (3.4.0, 3.2.1, 2.14.2)
$ sudo gem install capistrano -v 3.4.0

Brew based issues

Update brew and upgrade your formulas

$ brew update
$ brew upgrade

You might also need to re-link some of them manually

$ brew link <formula>

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href=""><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href=""/><![endif]--><!-- Internet Explorer-->

Creating a LinkedList class from scratch

If you're actually building a real system, then yes, you'd typically just use the stuff in the standard library if what you need is available there. That said, don't think of this as a pointless exercise. It's good to understand how things work, and understanding linked lists is an important step towards understanding more complex data structures, many of which don't exist in the standard libraries.

There are some differences between the way you're creating a linked list and the way the Java collections API does it. The Collections API is trying to adhere to a more complicated interface. The Collections API linked list is also a doubly linked list, while you're building a singly linked list. What you're doing is more appropriate for a class assignment.

With your LinkedList class, an instance will always be a list of at least one element. With this kind of setup you'd use null for when you need an empty list.

Think of next as being "the rest of the list". In fact, many similar implementations use the name "tail" instead of "next".

Here's a diagram of a LinkedList containing 3 elements:

linked list diagram

Note that it's a LinkedList object pointing to a word ("Hello") and a list of 2 elements. The list of 2 elements has a word ("Stack") and a list of 1 element. That list of 1 element has a word ("Overflow") and an empty list (null). So you can treat next as just another list that happens to be one element shorter.

You may want to add another constructor that just takes a String, and sets next to null. This would be for creating a 1-element list.

To append, you check if next is null. If it is, create a new one element list and set next to that.

next = new LinkedList(word);

If next isn't null, then append to next instead.


This is the recursive approach, which is the least amount of code. You can turn that into an iterative solution which would be more efficient in Java*, and wouldn't risk a stack overflow with very long lists, but I'm guessing that level of complexity isn't needed for your assignment.

* Some languages have tail call elimination, which is an optimization that lets the language implementation convert "tail calls" (a call to another function as the very last step before returning) into (effectively) a "goto". This makes such code completely avoid using the stack, which makes it safer (you can't overflow the stack if you don't use the stack) and typically more efficient. Scheme is probably the most well known example of a language with this feature.

CSS hide scroll bar if not needed

.container {overflow:auto;} will do the trick. If you want to control specific direction, you should set auto for that specific axis. A.E.

.container {overflow-y:auto;} .container {overflow-x:hidden;}

The above code will hide any overflow in the x-axis and generate a scroll-bar when needed on the y-axis.But you have to make sure that you content default height smaller than the container height; if not, the scroll-bar will not be hidden.

Use jQuery to scroll to the bottom of a div with lots of text

jQuery simple solution, one line, no external lib required :

$("#myDivID").animate({ scrollTop: $('#myDivID')[0].scrollHeight }, 1000);

Change 1000 to another value (this is the duration of the animation).

"Could not find or load main class" Error while running java program using cmd prompt

Create a folder org/tij/exercises and then move file. Then run below command

javac -cp . org/tij/exercises/


java -cp . org/tij/exercises/HelloWorld

How to find Max Date in List<Object>?

A small improvement from the accepted answer is to do the null check and also get full object.

public class DateComparator {

public static void main(String[] args) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
    employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
    employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
    employees.add(new Employee(4, "name4", null));
    employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
    employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
    Date maxDate = -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
    //Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = -> emp.getJoiningDate() != null).max(comparator).get();
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

    Employee minDatedEmployee = -> emp.getJoiningDate() != null).min(comparator).get();
    System.out.println(" minDatedEmployee : " + minDatedEmployee);


public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, days); // minus number would decrement the days
    return cal.getTime();

You would get below results :

 [Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
 maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]

 minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]

Update : What if list itself is empty ?

        Date maxDate = -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = -> emp.getJoiningDate() != null).max(comparator).orElse(null);
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

AppCompat v7 r21 returning error in values.xml?

Make sure the value for target (which tells the target android version) in file of both your project folder and appcompat_v7 folder is same (preferably the latest).

: inside 'your_project'/

target=android-21 android.library.reference.1=../appcompat_v7


: inside appcompat_v7/

target=android-21 android.library=true

and after this don't forget to clean your project .

applying css to specific li class

You are defining the color: #C1C1C1; for all the a elements with #sub-nav-container a.

Doing it again in li.sub-navigation-home-news won't do anything, as it is a parent of the a element.

BOOLEAN or TINYINT confusion

The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.

See here:

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Since I can not add a comment to the marked answer I will just post this here.

In addition to the correct answer you can indeed have this validated. Since this meta tag is only directed for IE all you need to do is add a IE conditional.

<!--[if IE]>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">

Doing this is just like adding any other IE conditional statement and only works for IE and no other browsers will be affected.

What is NODE_ENV and how to use it in Express?

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV is set to production or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  throw new Error('TestError');

app.use(function (req, res, next) {

Note that the latter app.use() must be last, after all other method handlers!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express). If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.

In Linux, set the environment variable NODE_ENV like this:

export NODE_ENV='value'

How to append multiple values to a list in Python

You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

So you can use list.append() to append a single value, and list.extend() to append multiple values.

"unrecognized selector sent to instance" error in Objective-C

For me, it was a leftover connection created in interfacebuilder bij ctrl-dragging. The name of the broken connection was in the error-log

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[NameOfYourApp.NameOfYourClass nameOfCorruptConnection:]:
unrecognized selector sent to instance 0x7f97a48bb000'

I had an action linked to a button. Pressing the button crashed the app because the Outlet no longer existed in my code. Searching for the name in the log led me to it in the storyboard. Deleted it, and the crash was gone!

WAMP Server doesn't load localhost

I faced a similar problem. I tried everything with ports, hosts and config files.But nothing helped.

I checked apache error logs. They showed the following error

(OS 10038)An operation was attempted on something that is not a socket.  : AH00332: winnt_accept: getsockname error on listening socket, is IPv6 available?

Finally this is what solved my problem.

1) Goto command prompt and run it in administrative mode. In windows 7 you can do it by typing cmd in run and then pressing ctrl+shift+enter

2) run the following command: netsh winsock reset

3) Restart the system

pandas read_csv and filter columns with usecols

If your csv file contains extra data, columns can be deleted from the DataFrame after import.

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x

df = pd.read_csv(StringIO(csv),
        index_col=["date", "loc"], 
        usecols=["dummy", "date", "loc", "x"],
        names=["dummy", "date", "loc", "x"])
del df['dummy']

Which gives us:

date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

How can I count the number of characters in a Bash variable

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Couting characters, words, lenght of the words and total lenght in a sentence

Exclude property from type

For versions of TypeScript at or above 3.5

In TypeScript 3.5, the Omit type was added to the standard library. See examples below for how to use it.

For versions of TypeScript below 3.5

In TypeScript 2.8, the Exclude type was added to the standard library, which allows an omission type to be written simply as:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

For versions of TypeScript below 2.8

You cannot use the Exclude type in versions below 2.8, but you can create a replacement for it in order to use the same sort of definition as above. However, this replacement will only work for string types, so it is not as powerful as Exclude.

// Functionally the same as Exclude, but for strings only.
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>

And an example of that type in use:

interface Test {
    a: string;
    b: number;
    c: boolean;

// Omit a single property:
type OmitA = Omit<Test, "a">; // Equivalent to: {b: number, c: boolean}

// Or, to omit multiple properties:
type OmitAB = Omit<Test, "a"|"b">; // Equivalent to: {c: boolean}

X close button only using css

As a pure CSS solution for the close or 'times' symbol you can use the ISO code with the content property. I often use this for :after or :before pseudo selectors.

The content code is \00d7.


  display: inline-block;
  content: "\00d7"; /* This will render the 'X' */

You can then style and position the pseudo selector in any way you want. Hope this helps someone :).

Do C# Timers elapse on a separate thread?

If the elapsed event takes longer then the interval, it will create another thread to raise the elapsed event. But there is a workaround for this

static void timer_Elapsed(object sender, ElapsedEventArgs e)    

How to enable scrolling of content inside a modal?

I had the same issue, and found a fix as below:

$('.yourModalClassOr#ID').on('', function (e) {
    $(' yourModalClassOr#ID ').css("max-height", $(window).height());
    $(' yourModalClassOr#ID ').css("overflow-y", "scroll");          /*Important*/
    $(' yourModalClassOr#ID ').modal('handleUpdate');


100% working.

How to add to an NSDictionary

By setting you'd use setValue:(id)value forKey:(id)key method of NSMutableDictionary object:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[NSNumber numberWithInt:5] forKey:@"age"];

Or in modern Objective-C:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"age"] = @5;

The difference between mutable and "normal" is, well, mutability. I.e. you can alter the contents of NSMutableDictionary (and NSMutableArray) while you can't do that with "normal" NSDictionary and NSArray

Can I run CUDA on Intel's integrated graphics processor?

At the present time, Intel graphics chips do not support CUDA. It is possible that, in the nearest future, these chips will support OpenCL (which is a standard that is very similar to CUDA), but this is not guaranteed and their current drivers do not support OpenCL either. (There is an Intel OpenCL SDK available, but, at the present time, it does not give you access to the GPU.)

Newest Intel processors (Sandy Bridge) have a GPU integrated into the CPU core. Your processor may be a previous-generation version, in which case "Intel(HD) graphics" is an independent chip.

Binding IIS Express to an IP Address

I think you can.

To do this you need to edit applicationhost.config file manually (edit bindingInformation '<ip-address>:<port>:<host-name>')

To start iisexpress, you need administrator privileges

How to get a json string from url?

Use the WebClient class in System.Net:

var json = new WebClient().DownloadString("url");

Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:

using (WebClient wc = new WebClient())
   var json = wc.DownloadString("url");