Programs & Examples On #Oracle sqldeveloper

Oracle SQL Developer is a free and fully supported graphical tool for database development.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

I found this error occurred when I was using the wrong version of Java. When I changed my environment from Java 7 down to Java 6 the error no longer appeared.

(The MSVCR71.DLL file is in the JDK 6 bin directory, where JDK 7 has MSVCR100.DLL.)

Oracle TNS names not showing when adding new connection to SQL Developer

None of the above changes made any difference in my case. I could run TNS_PING in the command window but SQL Developer couldn't figure out where tnsnames.ora was.

The issue in my case (Windows 7 - 64 bit - Enterprise ) was that the Oracle installer pointed the Start menu shortcut to the wrong version of SQL Developer. There appear to be three SQL Developer instances that accompany the installer. One is in %ORACLE_HOME%\client_1\sqldeveloper\ and two are in %ORACLE_HOME%\client_1\sqldeveloper\bin\ .

The installer installed a start menu shortcut that pointed at a version in the bin directory that simply did not function. It would ask for a password every time I started SQL Developer, not remember choices I had made and displayed a blank list when I chose TNS as the connection mechanism. It also does not have the TNS Directory field in the Database advanced settings referenced in other posts.

I tossed the old Start shortcut and installed a shortcut to %ORACLE_HOME%\client_1\sqldeveloper\sqldeveloper.exe . That change fixed the problem in my case.

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

The process of generating Entity-Relationship diagram in Oracle SQL Developer has been described in Oracle Magazine by Jeff Smith (link).

Excerpt:

Entity relationship diagram

Entity relationship diagram

Getting Started

To work through the example, you need an Oracle Database instance with the sample HR schema that’s available in the default database installation. You also need version 4.0 of Oracle SQL Developer, in which you access Oracle SQL Developer Data Modeler through the Data Modeler submenu [...] Alternatively, you can use the standalone Oracle SQL Developer Data Modeler. The modeling functionality is identical in the two implementations, and both are available as free downloads from Oracle Technology Network.

In Oracle SQL Developer, select View -> Data Modeler –> Browser. In the Browser panel, select the Relational Models node, right-click, and select New Relational Model to open a blank model diagram panel. You’re now starting at the same place as someone who’s using the standalone Oracle SQL Developer Data Modeler. Importing Your Data Dictionary

Importing Your Data Dictionary

A design in Oracle SQL Developer Data Modeler consists of one logical model and one or more relational and physical models. To begin the process of creating your design, you must import the schema information from your existing database. Select File -> Data Modeler -> Import -> Data Dictionary to open the Data Dictionary Import wizard.

Click Add to open the New -> Select Database Connection dialog box, and connect as the HR user. (For detailed information on creating a connection from Oracle SQL Developer, see “Making Database Connections,” in the May/June 2008 issue of Oracle Magazine.)

Select your connection, and click Next. You see a list of schemas from which you can import. Type HR in the Filter box to narrow the selection list. Select the checkbox next to HR, and click Next.

Read more...

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

In addition to Tony's answer, if you are looking to find out where your PL/SQL program is spending it's time, it is also worth checking out this part of the Oracle PL/SQL documentation.

Creating a new database and new connection in Oracle SQL Developer

Open Oracle SQLDeveloper

Right click on connection tab and select new connection

Enter HR_ORCL in connection name and HR for the username and password.

Specify localhost for your Hostname and enter ORCL for the SID.

Click Test.

The status of the connection Test Successfully.

The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.

The connection is saved and you see the connection list.

Directly export a query to CSV using SQL Developer

Click in the grid so it has focus.

Ctrl+End

This will force the rest of the records back into the grid.

All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/

Oracle SQL Developer: Unable to find a JVM

This is known to happen even if there are some syntactical errors in your heap space setting in the sqldeveloper.conf. If you have defined the heap space in any of the wrong ways mentioned here, it still will show the same error when you launch it.

EDIT : The correct way to set your heap size parameters would be something like this:

AddVMOption -XX:MaxPermSize=256M
AddVMOption -Xms256M
AddVMOption -Xmx768M

Print text in Oracle SQL Developer SQL Worksheet window

For me, I could only get it to work with

set serveroutput on format word_wrapped;

The wraped and WRAPPED just threw errors: SQLPLUS command failed - not enough arguments

Insert if not exists Oracle

INSERT INTO schema.myFoo ( primary_key        , value1          , value2         )
                         SELECT 'bar1' AS primary_key ,'baz1' AS value1 ,'bat1' AS value2 FROM DUAL WHERE (SELECT 1 AS value FROM schema.myFoo WHERE LOWER(primary_key) ='bar1' AND ROWNUM=1) is null;

Extract number from string with Oracle function

You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:

select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;

which will return "12345569".

also you can use this one:

select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
       regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual

which will return "12345569" for numbers and "StackOverFlow" for characters.

How to enter special characters like "&" in oracle database?

There are 3 ways to do so :

1) Simply do SET DEFINE OFF; and then execute the insert stmt.

2) Simply by concatenating reserved word within single quotes and concatenating it. E.g. Select 'Java_22 ' || '& '|| ':' || ' Oracle_14' from dual --(:) is an optional.

3) By using CHR function along with concatenation. E.g. Select 'Java_22 ' || chr(38)||' Oracle_14' from dual

Hope this help !!!

How can I set a custom date time format in Oracle SQL Developer?

When i copied the date format for timestamp and used that for date, it did not work. But changing the date format to this (DD-MON-YY HH12:MI:SS AM) worked for me.

The change has to be made in Tools->Preferences-> search for NLS

How to run .sql file in Oracle SQL developer tool to import database?

You can use Load function

Load TableName fullfilepath; 

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.:

declare
  myname varchar2(20) := 'tom';
begin
  for result_cursor in (select * from mytable where first_name = myname) loop
    dbms_output.put_line(result_cursor.first_name);
    dbms_output.put_line(result_cursor.other_field);
  end loop;
end;

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

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

Vendor code 17002 to connect to SQLDeveloper

I encountered same problem with ORACLE 11G express on Windows. After a long time waiting I got the same error message.

My solution is to make sure the hostname in tnsnames.ora (usually it's not "localhost") and the default hostname in sql developer(usually it's "localhost") same. You can either do this by changing it in the tnsnames.ora, or filling up the same in the sql developer.

Oh, of course you need to reboot all the oracle services (just to be safe).

Hope it helps.


I came across the similar problem again on another machine, but this time above solution doesn't work. After some trying, I found restarting all the oracle related services can fix the problem. Originally when the installation is done, connection can be made. Somehow after several reboot of computer, there is problem. I change all the oracle services with start time as auto. And once I could not connect, I restart them all over again (the core service should be restarted at last order), and works fine.

Some article says it might be due to the MTS problem. Microsoft's problem. Maybe!

How copy data from Excel to a table using Oracle SQL Developer

Click on "Tables" in "Connections" window, choose "Import data ...", follow the wizard and you will be asked for name for new table.

Printing the value of a variable in SQL Developer

DECLARE

  CTABLE USER_OBJECTS.OBJECT_NAME%TYPE;
  CCOLUMN ALL_TAB_COLS.COLUMN_NAME%TYPE;
  V_ALL_COLS VARCHAR2(5000);

  CURSOR CURSOR_TABLE
    IS
    SELECT OBJECT_NAME 
    FROM USER_OBJECTS 
    WHERE OBJECT_TYPE='TABLE'
    AND OBJECT_NAME LIKE 'STG%';

  CURSOR CURSOR_COLUMNS (V_TABLE_NAME IN VARCHAR2)
    IS
    SELECT COLUMN_NAME
    FROM ALL_TAB_COLS
    WHERE TABLE_NAME = V_TABLE_NAME;

BEGIN

  OPEN CURSOR_TABLE;
  LOOP
    FETCH CURSOR_TABLE INTO CTABLE;

    OPEN CURSOR_COLUMNS (CTABLE);
    V_ALL_COLS := NULL;
    LOOP

      FETCH CURSOR_COLUMNS INTO CCOLUMN;
      V_ALL_COLS := V_ALL_COLS || CCOLUMN;
      IF CURSOR_COLUMNS%FOUND THEN
        V_ALL_COLS := V_ALL_COLS || ', ';
      ELSE
        EXIT;
      END IF;
    END LOOP;
   close CURSOR_COLUMNS ;
    DBMS_OUTPUT.PUT_LINE(V_ALL_COLS);
    EXIT WHEN CURSOR_TABLE%NOTFOUND;
  END LOOP;`enter code here`
  CLOSE CURSOR_TABLE;

END;

I have added Close of second cursor. It working and getting output as well...

How to create a new database after initally installing oracle database 11g Express Edition?

This link: Creating the Sample Database in Oracle 11g Release 2 is a good example of creating a sample database.

This link: Newbie Guide to Oracle 11g Database Common Problems should help you if you come across some common problems creating your database.

Best of luck!

EDIT: As you are using XE, you should have a DB already created, to connect using SQL*Plus and SQL Developer etc. the info is here: Connecting to Oracle Database Express Edition and Exploring It.

Extract:

Connecting to Oracle Database XE from SQL Developer SQL Developer is a client program with which you can access Oracle Database XE. With Oracle Database XE 11g Release 2 (11.2), you must use SQL Developer version 3.0. This section assumes that SQL Developer is installed on your system, and shows how to start it and connect to Oracle Database XE. If SQL Developer is not installed on your system, see Oracle Database SQL Developer User's Guide for installation instructions.

Note:

For the following procedure: The first time you start SQL Developer on your system, you must provide the full path to java.exe in step 1.

For step 4, you need a user name and password.

For step 6, you need a host name and port.

To connect to Oracle Database XE from SQL Developer:

Start SQL Developer.

For instructions, see Oracle Database SQL Developer User's Guide.

If this is the first time you have started SQL Developer on your system, you are prompted to enter the full path to java.exe (for example, C:\jdk1.5.0\bin\java.exe). Either type the full path after the prompt or browse to it, and then press the key Enter.

The Oracle SQL Developer window opens.

In the navigation frame of the window, click Connections.

The Connections pane appears.

In the Connections pane, click the icon New Connection.

The New/Select Database Connection window opens.

In the New/Select Database Connection window, type the appropriate values in the fields Connection Name, Username, and Password.

For security, the password characters that you type appear as asterisks.

Near the Password field is the check box Save Password. By default, it is deselected. Oracle recommends accepting the default.

In the New/Select Database Connection window, click the tab Oracle.

The Oracle pane appears.

In the Oracle pane:

For Connection Type, accept the default (Basic).

For Role, accept the default.

In the fields Hostname and Port, either accept the defaults or type the appropriate values.

Select the option SID.

In the SID field, type accept the default (xe).

In the New/Select Database Connection window, click the button Test.

The connection is tested. If the connection succeeds, the Status indicator changes from blank to Success.

Description of the illustration success.gif

If the test succeeded, click the button Connect.

The New/Select Database Connection window closes. The Connections pane shows the connection whose name you entered in the Connection Name field in step 4.

You are in the SQL Developer environment.

To exit SQL Developer, select Exit from the File menu.

How to Execute SQL Server Stored Procedure in SQL Developer?

EXEC proc_name @paramValue1 = 0, @paramValue2 = 'some text';
GO

If the Stored Procedure objective is to perform an INSERT on a table that has an Identity field declared, then the field, in this scenario @paramValue1, should be declared and just pass the value 0, because it will be auto-increment.

Where to get this Java.exe file for a SQL Developer installation

If you don't want to install Java or you just want to get started writing queries quickly, then use SQL*Plus, which is the command line too.

It's not pretty, but will get you started quickly and there is Oracle documentation on it.

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

Oracle SQL Developer - tables cannot be seen

Launch SQL Developer as administrator

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

Spool Command: Do not output SQL statement to file

Exec the query in TOAD or SQL DEVELOPER

---select /*csv*/ username, user_id, created from all_users;

Save in .SQL format in "C" drive

--- x.sql

execute command

---- set serveroutput on
     spool y.csv
     @c:\x.sql
     spool off;

Oracle SQL Developer and PostgreSQL

Oracle SQL Developer 4.0.1.14 surely does support connections to PostgreSQL.

Edit:

If you have different user name and database name, one should specify in hostname: hostname/database? (do not forget ?) or hostname:port/database?.

(thanks to @kinkajou and @Kloe2378231; more details on https://stackoverflow.com/a/28671213/565525).

NLS_NUMERIC_CHARACTERS setting for decimal

You can see your current session settings by querying nls_session_parameters:

select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';

VALUE                                  
----------------------------------------
.,                                       

That may differ from the database defaults, which you can see in nls_database_parameters.

In this session your query errors:

select to_number('100,12') from dual;

Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 -  "invalid number"

I could alter my session, either directly with alter session or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):

alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;

TO_NUMBER('100,12')
-------------------
             100,12 

In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.

But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number(); though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:

alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;

TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
                                                        100.12 

By default the result is still displayed with my session settings, so the decimal separator is still a period.

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

How do you connect to a MySQL database using Oracle SQL Developer?

Although @BrianHart 's answer is correct, if you are connecting from a remote host, you'll also need to allow remote hosts to connect to the MySQL/MariaDB database.

My article describes the full instructions to connect to a MySQL/MariaDB database in Oracle SQL Developer:

https://alvinbunk.wordpress.com/2017/06/29/using-oracle-sql-developer-to-connect-to-mysqlmariadb-databases/

Use tnsnames.ora in Oracle SQL Developer

  • In SQLDeveloper browse Tools --> Preferences, as shown in below image.

    SQLDeveloper access preferences

  • In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
  • Then click on Ok, as shown in below diagram.
    tnsnames.ora available at Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN

    SQLDeveloper update tnsnames directory

Now you can connect via the TNSnames options.

How to Query Database Name in Oracle SQL Developer?

DESCRIBE DATABASE NAME; you need to specify the name of the database and the results will include the data type of each attribute.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I had this error because of some typo in an alias of a column that contained a questionmark (e.g. contract.reference as contract?ref)

How to export query result to csv in Oracle SQL Developer?

Version I am using

alt text

Update 5th May 2012

Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:

Method 1

Add the comment /*csv*/ to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)

enter image description here

That's it.

Method 2

Run a query

alt text

Right click and select unload.

Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out

alt text

Revised screen shot for SQL Developer Version 3.0.04

enter image description here

From the format drop down select CSV

alt text

And follow the rest of the on screen instructions.

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.

enter image description here

So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.

In the below picture I highlighted the input boxes that I've modified: enter image description here

CLEAR SCREEN - Oracle SQL Developer shortcut?

To clear the SQL window you can use:

clear screen;

which can also be shortened to

cl scr;

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

how to set auto increment column with sql developer

Unfortunately oracle doesnot support auto_increment like mysql does. You need to put a little extra effort to get that.

say this is your table -

CREATE TABLE MYTABLE (
  ID NUMBER NOT NULL,
  NAME VARCHAR2(100)
  CONSTRAINT "PK1" PRIMARY KEY (ID)
);

You will need to create a sequence -

CREATE SEQUENCE S_MYTABLE
START WITH 1
INCREMENT BY 1
CACHE 10;

and a trigger -

CREATE OR REPLACE TRIGGER T_MYTABLE_ID
BEFORE INSERT
ON MYTABLE
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
  if(:new.ID is null) then
  SELECT S_MYTABLE.nextval
  INTO :new.ID
  FROM dual;
  end if;
END;
/

ALTER TRIGGER "T_MYTABLE_ID" ENABLE;

How can I change the language (to english) in Oracle SQL Developer?

You can also configure directly on the file ..sqldeveloper\ide\bin\ide.conf:

Just add the JVM Option:

AddVMOption -Duser.language=en

The file will be like this:

enter image description here

Oracle SQL escape character (for a '&')

|| chr(38) ||

This solution is perfect.

SQL Developer is returning only the date, not the time. How do I fix this?

Well I found this way :

Oracle SQL Developer (Left top icon) > Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

enter image description here

Changing password with Oracle SQL Developer

Depending on the admin settings, you may have to specify your old password using the REPLACE option

alter user <username> identified by <newpassword> replace <oldpassword> 

Oracle SQL Developer spool output?

I was trying things to duplicate the spools you get from sqlplus. I found the following and hope it helps:

Create your sql script file ie:

Please note the echo and serveroutput.

Test_Spool.SQL

Spool 'c:\temp\Test1.txt';
set echo on;
set serveroutput on;
declare
sqlresult varchar2(60);

begin
  select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
  dbms_output.put_line('The date is ' || sqlresult);
end;

/

Spool off;
set serveroutput off;
set echo off;

Run the script from another worksheet:

@TEST_Spool.SQL

My output from the Test1.txt

set serveroutput on
declare
sqlresult varchar2(60);

begin
  select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
  dbms_output.put_line('The date is ' || sqlresult);
end;

anonymous block completed

The date is 2016-04-07 09:21:32

Spool of

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

In SQL*Plus putting SET DEFINE ? at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.

Oracle SqlDeveloper JDK path

On Windows,Close all the SQL Developer windows. Then You need to completely delete the SQL Developer and sqldeveloper folders located in user/AppData/Roaming. Finally, run the program, you will be prompted for new JDK.

Note that AppData is a hidden folder.

SQL Developer with JDK (64 bit) cannot find JVM

I had the same problem: The point here is to point on the java.exe binary under Oracle client installation and not the JDK installation under Program Files.

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

SELECT DISTINCT table_name, 
                constraint_name, 
                column_name, 
                r_table_name, 
                position, 
                constraint_type 
FROM   (SELECT uc.table_name, 
               uc.constraint_name, 
               cols.column_name, 
               (SELECT table_name 
                FROM   user_constraints 
                WHERE  constraint_name = uc.r_constraint_name) r_table_name, 
               (SELECT column_name 
                FROM   user_cons_columns 
                WHERE  constraint_name = uc.r_constraint_name 
                       AND position = cols.position)           r_column_name, 
               cols.position, 
               uc.constraint_type 
        FROM   user_constraints uc 
               inner join user_cons_columns cols 
                       ON uc.constraint_name = cols.constraint_name 
        WHERE  constraint_type != 'C') 
START WITH table_name = '&&tableName' 
           AND column_name = '&&columnName' 
CONNECT BY NOCYCLE PRIOR table_name = r_table_name 
                         AND PRIOR column_name = r_column_name; 

How to create a blank/empty column with SELECT query in oracle?

In DB2, using single quotes instead of your double quotes will work. So that could translate the same in Oracle..

SELECT CustomerName AS Customer, '' AS Contact 
FROM Customers;

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

Explicitly set column value to null SQL Developer

You'll have to write the SQL DML yourself explicitly. i.e.

UPDATE <table>
   SET <column> = NULL;

Once it has completed you'll need to commit your updates

commit;

If you only want to set certain records to NULL use a WHERE clause in your UPDATE statement.

As your original question is pretty vague I hope this covers what you want.

Run Stored Procedure in SQL Developer?

Creating Pl/SQL block can be painful if you have a lot of procedures which have a lot of parameters. There is an application written on python that do it for you. It parses the file with procedure declarations and creates the web app for convenient procedure invocations.

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

It is easy, but takes 3 steps:

  1. In SQL Developer, enter your query in the "Worksheet" and highlight it, and press F9 to run it. The first 50 rows will be fetched into the "Query Result" window.
  2. Click on any cell in the "Query Result" window to set the focus to that window.
  3. Hold the Ctrl key and tap the "A" key.

All rows will be fetched into the "Query Result" window!

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

How to export data with Oracle SQL Developer?

In SQL Developer, from the top menu choose Tools > Data Export. This launches the Data Export wizard. It's pretty straightforward from there.

There is a tutorial on the OTN site. Find it here.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

How do I change the default schema in sql developer?

Alternatively, just select 'Other Users' one of the element shows on the left hand side bottom of the current schema.

Select what ever the schema you want from the available list.

enter image description here

Understanding the results of Execute Explain Plan in Oracle SQL Developer

In recent Oracle versions the COST represent the amount of time that the optimiser expects the query to take, expressed in units of the amount of time required for a single block read.

So if a single block read takes 2ms and the cost is expressed as "250", the query could be expected to take 500ms to complete.

The optimiser calculates the cost based on the estimated number of single block and multiblock reads, and the CPU consumption of the plan. the latter can be very useful in minimising the cost by performing certain operations before others to try and avoid high CPU cost operations.

This raises the question of how the optimiser knows how long operations take. recent Oracle versions allow the collections of "system statistics", which are definitely not to be confused with statistics on tables or indexes. The system statistics are measurements of the performance of the hardware, mostly importantly:

  1. How long a single block read takes
  2. How long a multiblock read takes
  3. How large a multiblock read is (often different to the maximum possible due to table extents being smaller than the maximum, and other reasons).
  4. CPU performance

These numbers can vary greatly according to the operating environment of the system, and different sets of statistics can be stored for "daytime OLTP" operations and "nighttime batch reporting" operations, and for "end of month reporting" if you wish.

Given these sets of statistics, a given query execution plan can be evaluated for cost in different operating environments, which might promote use of full table scans at some times or index scans at others.

The cost is not perfect, but the optimiser gets better at self-monitoring with every release, and can feedback the actual cost in comparison to the estimated cost in order to make better decisions for the future. this also makes it rather more difficult to predict.

Note that the cost is not necessarily wall clock time, as parallel query operations consume a total amount of time across multiple threads.

In older versions of Oracle the cost of CPU operations was ignored, and the relative costs of single and multiblock reads were effectively fixed according to init parameters.

how to modify the size of a column

If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Count number of days between two dates

def business_days_between(date1, date2)
  business_days = 0
  date = date2
  while date > date1
   business_days = business_days + 1 unless date.saturday? or date.sunday?
   date = date - 1.day
  end
  business_days
end

What are the differences between C, C# and C++ in terms of real-world applications?

My opinion is C# and ASP.NET would be the best of the three for development that is web biased.

I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.

I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.

The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).

Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.

So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.

How to normalize an array in NumPy to a unit vector?

If you're using scikit-learn you can use sklearn.preprocessing.normalize:

import numpy as np
from sklearn.preprocessing import normalize

x = np.random.rand(1000)*10
norm1 = x / np.linalg.norm(x)
norm2 = normalize(x[:,np.newaxis], axis=0).ravel()
print np.all(norm1 == norm2)
# True

Bootstrap modal appearing under background

Like Davide Lorigliola, I fixed it by cranking up the z-index:

.modal-backdrop { z-index: -999999; }

Creating a very simple linked list

simple c# program to implement Single Link List with operations AddItemStart, AddItemEnd, RemoveItemStart, RemoveItemEnd and DisplayAllItems

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace SingleLinkedList
    {
        class Program
        {
            Node head;
            Node current;
            int counter = 0;
            public Program()
            {
                head = new Node();
                current = head;
            }
            public void AddStart(object data)
            {
                Node newnode = new Node();
                newnode.next = head.next;
                newnode.data = data;
                head.next = newnode;
                counter++;
            }
            public void AddEnd(object data)
            {
                Node newnode = new Node();
                newnode.data = data;
                current.next = newnode;
                current = newnode;
                counter++;
            }
            public void RemoveStart()
            {
                if (counter > 0)
                {
                    head.next = head.next.next;
                    counter--;
                }
                else
                {
                    Console.WriteLine("No element exist in this linked list.");
                }
            }
            public void RemoveEnd()
            {
                if (counter > 0)
                {
                    Node prevNode = new Node();
                    Node cur = head;
                    while (cur.next != null)
                    {
                        prevNode = cur;
                        cur = cur.next;
                    }
                    prevNode.next = null;
                }
                else
                {
                    Console.WriteLine("No element exist in this linked list.");
                }
            }
            public void Display()
            {
                Console.Write("Head ->");
                Node curr = head;
                while (curr.next != null)
                {
                    curr = curr.next;
                    Console.WriteLine(curr.data.ToString());
                }
            }
            public class Node
            {
                public object data;
                public Node next;
            }
            static void Main(string[] args)
            {
                Program p = new Program();
                p.AddEnd(2);
                p.AddStart(1);
                p.AddStart(0);
                p.AddEnd(3);
                p.Display();
                p.RemoveStart();
                Console.WriteLine("Removed node from Start");
                p.Display();
                Console.WriteLine("Removed node from End");
                p.RemoveEnd();
                p.Display();
                Console.ReadKey();
            }
        }
    }

Convert HttpPostedFileBase to byte[]

You can read it from the input stream:

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

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

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

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

Simplest/cleanest way to implement a singleton in JavaScript

I like to use a combination of the singleton pattern with the module pattern, and init-time branching with a Global NS check, wrapped within a closure.

In a case where the environment isn't going to change after the initialization of the singleton, the use of an immediately invoked object-literal to return a module full of utilities that will persist for some duration should be fine.

I'm not passing any dependencies, just invoking the singletons within their own little world - the only goal being to: create a utilities module for event binding / unbinding (device orientation / orientation changes could also work in this case).

window.onload = ( function( _w ) {
    console.log.apply( console, ['it', 'is', 'on'] );
    ( {
        globalNS : function() {
            var nameSpaces = ["utils", "eventUtils"],
                nsLength = nameSpaces.length,
                possibleNS = null;

            outerLoop:
            for ( var i = 0; i < nsLength; i++ ) {
                if ( !window[nameSpaces[i]] ) {
                    window[nameSpaces[i]] = this.utils;
                    break outerLoop;
                };
            };
        },
        utils : {
            addListener : null,
            removeListener : null
        },
        listenerTypes : {
            addEvent : function( el, type, fn ) {
                el.addEventListener( type, fn, false );
            },
            removeEvent : function( el, type, fn ) {
                el.removeEventListener( type, fn, false );
            },
            attachEvent : function( el, type, fn ) {
                el.attachEvent( 'on'+type, fn );
            },
            detatchEvent : function( el, type, fn ) {
                el.detachEvent( 'on'+type, fn );
            }
        },
        buildUtils : function() {
            if ( typeof window.addEventListener === 'function' ) {
                this.utils.addListener = this.listenerTypes.addEvent;
                this.utils.removeListener = this.listenerTypes.removeEvent;
            } else {
                this.utils.attachEvent = this.listenerTypes.attachEvent;
                this.utils.removeListener = this.listenerTypes.detatchEvent;
            };
            this.globalNS();
        },
        init : function() {
            this.buildUtils();
        }
    } ).init();
} ( window ) );

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

Chrome:The website uses HSTS. Network errors...this page will probably work later

One very quick way around this is, when you're viewing the "Your connection is not private" screen:

type badidea

type thisisunsafe (credit to The Java Guy for finding the new passphrase)

That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.

This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.

Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.

Edit: as of 30 Jan 2018 this passphrase appears to no longer work.

If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:

How to create a self-signed certificate with openssl?

Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.

Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea passphrase no longer works.

Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).

The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).

The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:

Wikipedia: List of Internet Top Level Domains: Special Use Domains

These top-level domains seem to be exempt from the new https-only restrictions:

  • .local
  • .localhost
  • .test
  • (any custom/non-standard top-level domain)

See the answer and link from codinghands to the original question for more information:

answer from codinghands

add column to mysql table if it does not exist

I've taken the OP's sproc and made it reusable and schema independent. Obviously it still requires MySQL 5.

DROP PROCEDURE IF EXISTS AddCol;

DELIMITER //

CREATE PROCEDURE AddCol(
    IN param_schema VARCHAR(100),
    IN param_table_name VARCHAR(100),
    IN param_column VARCHAR(100),
    IN param_column_details VARCHAR(100)
) 
BEGIN
    IF NOT EXISTS(
    SELECT NULL FROM information_schema.COLUMNS
    WHERE COLUMN_NAME=param_column AND TABLE_NAME=param_table_name AND table_schema = param_schema
    )
    THEN
        set @paramTable = param_table_name ;
        set @ParamColumn = param_column ;
        set @ParamSchema = param_schema;
        set @ParamColumnDetails = param_column_details;
        /* Create the full statement to execute */
        set @StatementToExecute = concat('ALTER TABLE `',@ParamSchema,'`.`',@paramTable,'` ADD COLUMN `',@ParamColumn,'` ',@ParamColumnDetails);
        /* Prepare and execute the statement that was built */
        prepare DynamicStatement from @StatementToExecute ;
        execute DynamicStatement ;
        /* Cleanup the prepared statement */
        deallocate prepare DynamicStatement ;

    END IF;
END //

DELIMITER ;

How to make sure docker's time syncs with that of the host?

I was facing a time offset of -1hour and 4min

Restarting Docker itself fixed the issue for me.

To set the timezone in general:

  1. ssh into your container: docker exec -it my_website_name bash

  2. run dpkg-reconfigure tzdata

  3. run date

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I am assuming you are using Eclipse as your developing environment.

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

How do I disable a Pylint warning?

I had this problem using Eclipse and solved it as follows:

In the pylint folder (e.g. C:\Python26\Lib\site-packages\pylint), hold Shift, right-click and choose to open the windows command in that folder. Type:

lint.py --generate-rcfile > standard.rc

This creates the standard.rc configuration file. Open it in Notepad and under [MESSAGES CONTROL], uncomment disable= and add the message ID's you want to disable, e.g.:

disable=W0511, C0321

Save the file, and in Eclipse ? Window ? Preferences ? PyDev ? *pylint, in the arguments box, type:

--rcfile=C:\Python26\Lib\site-packages\pylint\standard.rc

Now it should work...


You can also add a comment at the top of your code that will be interpreted by Pylint:

# pylint: disable=C0321

Pylint message codes.


Adding e.g. --disable-ids=C0321 in the arguments box does not work.

All available Pylint messages are stored in the dictionary _messages, an attribute of an instance of the pylint.utils.MessagesHandlerMixIn class. When running Pylint with the argument --disable-ids=... (at least without a configuration file), this dictionary is initially empty, raising a KeyError exception within Pylint (pylint.utils.MessagesHandlerMixIn.check_message_id().

In Eclipse, you can see this error-message in the Pylint Console (windows* ? show view ? Console, select Pylint console from the console options besides the console icon.)

Integer value comparison

To figure out if an Integer is greater than 0, you can:

  • check if compareTo(O) returns a positive number:

    if (count.compareTo(0) > 0)
         ...
    

    But that looks pretty silly, doesn't it? Better just...

  • use autoboxing1:

    if (count > 0)
        ....
    

    This is equivalent to:

    if (count.intValue() > 0)
        ...
    

    It is important to note that "==" is evaluated like this, with the Integer operand unboxed rather than the int operand boxed. Otherwise, count == 0 would return false when count was initialized as new Integer(0) (because "==" tests for reference equality).

1Technically, the first example uses autoboxing (before Java 1.5 you couldn't pass an int to compareTo) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.

How to change HTML Object element data attribute value in javascript

and in jquery:

$('element').attr('some attribute','some attributes value')

i.e

$('a').attr('href','http://www.stackoverflow.com/')

Getting Textbox value in Javascript

Since you have master page and your control is in content place holder, Your control id will be generated different in client side. you need to do like...

var TestVar = document.getElementById('<%= txt_model_code.ClientID %>').value;

Javascript runs on client side and to get value you have to provide client id of your control

Sending Multipart File as POST parameters with RestTemplate requests

One of our guys does something similar with the filesystemresource. try

mvm.add("file", new FileSystemResource(pUploadDTO.getFile())); 

assuming the output of your .getFile is a java File object, that should work the same as ours, which just has a File parameter.

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Program "make" not found in PATH

Additional hint: If you have multiple projects with different toolchains open, check the build console header for the failing project's path.

I've just spent half an hour trying to fix a build that showed this error because another project with hopelessly outdated toolchain settings was open in the same workbench. Closing the other project re-enabled the build.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

Postgresql SELECT if string contains

In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%' there are position (reversed order of args) and strpos.

SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0

Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain % and especially _ (single char wildcard), to give no false positives.

How to remove decimal values from a value of type 'double' in Java

Alternatively, you can use the method int integerValue = (int)Math.round(double a);

jQuery Event : Detect changes to the html/text of a div

Since $("#selector").bind() is deprecated, you should use:

$("body").on('DOMSubtreeModified', "#selector", function() {
    // code here
});

What are the date formats available in SimpleDateFormat class?

Date and time formats are well described below

SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns

There could be n Number of formats you can possibly make. ex - dd/MM/yyyy or YYYY-'W'ww-u or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.

  • G - Era designator (AD)
  • y - Year (1996; 96)
  • Y - Week Year (2009; 09)
  • M - Month in year (July; Jul; 07)
  • w - Week in year (27)
  • W - Week in month (2)
  • D - Day in year (189)
  • d - Day in month (10)
  • F - Day of week in month (2)
  • E - Day name in week (Tuesday; Tue)
  • u - Day number of week (1 = Monday, ..., 7 = Sunday)
  • a - AM/PM marker
  • H - Hour in day (0-23)
  • k - Hour in day (1-24)
  • K - Hour in am/pm (0-11)
  • h - Hour in am/pm (1-12)
  • m - Minute in hour (30)
  • s - Second in minute (55)
  • S - Millisecond (978)
  • z - General time zone (Pacific Standard Time; PST; GMT-08:00)
  • Z - RFC 822 time zone (-0800)
  • X - ISO 8601 time zone (-08; -0800; -08:00)

To parse:

2000-01-23T04:56:07.000+0000

Use: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

R Apply() function on specific dataframe columns

lapply is probably a better choice than apply here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.

The pattern is:

df[cols] <- lapply(df[cols], FUN)

The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:

wifi[4:9] <- lapply(wifi[4:9], A)

An example of using column names:

wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How to create a dotted <hr/> tag?

You could just have <hr style="border-top: dotted 1px;" /> . That should work.

How to read xml file contents in jQuery and display in html elements?

_x000D_
_x000D_
 $.get("/folder_name/filename.xml", function (xml) {_x000D_
 var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
 });
_x000D_
_x000D_
_x000D_

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

This did it for my case.

             <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:scaleType="centerCrop"
                android:adjustViewBounds="true"
                />

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

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

Ruby on Rails: how to render a string as HTML?

UPDATE

For security reasons, it is recommended to use sanitize instead of html_safe.

<%= sanitize @str %>

What's happening is that, as a security measure, Rails is escaping your string for you because it might have malicious code embedded in it. But if you tell Rails that your string is html_safe, it'll pass it right through.

@str = "<b>Hi</b>".html_safe
<%= @str %>

OR

@str = "<b>Hi</b>"
<%= @str.html_safe %>

Using raw works fine, but all it's doing is converting the string to a string, and then calling html_safe. When I know I have a string, I prefer calling html_safe directly, because it skips an unnecessary step and makes clearer what's going on. Details about string-escaping and XSS protection are in this Asciicast.

Check if xdebug is working

Run

php -m -c

in your terminal, and then look for [Zend Modules]. It should be somewhere there if it is loaded!

NB

If you're using Ubuntu, it may not show up here because you need to add the xdebug settings from /etc/php5/apache2/php.ini into /etc/php5/cli/php.ini. Mine are

[xdebug]
zend_extension = /usr/lib/php5/20121212/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000

What is the difference between buffer and cache memory in Linux?

"Buffers" represent how much portion of RAM is dedicated to cache disk blocks. "Cached" is similar like "Buffers", only this time it caches pages from file reading.

quote from:

Include jQuery in the JavaScript Console

I'm a rebel.

Solution: don't use jQuery. jQuery is a library to abstract the DOM inconcistencies across the browsers. Since you're in your own console, you don't need this kind of abstraction.

For your example:

$$('element').length

($$ is an alias to document.querySelectorAll in the console.)

For any other example: I'm sure I can find anything. Especially if you're using a modern browser (Chrome, FF, Safari, Opera).

Besides, knowing how the DOM works wouldn't hurt anyone, it would only increase your level of jQuery (yes, learning more about javascript makes you better at jQuery).

Change URL and redirect using jQuery

As mentioned in the other answers, you don't need jQuery to do this; you can just use the standard properties.

However, it seems you don't seem to know the difference between window.location.replace(url) and window.location = url.

  1. window.location.replace(url) replaces the current location in the address bar by a new one. The page that was calling the function, won't be included in the browser history. Therefore, on the new location, clicking the back button in your browser would make you go back to the page you were viewing before you visited the document containing the redirecting JavaScript.
  2. window.location = url redirects to the new location. On this new page, the back button in your browser would point to the original page containing the redirecting JavaScript.

Of course, both have their use cases, but it seems to me like in this case you should stick with the latter.

P.S.: You probably forgot two slashes after http: on line 2 of your JavaScript:

url = "http://abc.com/" + temp;

Confused about Service vs Factory

Here are some more examples of services vs factories which may be useful in seeing the difference between them. Basically, a service has "new ..." called on it, it is already instantiated. A factory is not instantiated automatically.

Basic Examples

Return a class object which has a single method

Here is a service that has a single method:

angular.service('Hello', function () {
  this.sayHello = function () { /* ... */ };
});

Here is a factory that returns an object with a method:

angular.factory('ClassFactory', function () {
  return {
    sayHello: function () { /* ... */ }
  };
});

Return a value

A factory that returns a list of numbers:

angular.factory('NumberListFactory', function () {
  return [1, 2, 3, 4, 5];
});

console.log(NumberListFactory);

A service that returns a list of numbers:

angular.service('NumberLister', function () {
  this.numbers = [1, 2, 3, 4, 5];
});

console.log(NumberLister.numbers);

The output in both cases is the same, the list of numbers.

Advanced Examples

"Class" variables using factories

In this example we define a CounterFactory, it increments or decrements a counter and you can get the current count or get how many CounterFactory objects have been created:

angular.factory('CounterFactory', function () {
  var number_of_counter_factories = 0; // class variable

  return function () {
    var count = 0; // instance variable
    number_of_counter_factories += 1; // increment the class variable

    // this method accesses the class variable
    this.getNumberOfCounterFactories = function () {
      return number_of_counter_factories;
    };

    this.inc = function () {
      count += 1;
    };
    this.dec = function () {
      count -= 1;
    };
    this.getCount = function () {
      return count;
    };
  }

})

We use the CounterFactory to create multiple counters. We can access the class variable to see how many counters were created:

var people_counter;
var places_counter;

people_counter = new CounterFactory();
console.log('people', people_counter.getCount());
people_counter.inc();
console.log('people', people_counter.getCount());

console.log('counters', people_counter.getNumberOfCounterFactories());

places_counter = new CounterFactory();
console.log('places', places_counter.getCount());

console.log('counters', people_counter.getNumberOfCounterFactories());
console.log('counters', places_counter.getNumberOfCounterFactories());

The output of this code is:

people 0
people 1
counters 1
places 0
counters 2
counters 2

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

How can I use delay() with show() and hide() in Jquery

from jquery api

Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

http://api.jquery.com/delay/

Matplotlib - global legend and title aside subplots

Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure:

import matplotlib.pyplot as plt
fig = plt.gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)

Alternatively (based on @Steven C. Howell's comment below (thank you!)), use the matplotlib.pyplot.suptitle() function:

 import matplotlib.pyplot as plt
 # plot stuff
 # ...
 plt.suptitle("Title centered above all subplots", fontsize=14)

How to Add a Dotted Underline Beneath HTML Text

Reformatted the answer by @epascarello:

_x000D_
_x000D_
u.dotted {_x000D_
  border-bottom: 1px dashed #999;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<u class="dotted">I like cheese</u>
_x000D_
_x000D_
_x000D_

jquery remove "selected" attribute of option?

Similar to @radiak's response, but with jQuery (see this API document and comment on how to change the selectedIndex).

$('#mySelectParent').find("select").prop("selectedIndex",-1);

The benefits to this approach are:

  • You can stay within jQuery
  • You can limit the scope using jQuery selectors (#mySelectParent in the example)
  • More explicitly defined code
  • Works in IE8, Chrome, FF

The difference between the Runnable and Callable interfaces in Java

It is a kind of an interface naming convention which matches with functional programming

//Runnable
interface Runnable {
    void run();
}

//Action - throws exception
interface Action {
    void run() throws Exception;
}

//Consumer - consumes a value/values, throws exception
interface Consumer1<T> {
    void accept(T t) throws Exception;
}

//Callable - return result, throws exception
interface Callable<R> {
    R call() throws Exception;
}

//Supplier - returns result, throws exception
interface Supplier<R> {
    R get() throws Exception;
}

//Predicate - consumes a value/values, returns true or false, throws exception
interface Predicate1<T> {
    boolean test(T t) throws Exception;
}

//Function - consumes a value/values, returns result, throws exception
public interface Function1<T, R> {
    R apply(T t) throws Exception;
}

...

Adding items to a JComboBox

create a new class called ComboKeyValue.java

    public class ComboKeyValue {
        private String key;
        private String value;
    
        public ComboKeyValue(String key, String value) {
            this.key = key;
            this.value = value;
        }
        
        @Override
        public String toString(){
            return key;
        }
    
        public String getKey() {
            return key;
        }
    
        public String getValue() {
            return value;
        }
}

when you want to add a new item, just write the code as below

 DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(new ComboKeyValue("key", "value"));
    properties.setModel(model);

Command to get latest Git commit hash from a branch

git log -n 1 [branch_name]

branch_name (may be remote or local branch) is optional. Without branch_name, it will show the latest commit on the current branch.

For example:

git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch

git log -n 1 --pretty=format:"%H"  #To get only hash value of commit

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

Use of "this" keyword in C++

Yes. unless, there is an ambiguity.

IntelliJ: Working on multiple projects

For people not using maven to build and wanting to add a new project (I am using intellij 14.1.3):

  1. Right click the top level folder in the project view, select new -> Module
  2. Name the module the same name as the project to be added
  3. From the top menu select File->New->Project. Enter the same name as the new module, same folder locations as well.
  4. Open the Project, and wait for intellij to create the project structure.
  5. Close this new project, and open the original project the module was added to in step 2

Depending on your builder, additional steps will be needed to add it to the build process.

For SBT, and in the top level project I modified the Build.scala file to aggregate the new project, and added the project in the SBT projects window. More info on SBT multiproject builds: http://www.scala-sbt.org/0.12.2/docs/Getting-Started/Multi-Project.html

How do I prevent 'git diff' from using a pager?

I have this hunk in my .gitconfig and it seems to work fine (disabled for both diff and show):

[pager]
    diff = false
    show = false

Duplicate headers received from server

For me the issue was about a comma not in the filename but as below: -

Response.ok(streamingOutput,MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment, filename=your_file_name").build();

I accidentally put a comma after attachment. Got it resolved by replacing comma with a semicolon.

C# Return Different Types?

Marc's answer should be the correct one, but in .NET 4 you couldn't also go with dynamic type.

This should be used only if you have no control over the classes you return and there are no common ancestors ( usually with interop ) and only if not using dynamic is a lot more painful then using(casting every object in every step :) ).

Few blog post trying to explain when to use dynamic: http://blogs.msdn.com/b/csharpfaq/archive/tags/dynamic/

public dynamic GetSomething()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio(); 
     return // anyobject

}

How to set ChartJS Y axis title?

For x and y axes:

     options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }],
        xAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'hola'
          }
        }],
      }
    }

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

How do you format code in Visual Studio Code (VSCode)

Use extension...

Enables auto formatting of the code when you save a file.

Launch Visual Studio Code and Quick Open (Ctrl + P), paste the following command, and press Enter.

ext install format-on-save

https://marketplace.visualstudio.com/items?itemName=gyuha.format-on-save

How to create JSON Object using String?

If you use the gson.JsonObject you can have something like that:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

Filter output in logcat by tagname

Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:

$ adb shell logcat | grep YouTag
# just like: 
$ ps -ef | grep your_proc 

Regular Expression For Duplicate Words

Since some developers are coming to this page in search of a solution which not only eliminates duplicate consecutive non-whitespace substrings, but triplicates and beyond, I'll show the adapted pattern.

Pattern: /(\b\S+)(?:\s+\1\b)+/ (Pattern Demo)
Replace: $1 (replaces the fullstring match with capture group #1)

This pattern greedily matches a "whole" non-whitespace substring, then requires one or more copies of the matched substring which may be delimited by one or more whitespace characters (space, tab, newline, etc).

Specifically:

  • \b (word boundary) characters are vital to ensure partial words are not matched.
  • The second parenthetical is a non-capturing group, because this variable width substring does not need to be captured -- only matched/absorbed.
  • the + (one or more quantifier) on the non-capturing group is more appropriate than * because * will "bother" the regex engine to capture and replace singleton occurrences -- this is wasteful pattern design.

*note if you are dealing with sentences or input strings with punctuation, then the pattern will need to be further refined.

How to install cron

On CentOS/RHEL:

yum install cronie

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

How to auto generate migrations with Sequelize CLI from Sequelize models?

As of 16/9/2020 most of these answers are not too much consistent any way! Try this new npm package

Sequelize-mig

It completed most known problems in sequelize-auto-migrations and its forks and its maintained and documented!

Its used in a way similar to the known one

Install:

npm install sequelize-mig -g / yarn global add sequelize-mig

then use it like this

sequelize-mig migration:make -n <migration name>

How do I indent multiple lines at once in Notepad++?

I have Notepad++ 5.3.1 (UNICODE). I haven't done any magic and it works fine for me as described by you.

Maybe it depends on the (programming/markup/...) "Language"?

How can I match on an attribute that contains a certain string?

Here's an example that finds div elements whose className contains atag:

//div[contains(@class, 'atag')]

Here's an example that finds div elements whose className contains atag and btag:

//div[contains(@class, 'atag') and contains(@class ,'btag')]

However, it will also find partial matches like class="catag bobtag".

If you don't want partial matches, see bobince's answer below.

Cannot assign requested address - possible causes?

sysctl -w net.ipv4.tcp_timestamps=1
sysctl -w net.ipv4.tcp_tw_recycle=1

How to fix a locale setting warning from Perl

On Debian, after much searching, this did the trick.

First:

sudo apt-get purge locales

Then:

sudo aptitude install locales

And the famous:

sudo dpkg-reconfigure locales

This rids the system of locales, then re-installs locales and downgrades libc6 from 2.19 to 2.13 which is the issue. Then it configures locales again.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

I run it like this -

created > startOfDay(-0d)

It gives me all issues created today. When you change -0d to -1d, it will give you all issues created yesterday and today.

How to synchronize or lock upon variables in Java?

Use the synchronized keyword.

class sample {
    private String msg=null;

    public synchronized void newmsg(String x){
        msg=x;
    }

    public synchronized string getmsg(){
        String temp=msg;
        msg=null;
        return msg;
    }
}

Using the synchronized keyword on the methods will require threads to obtain a lock on the instance of sample. Thus, if any one thread is in newmsg(), no other thread will be able to get a lock on the instance of sample, even if it were trying to invoke getmsg().

On the other hand, using synchronized methods can become a bottleneck if your methods perform long-running operations - all threads, even if they want to invoke other methods in that object that could be interleaved, will still have to wait.

IMO, in your simple example, it's ok to use synchronized methods since you actually have two methods that should not be interleaved. However, under different circumstances, it might make more sense to have a lock object to synchronize on, as shown in Joh Skeet's answer.

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

I know of enabling or disabling wifi:

WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);

where status may be true or false as per requirement.

Edit:

You also need the following permissions in your manifest file:

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

Convert a Python list with strings all to lowercase or uppercase

Solution:

>>> s = []
>>> p = ['This', 'That', 'There', 'is', 'apple']
>>> [s.append(i.lower()) if not i.islower() else s.append(i) for i in p]
>>> s
>>> ['this', 'that', 'there', 'is','apple']

This solution will create a separate list containing the lowercase items, regardless of their original case. If the original case is upper then the list s will contain lowercase of the respective item in list p. If the original case of the list item is already lowercase in list p then the list s will retain the item's case and keep it in lowercase. Now you can use list s instead of list p.

Using JavaScript to display a Blob

If you want to use fetch instead:

var myImage = document.querySelector('img');

fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Source:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

How to see if an object is an array without using reflection?

There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.

Therefore, the following is incorrect as a test to see if obj is an array of any kind:

// INCORRECT!
public boolean isArray(final Object obj) {
    return obj instanceof Object[];
}

Specifically, it doesn't work if obj is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object. But it is moot in this case.)

I use Google GWT so I am not allowed to use reflection :(

The best solution (to the isArray array part of the question) depends on what counts as "using reflection".

  • In GWT, calling obj.getClass().isArray() does not count as using reflection1, so that is the best solution.

  • Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof expressions.

    public boolean isArray(final Object obj) {
        return obj instanceof Object[] || obj instanceof boolean[] ||
           obj instanceof byte[] || obj instanceof short[] ||
           obj instanceof char[] || obj instanceof int[] ||
           obj instanceof long[] || obj instanceof float[] ||
           obj instanceof double[];
    }
    
  • You could also try messing around with the name of the object's class as follows, but the call to obj.getClass() is bordering on reflection.

    public boolean isArray(final Object obj) {
        return obj.getClass().toString().charAt(0) == '[';
    }
    

1 - More precisely, the Class.isArray method is listed as supported by GWT in this page.

For each row return the column name of the largest value

A simple for loop can also be handy:

> df<-data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
> df
  V1 V2 V3
1  2  7  9
2  8  3  6
3  1  5  4
> df2<-data.frame()
> for (i in 1:nrow(df)){
+   df2[i,1]<-colnames(df[which.max(df[i,])])
+ }
> df2
  V1
1 V3
2 V1
3 V2

Convert a List<T> into an ObservableCollection<T>

ObservableCollection < T > has a constructor overload which takes IEnumerable < T >

Example for a List of int:

ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);

One more example for a List of ObjectA:

ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);

TSQL Default Minimum DateTime

Sometimes you inherit brittle code that is already expecting magic values in a lot of places. Everyone is correct, you should use NULL if possible. However, as a shortcut to make sure every reference to that value is the same, I like to put "constants" (for lack of a better name) in SQL in a scaler function and then call that function when I need the value. That way if I ever want to update them all to be something else, I can do so easily. Or if I want to change the default value moving forward, I only have one place to update it.

The following code creates the function and a table using it for the default DateTime value. Then inserts and select from the table without specifying the value for Modified. Then cleans up after itself. I hope this helps.

-- CREATE FUNCTION
CREATE FUNCTION dbo.DateTime_MinValue ( )
RETURNS DATETIME
AS 
    BEGIN
        DECLARE @dateTime_min DATETIME ;
        SET @dateTime_min = '1/1/1753 12:00:00 AM'
        RETURN @dateTime_min ;
    END ;
GO


-- CREATE TABLE USING FUNCTION FOR DEFAULT
CREATE TABLE TestTable
(
  TestTableId INT IDENTITY(1, 1)
                  PRIMARY KEY CLUSTERED ,
  Value VARCHAR(50) ,
  Modified DATETIME DEFAULT dbo.DateTime_MinValue()
) ;


-- INSERT VALUE INTO TABLE
INSERT  INTO TestTable
        ( Value )
VALUES  ( 'Value' ) ;


-- SELECT FROM TABLE
SELECT  TestTableId ,
        VALUE ,
        Modified
FROM    TestTable ;


-- CLEANUP YOUR DB
DROP TABLE TestTable ;
DROP FUNCTION dbo.DateTime_MinValue ;

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

I wrote a function for my own project to do this (it doesn't use numpy, though):

def partition(seq, chunks):
    """Splits the sequence into equal sized chunks and them as a list"""
    result = []
    for i in range(chunks):
        chunk = []
        for element in seq[i:len(seq):chunks]:
            chunk.append(element)
        result.append(chunk)
    return result

If you want the chunks to be randomized, just shuffle the list before passing it in.

Working copy locked error in tortoise svn while committing

If this (https://stackoverflow.com/a/11764922/3045875) does not help: Check if another SVN tool is interfering and close the tool. We just struggled a couple of hours at merging using TortoiseSVN and had dozens of such lock errors. Eventually we figured that Matlabs SVN integration is interfering and after closing it all worked out.

Why I can't access remote Jupyter Notebook server?

Try doing below step:

Following command fixes the read/write

    sudo chmod -R a+rw /home/ubuntu/certs/mycert.pem

Restoring database from .mdf and .ldf files of SQL Server 2008

First google search yielded me this answer. So I thought of updating this with newer version of attach, detach.

Create database dbname 
On 
(   
Filename= 'path where you copied files',   
Filename ='path where you copied log'
)
For attach; 

Further,if your database is cleanly shutdown(there are no active transactions while database was shutdown) and you dont have log file,you can use below method,SQL server will create a new transaction log file..

Create database dbname 
    On 
    (   
    Filename= 'path where you copied files'   
    )
    For attach; 

if you don't specify transaction log file,SQL will try to look in the default path and will try to use it irrespective of whether database was cleanly shutdown or not..

Here is what MSDN has to say about this..

If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.

There are some restrictions with this approach and some side affects too..

1.attach-and-detach operations both disable cross-database ownership chaining for the database
2.Database trustworthy is set to off
3.Detaching a read-only database loses information about the differential bases of differential backups.

Most importantly..you can't attach a database with recent versions to an earlier version

References:
https://msdn.microsoft.com/en-in/library/ms190794.aspx

How to get the nth occurrence in a string?

a simple solution just add string, character and idx:

function getCharIdx(str,char,n){
  let r = 0
  for (let i = 0; i<str.length; i++){
    if (str[i] === char){
      r++
      if (r === n){
        return i
      }

    }
   
  }
}

iPhone Debugging: How to resolve 'failed to get the task for process'?

Yes , Provisioning profiles which are for distribution purpose, i.e. Distrutions provisioning profiles do not support debugging and gives this error. Simply create and use debug provisioning profile (take care of this when creating provisioning profile from developer.apple.com account).

Sanitizing user input before adding it to the DOM in Javascript

Never use escape(). It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.

If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

However whilst this is enough to put your user_id in places like the input value, it's not enough for id because IDs can only use a limited selection of characters. (And % isn't among them, so escape() or even encodeURIComponent() is no good.)

You could invent your own encoding scheme to put any characters in an ID, for example:

function encodeID(s) {
    if (s==='') return '_';
    return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
        return '_'+match[0].charCodeAt(0).toString(16)+'_';
    });
}

But you've still got a problem if the same user_id occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById, or worrying about how arbitrary strings are inserted into IDs.

eg.:

function addChut(user_id) {
    var log= document.createElement('div');
    log.className= 'log';
    var textarea= document.createElement('textarea');
    var input= document.createElement('input');
    input.value= user_id;
    input.readonly= True;
    var button= document.createElement('input');
    button.type= 'button';
    button.value= 'Message';

    var chut= document.createElement('div');
    chut.className= 'chut';
    chut.appendChild(log);
    chut.appendChild(textarea);
    chut.appendChild(input);
    chut.appendChild(button);
    document.getElementById('chuts').appendChild(chut);

    button.onclick= function() {
        alert('Send '+textarea.value+' to '+user_id);
    };

    return chut;
}

You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.

ETA:

I'm using jQuery at the moment as a framework

OK, then consider the jQuery 1.4 creation shortcuts, eg.:

var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...

The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.

You can keep a lookup of user_id to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id are restricted.

var chut_lookup= {};
...

function getChut(user_id) {
    var key= '_map_'+user_id;
    if (key in chut_lookup)
        return chut_lookup[key];
    return chut_lookup[key]= addChut(user_id);
}

(The _map_ prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object member names, confuse it.)

Checkout another branch when there are uncommitted changes on the current branch

Preliminary notes

This answer is an attempt to explain why Git behaves the way it does. It is not a recommendation to engage in any particular workflows. (My own preference is to just commit anyway, avoiding git stash and not trying to be too tricky, but others like other methods.)

The observation here is that, after you start working in branch1 (forgetting or not realizing that it would be good to switch to a different branch branch2 first), you run:

git checkout branch2

Sometimes Git says "OK, you're on branch2 now!" Sometimes, Git says "I can't do that, I'd lose some of your changes."

If Git won't let you do it, you have to commit your changes, to save them somewhere permanent. You may want to use git stash to save them; this is one of the things it's designed for. Note that git stash save or git stash push actually means "Commit all the changes, but on no branch at all, then remove them from where I am now." That makes it possible to switch: you now have no in-progress changes. You can then git stash apply them after switching.

Sidebar: git stash save is the old syntax; git stash push was introduced in Git version 2.13, to fix up some problems with the arguments to git stash and allow for new options. Both do the same thing, when used in the basic ways.

You can stop reading here, if you like!

If Git won't let you switch, you already have a remedy: use git stash or git commit; or, if your changes are trivial to re-create, use git checkout -f to force it. This answer is all about when Git will let you git checkout branch2 even though you started making some changes. Why does it work sometimes, and not other times?

The rule here is simple in one way, and complicated/hard-to-explain in another:

You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.

That is—and please note that this is still simplified; there are some extra-difficult corner cases with staged git adds, git rms and such—suppose you are on branch1. A git checkout branch2 would have to do this:

  • For every file that is in branch1 and not in branch2,1 remove that file.
  • For every file that is in branch2 and not in branch1, create that file (with appropriate contents).
  • For every file that is in both branches, if the version in branch2 is different, update the working tree version.

Each of these steps could clobber something in your work-tree:

  • Removing a file is "safe" if the version in the work-tree is the same as the committed version in branch1; it's "unsafe" if you've made changes.
  • Creating a file the way it appears in branch2 is "safe" if it does not exist now.2 It's "unsafe" if it does exist now but has the "wrong" contents.
  • And of course, replacing the work-tree version of a file with a different version is "safe" if the work-tree version is already committed to branch1.

Creating a new branch (git checkout -b newbranch) is always considered "safe": no files will be added, removed, or altered in the work-tree as part of this process, and the index/staging-area is also untouched. (Caveat: it's safe when creating a new branch without changing the new branch's starting-point; but if you add another argument, e.g., git checkout -b newbranch different-start-point, this might have to change things, to move to different-start-point. Git will then apply the checkout safety rules as usual.)


1This requires that we define what it means for a file to be in a branch, which in turn requires defining the word branch properly. (See also What exactly do we mean by "branch"?) Here, what I really mean is the commit to which the branch-name resolves: a file whose path is P is in branch1 if git rev-parse branch1:P produces a hash. That file is not in branch1 if you get an error message instead. The existence of path P in your index or work-tree is not relevant when answering this particular question. Thus, the secret here is to examine the result of git rev-parse on each branch-name:path. This either fails because the file is "in" at most one branch, or gives us two hash IDs. If the two hash IDs are the same, the file is the same in both branches. No changing is required. If the hash IDs differ, the file is different in the two branches, and must be changed to switch branches.

The key notion here is that files in commits are frozen forever. Files you will edit are obviously not frozen. We are, at least initially, looking only at the mismatches between two frozen commits. Unfortunately, we—or Git—also have to deal with files that aren't in the commit you're going to switch away from and are in the commit you're going to switch to. This leads to the remaining complications, since files can also exist in the index and/or in the work-tree, without having to exist these two particular frozen commits we're working with.

2It might be considered "sort-of-safe" if it already exists with the "right contents", so that Git does not have to create it after all. I recall at least some versions of Git allowing this, but testing just now shows it to be considered "unsafe" in Git 1.8.5.4. The same argument would apply to a modified file that happens to be modified to match the to-be-switch-to branch. Again, 1.8.5.4 just says "would be overwritten", though. See the end of the technical notes as well: my memory may be faulty as I don't think the read-tree rules have changed since I first started using Git at version 1.5.something.


Does it matter whether the changes are staged or unstaged?

Yes, in some ways. In particular, you can stage a change, then "de-modify" the work tree file. Here's a file in two branches, that's different in branch1 and branch2:

$ git show branch1:inboth
this file is in both branches
$ git show branch2:inboth
this file is in both branches
but it has more stuff in branch2 now
$ git checkout branch1
Switched to branch 'branch1'
$ echo 'but it has more stuff in branch2 now' >> inboth

At this point, the working tree file inboth matches the one in branch2, even though we're on branch1. This change is not staged for commit, which is what git status --short shows here:

$ git status --short
 M inboth

The space-then-M means "modified but not staged" (or more precisely, working-tree copy differs from staged/index copy).

$ git checkout branch2
error: Your local changes ...

OK, now let's stage the working-tree copy, which we already know also matches the copy in branch2.

$ git add inboth
$ git status --short
M  inboth
$ git checkout branch2
Switched to branch 'branch2'

Here the staged-and-working copies both matched what was in branch2, so the checkout was allowed.

Let's try another step:

$ git checkout branch1
Switched to branch 'branch1'
$ cat inboth
this file is in both branches

The change I made is lost from the staging area now (because checkout writes through the staging area). This is a bit of a corner case. The change is not gone, but the fact that I had staged it, is gone.

Let's stage a third variant of the file, different from either branch-copy, then set the working copy to match the current branch version:

$ echo 'staged version different from all' > inboth
$ git add inboth
$ git show branch1:inboth > inboth
$ git status --short
MM inboth

The two Ms here mean: staged file differs from HEAD file, and, working-tree file differs from staged file. The working-tree version does match the branch1 (aka HEAD) version:

$ git diff HEAD
$

But git checkout won't allow the checkout:

$ git checkout branch2
error: Your local changes ...

Let's set the branch2 version as the working version:

$ git show branch2:inboth > inboth
$ git status --short
MM inboth
$ git diff HEAD
diff --git a/inboth b/inboth
index ecb07f7..aee20fb 100644
--- a/inboth
+++ b/inboth
@@ -1 +1,2 @@
 this file is in both branches
+but it has more stuff in branch2 now
$ git diff branch2 -- inboth
$ git checkout branch2
error: Your local changes ...

Even though the current working copy matches the one in branch2, the staged file does not, so a git checkout would lose that copy, and the git checkout is rejected.

Technical notes—only for the insanely curious :-)

The underlying implementation mechanism for all of this is Git's index. The index, also called the "staging area", is where you build the next commit: it starts out matching the current commit, i.e., whatever you have checked-out now, and then each time you git add a file, you replace the index version with whatever you have in your work-tree.

Remember, the work-tree is where you work on your files. Here, they have their normal form, rather than some special only-useful-to-Git form like they do in commits and in the index. So you extract a file from a commit, through the index, and then on into the work-tree. After changing it, you git add it to the index. So there are in fact three places for each file: the current commit, the index, and the work-tree.

When you run git checkout branch2, what Git does underneath the covers is to compare the tip commit of branch2 to whatever is in both the current commit and the index now. Any file that matches what's there now, Git can leave alone. It's all untouched. Any file that's the same in both commits, Git can also leave alone—and these are the ones that let you switch branches.

Much of Git, including commit-switching, is relatively fast because of this index. What's actually in the index is not each file itself, but rather each file's hash. The copy of the file itself is stored as what Git calls a blob object, in the repository. This is similar to how the files are stored in commits as well: commits don't actually contain the files, they just lead Git to the hash ID of each file. So Git can compare hash IDs—currently 160-bit-long strings—to decide if commits X and Y have the same file or not. It can then compare those hash IDs to the hash ID in the index, too.

This is what leads to all the oddball corner cases above. We have commits X and Y that both have file path/to/name.txt, and we have an index entry for path/to/name.txt. Maybe all three hashes match. Maybe two of them match and one doesn't. Maybe all three are different. And, we might also have another/file.txt that's only in X or only in Y and is or is not in the index now. Each of these various cases requires its own separate consideration: does Git need to copy the file out from commit to index, or remove it from index, to switch from X to Y? If so, it also has to copy the file to the work-tree, or remove it from the work-tree. And if that's the case, the index and work-tree versions had better match at least one of the committed versions; otherwise Git will be clobbering some data.

(The complete rules for all of this are described in, not the git checkout documentation as you might expect, but rather the git read-tree documentation, under the section titled "Two Tree Merge".)

Hibernate Group by Criteria Object

Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.

For example :

SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name

Its equivalent criteria object is :

List result = session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).list();

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()

If you run yourcode.py you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

How to read a value from the Windows registry

Here is some pseudo-code to retrieve the following:

  1. If a registry key exists
  2. What the default value is for that registry key
  3. What a string value is
  4. What a DWORD value is

Example code:

Include the library dependency: Advapi32.lib

HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);
std::wstring strValueOfBinDir;
std::wstring strKeyDefaultValue;
GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");

LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
{
    nValue = nDefaultValue;
    DWORD dwBufferSize(sizeof(DWORD));
    DWORD nResult(0);
    LONG nError = ::RegQueryValueExW(hKey,
        strValueName.c_str(),
        0,
        NULL,
        reinterpret_cast<LPBYTE>(&nResult),
        &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        nValue = nResult;
    }
    return nError;
}


LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
{
    DWORD nDefValue((bDefaultValue) ? 1 : 0);
    DWORD nResult(nDefValue);
    LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
    if (ERROR_SUCCESS == nError)
    {
        bValue = (nResult != 0) ? true : false;
    }
    return nError;
}


LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
{
    strValue = strDefaultValue;
    WCHAR szBuffer[512];
    DWORD dwBufferSize = sizeof(szBuffer);
    ULONG nError;
    nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        strValue = szBuffer;
    }
    return nError;
}

Changing the image source using jQuery

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

What is the default access specifier in Java?

The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.

Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package

Is it possible to get a history of queries made in postgres

Not logging but if you're troubleshooting slow running queries in realtime, you can query the pg_stat_activity view to see which queries are active, the user/connection they came from, when they started, etc. Eg...

SELECT *
FROM pg_stat_activity
WHERE state = 'active'

See the pg_stat_activity view docs.

Scanner is skipping nextLine() after using next() or nextFoo()?

As nextXXX() methods don't read newline, except nextLine(). We can skip the newline after reading any non-string value (int in this case) by using scanner.skip() as below:

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(x);
double y = sc.nextDouble();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(y);
char z = sc.next().charAt(0);
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(z);
String hello = sc.nextLine();
System.out.println(hello);
float tt = sc.nextFloat();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(tt);

How can I regenerate ios folder in React Native project?

Since react-native eject is depreciated in 60.3 and I was getting diff errors trying to upgrade form 60.1 to 60.3 regenerating the android folder was not working.

I had to

rm -R node_modules

Then update react-native in package.json to 59.1 (remove package-lock.json)

Run

npm install

react-native eject

This will regenerate your android and ios folders Finally upgrade back to 60.3

react-native upgrade

react-native upgrade while back and 59.1 did not regenerate my android folder so the eject was necessary.

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

How to Completely Uninstall Xcode and Clear All Settings

This answer should be more of a comment against Dawn Song's comment earlier, but since I don't have enough reputation, I'm going to write it as an answer.

According to the forum page

https://forums.developer.apple.com/thread/11313

"In general, you should never just delete the CoreSimulator/Devices directory yourself. If you really absolutely must, you need to make sure that the service is not runnign while you do that. eg:"

# Quit Xcode.app, Simulator.app, etc
sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService
rm -rf ~/Library/*/CoreSimulator

I definitely ran into this issue after deleting and reinstalling Xcode.

You might encounter a problem trying to connect the build to a simulator device. The thread also answers what to do in that case,

gem install snapshot
fastlane snapshot reset_simulators

How do you check for permissions to write to a directory or file?

You can try following code block to check if the directory is having Write Access.

It checks the FileSystemAccessRule.

           string directoryPath = "C:\\XYZ"; //folderBrowserDialog.SelectedPath;
           bool isWriteAccess = false;
           try
           {
              AuthorizationRuleCollection collection = Directory.GetAccessControl(directoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
              foreach (FileSystemAccessRule rule in collection)
              {
                 if (rule.AccessControlType == AccessControlType.Allow)
                 {
                    isWriteAccess = true;
                    break;
                 }
              }
           }
           catch (UnauthorizedAccessException ex)
           {
              isWriteAccess = false;
           }
           catch (Exception ex)
           {
              isWriteAccess = false;
           }
           if (!isWriteAccess)
           {
             //handle notifications                 
           }

Check list of words in another string

Here are a couple of alternative ways of doing it, that may be faster or more suitable than KennyTM's answer, depending on the context.

1) use a regular expression:

import re
words_re = re.compile("|".join(list_of_words))

if words_re.search('some one long two phrase three'):
   # do logic you want to perform

2) You could use sets if you want to match whole words, e.g. you do not want to find the word "the" in the phrase "them theorems are theoretical":

word_set = set(list_of_words)
phrase_set = set('some one long two phrase three'.split())
if word_set.intersection(phrase_set):
    # do stuff

Of course you can also do whole word matches with regex using the "\b" token.

The performance of these and Kenny's solution are going to depend on several factors, such as how long the word list and phrase string are, and how often they change. If performance is not an issue then go for the simplest, which is probably Kenny's.

How to find out which package version is loaded in R?

Based on the previous answers, here is a simple alternative way of printing the R-version, followed by the name and version of each package loaded in the namespace. It works in the Jupyter notebook, where I had troubles running sessionInfo() and R --version.

print(paste("R", getRversion()))
print("-------------")
for (package_name in sort(loadedNamespaces())) {
    print(paste(package_name, packageVersion(package_name)))
}

Out:

[1] "R 3.2.2"
[1] "-------------"
[1] "AnnotationDbi 1.32.2"
[1] "Biobase 2.30.0"
[1] "BiocGenerics 0.16.1"
[1] "BiocParallel 1.4.3"
[1] "DBI 0.3.1"
[1] "DESeq2 1.10.0"
[1] "Formula 1.2.1"
[1] "GenomeInfoDb 1.6.1"
[1] "GenomicRanges 1.22.3"
[1] "Hmisc 3.17.0"
[1] "IRanges 2.4.6"
[1] "IRdisplay 0.3"
[1] "IRkernel 0.5"

jQuery pass more parameters into callback

When using doSomething(data, myDiv), you actually call the function and do not make a reference to it.

You can either pass the doStomething function directly but you must ensure it has the correct signature.

If you want to keep doSomething the way it is, you can wrap its call in an anonymous function.

function clicked() {
    var myDiv = $("#my-div");
    $.post("someurl.php",someData, function(data){ 
      doSomething(data, myDiv)
    },"json"); 
}

function doSomething(curData, curDiv) {
    ...
}

Inside the anonymous function code, you can use the variables defined in the enclosing scope. This is the way Javascript scoping works.

jQuery - how to check if an element exists?

Assuming you are trying to find if a div exists

$('div').length ? alert('div found') : alert('Div not found')

Check working example at http://jsfiddle.net/Qr86J/1/

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are mixing mysqli and mysql extensions, which will not work.

You need to use

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   

mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli.

How to resolve /var/www copy/write permission denied?

it'matter of *unix permissions, gain root acces, for example by typing

sudo su
[then type your password]

and try to do what you have to do

Java code To convert byte to Hexadecimal

Here is a simple function to convert byte to Hexadecimal

   private static String convertToHex(byte[] data) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
        int halfbyte = (data[i] >>> 4) & 0x0F;
        int two_halfs = 0;
        do {
            if ((0 <= halfbyte) && (halfbyte <= 9))
                buf.append((char) ('0' + halfbyte));
            else
                buf.append((char) ('a' + (halfbyte - 10)));
            halfbyte = data[i] & 0x0F;
        } while(two_halfs++ < 1);
    }
    return buf.toString();
}

Passing parameters to addTarget:action:forControlEvents

To pass custom params along with the button click you just need to SUBCLASS UIButton.

(ASR is on, so there's no releases in the code.)

This is myButton.h

#import <UIKit/UIKit.h>

@interface myButton : UIButton {
    id userData;
}

@property (nonatomic, readwrite, retain) id userData;

@end

This is myButton.m

#import "myButton.h"
@implementation myButton
@synthesize userData;
@end

Usage:

myButton *bt = [myButton buttonWithType:UIButtonTypeCustom];
[bt setFrame:CGRectMake(0,0, 100, 100)];
[bt setExclusiveTouch:NO];
[bt setUserData:**(insert user data here)**];

[bt addTarget:self action:@selector(touchUpHandler:) forControlEvents:UIControlEventTouchUpInside];

[view addSubview:bt];

Recieving function:

- (void) touchUpHandler:(myButton *)sender {
    id userData = sender.userData;
}

If you need me to be more specific on any part of the above code — feel free to ask about it in comments.

How do you convert WSDLs to Java classes using Eclipse?

Using command prompt in windows you can use below command to get class files.

wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl

if you want to generate source code you should be using below commnad.

wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl

Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.

Is there an XSLT name-of element?

<xsl:for-each select="person">
  <xsl:for-each select="*">
    <xsl:value-of select="local-name()"/> : <xsl:value-of select="."/>
  </xsl:for-each>  
</xsl:for-each>

How to remove the first and the last character of a string

use .replace(/.*\/(\S+)\//img,"$1")

"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

Checking if date is weekend PHP

If you have PHP >= 5.1:

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}

otherwise:

function isWeekend($date) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || $weekDay == 6);
}

Using Gradle to build a jar with dependencies

This works fine for me.

My Main class:

package com.curso.online.gradle;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class Main {

    public static void main(String[] args) {
        Logger logger = Logger.getLogger(Main.class);
        logger.debug("Starting demo");

        String s = "Some Value";

        if (!StringUtils.isEmpty(s)) {
            System.out.println("Welcome ");
        }

        logger.debug("End of demo");
    }

}

And it is the content of my file build.gradle:

apply plugin: 'java'

apply plugin: 'eclipse'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    compile  'org.apache.commons:commons-lang3:3.0'
    compile  'log4j:log4j:1.2.16'
}

task fatJar(type: Jar) {
    manifest {
        attributes 'Main-Class': 'com.curso.online.gradle.Main'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

And I write the following in my console:

java -jar ProyectoEclipseTest-all.jar

And the output is great:

log4j:WARN No appenders could be found for logger (com.curso.online.gradle.Main)
.
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more in
fo.
Welcome

How do I get the last character of a string?

Try this:

if (s.charAt(0) == s.charAt(s.length() - 1))

C# Sort and OrderBy comparison

Why not measure it:

class Program
{
    class NameComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return string.Compare(x, y, true);
        }
    }

    class Person
    {
        public Person(string id, string name)
        {
            Id = id;
            Name = name;
        }
        public string Id { get; set; }
        public string Name { get; set; }
    }

    static void Main()
    {
        List<Person> persons = new List<Person>();
        persons.Add(new Person("P005", "Janson"));
        persons.Add(new Person("P002", "Aravind"));
        persons.Add(new Person("P007", "Kazhal"));

        Sort(persons);
        OrderBy(persons);

        const int COUNT = 1000000;
        Stopwatch watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            Sort(persons);
        }
        watch.Stop();
        Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            OrderBy(persons);
        }
        watch.Stop();
        Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
    }

    static void Sort(List<Person> list)
    {
        list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
    }

    static void OrderBy(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
    }
}

On my computer when compiled in Release mode this program prints:

Sort: 1162ms
OrderBy: 1269ms

UPDATE:

As suggested by @Stefan here are the results of sorting a big list fewer times:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString()));
}

Sort(persons);
OrderBy(persons);

const int COUNT = 30;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);

Prints:

Sort: 8965ms
OrderBy: 8460ms

In this scenario it looks like OrderBy performs better.


UPDATE2:

And using random names:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}

Where:

private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
    var sb = new StringBuilder(size);
    int start = (lowerCase) ? 97 : 65;
    for (int i = 0; i < size; i++)
    {
        sb.Append((char)(26 * randomSeed.NextDouble() + start));
    }
    return sb.ToString();
}

Yields:

Sort: 8968ms
OrderBy: 8728ms

Still OrderBy is faster

How do I install cygwin components from the command line?

Dawid Ferenczy's answer is pretty complete but after I tried almost all of his options I've found that the Chocolatey’s cyg-get was the best (at least the only one that I could get to work).

I was wanting to install wget, the steps was this:

choco install cyg-get

Then:

cyg-get wget

Redirect all to index.php using htaccess

Your rewrite rule looks almost ok.

First make sure that your .htaccess file is in your document root (the same place as index.php) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).

Next make a slight change to your rule so it looks something like:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

At the moment you're just matching on . which is one instance of any character, you need at least .* to match any number of instances of any character.

The $_GET['path'] variable will contain the fake directory structure, so /mvc/module/test for instance, which you can then use in index.php to determine the Controller and actions you want to perform.


If you want the whole shebang installed in a sub-directory, such as /mvc/ or /framework/ the least complicated way to do it is to change the rewrite rule slightly to take that into account.

RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]

And ensure that your index.php is in that folder whilst the .htaccess file is in the document root.


Alternative to $_GET['path'] (updated Feb '18 and Jan '19)

It's not actually necessary (nor even common now) to set the path as a $_GET variable, many frameworks will rely on $_SERVER['REQUEST_URI'] to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.

This does simplify the RewriteRule slightly as you don't need to create the path parameter (which means the OP's original RewriteRule will now work):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

However, the rule about installing in a sub-directory still applies, e.g.

RewriteRule ^.*$ /mvc/index.php [L,QSA]



The flags:

NC = No Case (not case sensitive, not really necessary since there are no characters in the pattern)

L = Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)

QSA = Query String Append, just in case you've got something like ?like=penguins on the end which you want to keep and pass to index.php.

Is it possible to change the radio button icon in an android radio button group

You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl" 
    android:state_pressed="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_checked="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />  
</selector> 

Here you can use 3 different images for radiobutton

and use this file to RadioButton like:

android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content" 

Why won't eclipse switch the compiler to Java 8?

First install the JDK1.8 set to Path Open Eclipse and Oper Eclipse Market Place option. Search for jdk 1.8 for kepler Install the required plugin. Restart the eclipse. Change compiler level to 1.8 from preferences. If still there is an error then click on the file and change the compiler setting explicitly to Jdk 1.8

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));
}

Are list-comprehensions and functional functions faster than "for loops"?

I wrote a simple script that test the speed and this is what I found out. Actually for loop was fastest in my case. That really suprised me, check out bellow (was calculating sum of squares).

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        i = i**2
        a += i
    return a

def square_sum3(numbers):
    sqrt = lambda x: x**2
    return sum(map(sqrt, numbers))

def square_sum4(numbers):
    return(sum([int(i)**2 for i in numbers]))


time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.302000 #Reduce
0:00:00.144000 #For loop
0:00:00.318000 #Map
0:00:00.390000 #List comprehension

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

Use jquery to set value of div tag

use as below:

<div id="getSessionStorage"></div>

For this to append anything use below code for reference:

$(document).ready(function () {
        var storageVal = sessionStorage.getItem("UserName");
        alert(storageVal);
        $("#getSessionStorage").append(storageVal);
     });

This will appear as below in html (assuming storageVal="Rishabh")

<div id="getSessionStorage">Rishabh</div>

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

Bind failed: Address already in use

The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.

Also check if you are binding to the right ip address (I am assuming it would be localhost)

Disable output buffering

I would rather put my answer in How to flush output of print function? or in Python's print function that flushes the buffer when it's called?, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.

Since Python 3.3, print() supports the keyword argument "flush" (see documentation):

print('Hello World!', flush=True)

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

How to HTML encode/escape a string? Is there a built-in?

In Ruby on Rails 3 HTML will be escaped by default.

For non-escaped strings use:

<%= raw "<p>hello world!</p>" %>

How to add 'libs' folder in Android Studio?

Another strange thing. You wont see the libs folder in Android Studio, unless you have at least 1 file in the folder. So, I had to go to the libs folder using File Explorer, and then place the jar file there. Then, it showed up in Android Studio.

How to make button look like a link?

try using the css pseudoclass :focus

input[type="button"], input[type="button"]:focus {
  /* your style goes here */
}

edit as for links and onclick events use (you shouldn’t use inline javascript eventhandlers, but for the sake of simplicity i will use them here):

<a href="some/page.php" title="perform some js action" onclick="callFunction(this.href);return false;">watch and learn</a>

with this.href you can even access the target of the link in your function. return false will just prevent browsers from following the link when clicked.

if javascript is disabled the link will work as a normal link and just load some/page.php—if you want your link to be dead when js is disabled use href="#"

Retrieving a Foreign Key value with django-rest-framework serializers

This solution is better because of no need to define the source model. But the name of the serializer field should be the same as the foreign key field name

class ItemSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(read_only=True, slug_field='title')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category')

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I had kind of the same problem and after going carefully against all charsets and finding that they were all right, I realized that the bugged property I had in my class was annotated as @Column instead of @JoinColumn (javax.presistence; hibernate) and it was breaking everything up.

What happens when a duplicate key is put into a HashMap?

By definition, the put command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types).

The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or null if none present), so you can determine what was there and maintain a reference if necessary.

More information here: HashMap Doc

Searching a list of objects in Python

You can get a list of all matching elements with a list comprehension:

[x for x in myList if x.n == 30]  # list of all elements with .n==30

If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do

def contains(list, filter):
    for x in list:
        if filter(x):
            return True
    return False

if contains(myList, lambda x: x.n == 3)  # True if any element has .n==3
    # do stuff

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Use a virtual machine. Start fresh as often as you want, and stop doing these hacks that may or may not simulate a clean machine.

Seriously, use VMWare or VirtualPC.

how to check if a datareader is null or empty

I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:

DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");

using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.

Adding Table rows Dynamically in Android

You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:

    public void init(){
    TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);


    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        checkBox = new CheckBox(this);
        tv = new TextView(this);
        addBtn = new ImageButton(this);
        addBtn.setImageResource(R.drawable.add);
        minusBtn = new ImageButton(this);
        minusBtn.setImageResource(R.drawable.minus);
        qty = new TextView(this);
        checkBox.setText("hello");
        qty.setText("10");
        row.addView(checkBox);
        row.addView(minusBtn);
        row.addView(qty);
        row.addView(addBtn);
        ll.addView(row,i);
    }
}

Why is json_encode adding backslashes?

I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.

Here is what was happening. If you do:

$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);

The result is:

["{\"test\":\"2\"}","{\"test\":\"four\"}"]

So, what you actually need to do is:

$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);

And this will return

[{"test":"2"},{"test":"four"}]

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

  1. The accepted answer is one way of fixing the issue, because it will just apply some strategy for the problematic dependency (com.google.code.findbugs:jsr305) and it will resolve the problem around the project, using some version of this dependency. Basically it will align the versions of this library inside the whole project.

  2. There is an answer from @Santhosh (and couple of other people) who suggests to exclude the same dependency for espresso, which should work by the same way, but if the project has some other dependencies who depend on the same library (com.google.code.findbugs:jsr305), again we will have the same issue. So in order to use this approach you will need to exclude the same group from all project dependencies, who depend on com.google.code.findbugs:jsr305. I personally found that Espresso Contrib and Espresso Intents also use com.google.code.findbugs:jsr305.

I hope this thoughts will help somebody to realise what exactly is happening here and how things work (not just copy paste some code) :).

How do I set a fixed background image for a PHP file?

It's not a good coding to put PHP code into CSS

body
{
    background-image:url('bg.png');
}

that's it

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

I'd do

for i in `seq 0 2 10`; do echo $i; done

(though of course seq 0 2 10 will produce the same output on its own).

Note that seq allows floating-point numbers (e.g., seq .5 .25 3.5) but bash's brace expansion only allows integers.

Check if a file exists or not in Windows PowerShell?

You can use the Test-Path cmd-let. So something like...

if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
    Write-Host "$file doesn't exist in both locations."
}

link_to image tag. how to add class to a tag

Just adding that you can pass the link_to method a block:

<%= link_to href: 'http://www.example.com/' do %>
    <%= image_tag 'happyface.png', width: 136, height: 67, alt: 'a face that is unnervingly happy'%>
<% end %>

results in:

<a href="/?href=http%3A%2F%2Fhttp://www.example.com/k%2F">
    <img alt="a face that is unnervingly happy" height="67" src="/assets/happyface.png" width="136">
</a>

This has been a life saver when the designer has given me complex links with fancy css3 roll-over effects.

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Also make sure php is enabled by uncommenting the

LoadModule php5_module libexec/apache2/libphp5.so

line that comes right after

LoadModule rewrite_module libexec/apache2/mod_rewrite.so

Make sure both those lines in

/etc/apache2/httpd.conf

are uncommented.

CSS to hide INPUT BUTTON value text

This following has worked best for me:

HTML:

<input type="submit"/>

CSS:

input[type=submit] {
    background: url(http://yourURLhere) no-repeat;
    border: 0;
    display: block;
    font-size:0;
    height: 38px;
    width: 171px;
}

If you don't set value on your <input type="submit"/> it will place the default text "Submit" inside your button. SO, just set the font-size: 0; on your submit and then make sure you set a height and width for your input type so that your image will display. DON'T forget media queries for your submit if you need them, for example:

CSS:

@media (min-width:600px) {
  input[type=submit] {
    width:200px;
    height: 44px;
  }
}

This means when the screen is at exactly 600px wide or greater the button will change it's dimensions

How to trim white space from all elements in array?

String val = "hi hello prince";
String arr[] = val.split(" ");

for (int i = 0; i < arr.length; i++)
{   
     System.out.print(arr[i]);
}

write newline into a file

Files.write(Paths.get(filepath),texttobewrittentofile,StandardOpenOption.APPEND ,StandardOpenOption.CREATE);    

This creates a file, if it does not exist If files exists, it is uses the existing file and text is appended If you want everyline to be written to the next line add lineSepartor for newline into file.

String texttobewrittentofile = text + System.lineSeparator();

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

How do I pass a method as a parameter in Python

Yes; functions (and methods) are first class objects in Python. The following works:

def foo(f):
    print "Running parameter f()."
    f()

def bar():
    print "In bar()."

foo(bar)

Outputs:

Running parameter f().
In bar().

These sorts of questions are trivial to answer using the Python interpreter or, for more features, the IPython shell.

Best way to add Activity to an Android project in Eclipse?

I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

Create instance of generic type in Java?

As you said, you can't really do it because of type erasure. You can sort of do it using reflection, but it requires a lot of code and lot of error handling.

Bootstrap 4, how to make a col have a height of 100%?

Although it is not a good solution but may solve your problem. You need to use position absolute in #yellow element!

_x000D_
_x000D_
#yellow {height: 100%; background: yellow; position: absolute; top: 0px; left: 0px;}_x000D_
.container-fluid {position: static !important;}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<div class="container-fluid">_x000D_
  <div class="row justify-content-center">_x000D_
_x000D_
    <div class="col-4" id="yellow">_x000D_
      XXXX_x000D_
    </div>_x000D_
_x000D_
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">_x000D_
      Form Goes Here_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

C++ vector of char array

In fact technically you can store C++ arrays in a vector, and it makes a lot of sense. Not directly, but by a simple workaround, wrapping in a class, will meet exactly all the requirements of a multidimensional array. As the question is already answered by anon. Some explanations steel needed. STL already provides std::array for these purposes.
Is an unpleasant surprise to fall in the trap of not understanding clearly the difference between arrays and pointers, between multidimensional arrays and arrays of arrays, and so on and so on. Vectors of vectors contains vectors as elements. Each element containing a copy of size, capacity and maybe other things, meanwhile the vector datas for elements will be placed in different random places in memory. But a vector of arrays will contain a contiguous segment of memory with all data, which is identical to multidimensional array. Also there is no good reason to keep the size of each array element while it is known to be the same for all elements. So, making a vector of array, you can't do it directly. But you can workaround it easily by wrapping the array in a class, and in this sample the memory will be identical to the memory of a bidimensional array. This approach is already widely used by many libraries. At low level it will be easily interoperable with APIs that are not C++ vector aware. So without using std::array it will look like this:

int main()
{
    struct ss
    {
        int a[5];
        int& operator[] (const int& i) { return a[i]; }
    } a{ 1,2,3,4,5 }, b{ 9,8,7,6,5 };

    vector<ss> v;
    v.resize(10);
    v[0] = a;
    v[1] = b;
    v.push_back(a); // will push to index 10, with reallocation
    v.push_back(b); // will push to index 11, with reallocation

    auto d = v.data();
    // cin >> v[1][3]; //input any element from stdin
    cout << "show two element: "<< v[1][2] <<":"<< v[1][3] << endl;
    return 0;
}

Since C++11 STL contains std::array for these purposes, so no need to reinvent it:

....
#include<array>
....
int main()
{
    vector<array<int, 5>> v;
    v.reserve(10);
    v.resize(2);
    v[0] = array<int, 5> {1, 2, 3, 4, 5};
    v[1] = array<int, 5> {9, 8, 7, 6, 5};
    v.emplace_back(array<int, 5>{ 7, 2, 53, 4, 5 });
    ///cin >> v[1][1];
    auto d = v.data();

Now look how looks in memory


Now, this is why vectors of vectors is not the answer. Supposing following code

int main()
{
    vector<vector<int>> vv = { { 1,2,3,4,5 }, { 9,8,7,6,5 } };
    auto dd = vv.data();
    return 0;
}

Guess what it looks like in the memory now

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

Django set field value after a form is initialized

To throw yet another way into the mix: this works too, with a bit more modern notation. It just works around the fact that a QueryDict is immutable.

>>> the_form.data = {**f.data.dict(), 'some_field': 47}
>>> the_form['some_field'].as_widget()
'<input type="hidden" name="some_field" value="47"
        class="field-some_field" id="id_some_field">'

How can we generate getters and setters in Visual Studio?

I use Visual Studio 2013 Professional.

  • Place your cursor at the line of an instance variable.

    Enter image description here

  • Press combine keys Ctrl + R, Ctrl + E, or click the right mouse button. Choose context menu RefactorEncapsulate Field..., and then press OK.

    Enter image description here

  • In Preview Reference Changes - Encapsulate Field dialog, press button Apply.

    Enter image description here

  • This is result:

    Enter image description here



You also place the cursor for choosing a property. Use menu EditRefactorEncapsulate Field...

  • Other information:

    Since C# 3.0 (November 19th 2007), we can use auto-implemented properties (this is merely syntactic sugar).

    And

    private int productID;
    
    public int ProductID
    {
        get { return productID; }
        set { productID = value; }
    }
    

    becomes

    public int ProductID { get; set; }
    

Select single item from a list

Use the FirstOrDefault selector.

var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var firstEven = list.FirstOrDefault(n => n % 2 == 0);

if (firstEven == 0)
    Console.WriteLine("no even number");
else 
    Console.WriteLine("first even number is {0}", firstEven);

Just pass in a predicate to the First or FirstOrDefault method and it'll happily go round' the list and picks the first match for you.

If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.

Hope this helps :-)

How to get response status code from jQuery.ajax?

Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete() method of jquery ajax. I quote the notice on jquery website here:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

To know the status code of a ajax response, one can use the following code:

$.ajax( url [, settings ] )
.always(function (jqXHR) {
    console.log(jqXHR.status);
});

Works similarily for .done() and .fail()

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Adding image inside table cell in HTML

This worked for me:-

 <!DOCTYPE html> 
  <html>
  <head>
<title>CAR APPLICATION</title>
 </head>
 <body>
<center>
    <h1>CAR APPLICATION</h1>
</center>

<table border="5" bordercolor="red" align="center">
    <tr>
        <th colspan="3">ABCD</th> 
    </tr>
    <tr>
        <th>Name</th>
        <th>Origin</th>
        <th>Photo</th>
    </tr>
    <tr>
        <td>Bugatti Veyron Super Sport</th>
        <td>Molsheim, Alsace, France</th>
                <!-- considering it is on the same folder that .html file -->
        <td><img src=".\A.jpeg" alt="" border=3 height=100 width=300></img></th>
    </tr>
    <tr>
        <td>SSC Ultimate Aero TT  TopSpeed</th>
        <td>United States</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td>Koenigsegg CCX</th>
        <td>Ängelholm, Sweden</th>
        <td border=4 height=100 width=300>Photo1</th>
    </tr>
    <tr>
        <td>Saleen S7</th>
        <td>Irvine, California, United States</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td> McLaren F1</th>
        <td>Surrey, England</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td>Ferrari Enzo</th>
        <td>Maranello, Italy</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
    <tr>
        <td> Pagani Zonda F Clubsport</th>
        <td>Modena, Italy</th>
        <td border=3 height=100 width=100>Photo1</th>
    </tr>
</table>
  </body>
  <html>

How to create a timeline with LaTeX?

If you are looking for UML sequence diagrams, you might be interested in pkf-umlsd, which is based on TiKZ. Nice demos can be found here.

How to find locked rows in Oracle

The below PL/SQL block finds all locked rows in a table. The other answers only find the blocking session, finding the actual locked rows requires reading and testing each row.

(However, you probably do not need to run this code. If you're having a locking problem, it's usually easier to find the culprit using GV$SESSION.BLOCKING_SESSION and other related data dictionary views. Please try another approach before you run this abysmally slow code.)

First, let's create a sample table and some data. Run this in session #1.

--Sample schema.
create table test_locking(a number);
insert into test_locking values(1);
insert into test_locking values(2);
commit;
update test_locking set a = a+1 where a = 1;

In session #2, create a table to hold the locked ROWIDs.

--Create table to hold locked ROWIDs.
create table locked_rowids(the_rowid rowid);
--Remove old rows if table is already created:
--delete from locked_rowids;
--commit;

In session #2, run this PL/SQL block to read the entire table, probe each row, and store the locked ROWIDs. Be warned, this may be ridiculously slow. In your real version of this query, change both references to TEST_LOCKING to your own table.

--Save all locked ROWIDs from a table.
--WARNING: This PL/SQL block will be slow and will temporarily lock rows.
--You probably don't need this information - it's usually good enough to know
--what other sessions are locking a statement, which you can find in
--GV$SESSION.BLOCKING_SESSION.
declare
    v_resource_busy exception;
    pragma exception_init(v_resource_busy, -00054);
    v_throwaway number;
    type rowid_nt is table of rowid;
    v_rowids rowid_nt := rowid_nt();
begin
    --Loop through all the rows in the table.
    for all_rows in
    (
        select rowid
        from test_locking
    ) loop
        --Try to look each row.
        begin
            select 1
            into v_throwaway
            from test_locking
            where rowid = all_rows.rowid
            for update nowait;
        --If it doesn't lock, then record the ROWID.
        exception when v_resource_busy then
            v_rowids.extend;
            v_rowids(v_rowids.count) := all_rows.rowid;
        end;

        rollback;
    end loop;

    --Display count:
    dbms_output.put_line('Rows locked: '||v_rowids.count);

    --Save all the ROWIDs.
    --(Row-by-row because ROWID type is weird and doesn't work in types.)
    for i in 1 .. v_rowids.count loop
        insert into locked_rowids values(v_rowids(i));
    end loop;
    commit;
end;
/

Finally, we can view the locked rows by joining to the LOCKED_ROWIDS table.

--Display locked rows.
select *
from test_locking
where rowid in (select the_rowid from locked_rowids);


A
-
1

jQuery $.ajax(), pass success data into separate function

Works fine for me:

<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
    alert(data + "\t" + textStatus);
}

var test = function(str, cb) {
    var data = 'Input values';
    $.ajax({
        type: 'post',
        url: 'http://www.mydomain.com/ajaxscript',
        data: data,
        success: cb
    });
}
test('Hello, world', callback);
</script>

How to suspend/resume a process in Windows?

I use (a very old) process explorer from SysInternals (procexp.exe). It is a replacement / addition to the standard Task manager, you can suspend a process from there.

Edit: Microsoft has bought over SysInternals, url: procExp.exe

Other than that you can set the process priority to low so that it does not get in the way of other processes, but this will not suspend the process.

Task vs Thread differences

The Thread class is used for creating and manipulating a thread in Windows.

A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

In the days of old (i.e. before TPL) it used to be that using the Thread class was one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool), however this was cumbersome and had several disadvantages, not least of which was the performance overhead of creating a whole new thread to perform a task in the background.

Nowadays using tasks and the TPL is a far better solution 90% of the time as it provides abstractions which allows far more efficient use of system resources. I imagine there are a few scenarios where you want explicit control over the thread on which you are running your code, however generally speaking if you want to run something asynchronously your first port of call should be the TPL.

How to get the range of occupied cells in excel sheet

You should try the currentRegion property, if you know from where you are to find the range. This will give you the boundaries of your used range.

How to create separate AngularJS controller files?

Using the angular.module API with an array at the end will tell angular to create a new module:

myApp.js

// It is like saying "create a new module"
angular.module('myApp.controllers', []); // Notice the empty array at the end here

Using it without the array is actually a getter function. So to seperate your controllers, you can do:

Ctrl1.js

// It is just like saying "get this module and create a controller"
angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

During your javascript imports, just make sure myApp.js is after AngularJS but before any controllers / services / etc...otherwise angular won't be able to initialize your controllers.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

On Gradle 5.x I use:

wrapper {
    gradleVersion = '5.5.1'
}

How do you get the contextPath from JavaScript, the right way?

I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.

You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:

function getContextPath() {
   return "<%=request.getContextPath()%>";
}

It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.

At this point I agree with @BalusC to use EL:

function getContextPath() {
   return "${pageContext.request.contextPath}";
}

or depending on the version of JSP fallback to JSTL:

function getContextPath() {
   return "<c:out value="${pageContext.request.contextPath}" />";
}

How to solve "Fatal error: Class 'MySQLi' not found"?

I found a solution for this problem after a long analysing procedure. After properly testing my php installation with the command line features I found out that the php is working well and could work with the mysql database. Btw. you can run code-files with php code with the command php -f filename.php
So I realized, it must something be wrong with the Apache.
I made a file with just the phpinfo() function inside.
Here I saw, that in the line
Loaded Configuration File
my config file was not loaded, instead there was mentioned (none).

Finally I found within the Apache configuration the entry

<IfModule php5_module>
    PHPINIDir "C:/xampp/php"
</IfModule>

But I've installed the PHP 7 and so the Apache could not load the php.ini file because there was no entry for that. I added

<IfModule php7_module>
    PHPINIDir "C:/xampp/php"
</IfModule>

and after restart Apache all works well.

These code blocks above I found in my httpd-xampp.conf file. May it is somewhere else at your configuration.
In the same file I had changed before the settings for the php 7 as replacement for the php 5 version.

#
# PHP-Module setup
#
#LoadFile "C:/xampp/php/php5ts.dll"
#LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"
LoadFile "C:/xampp/php/php7ts.dll"
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

As you can see I have the xampp package installed but this problem was just on the Apache side.

Windows batch files: .bat vs .cmd?

.cmd and .bat file execution is different because in a .cmd errorlevel variable it can change on a command that is affected by command extensions. That's about it really.

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

    
_x000D_
_x000D_
    /* add javascript*/_x000D_
    {_x000D_
    document.getElementById('abc 1').style.display='none';_x000D_
    }_x000D_
   /* after that add html*/_x000D_
   
_x000D_
    <html>_x000D_
    <head>_x000D_
    <title>...</title>_x000D_
    </head>_x000D_
    <body>_x000D_
    <table border = 2>_x000D_
    <tr id = "abc 1">_x000D_
    <td>abcd</td>_x000D_
    </tr>_x000D_
    <tr id ="abc 2">_x000D_
    <td>efgh</td>_x000D_
    </tr>_x000D_
    </table>_x000D_
    </body>_x000D_
    </html>_x000D_
_x000D_
    
_x000D_
_x000D_
_x000D_

typedef fixed length array

The typedef would be

typedef char type24[3];

However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.

A better solution would be

typedef struct type24 { char x[3]; } type24;

You probably also want to be using unsigned char instead of char, since the latter has implementation-defined signedness.

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

Package structure for a Java project?

The way i usually have my hierarchy of folder-

  • Project Name
    • src
    • bin
    • tests
    • libs
    • docs

Error in Swift class: Property not initialized at super.init call

Swift will not allow you to initialise super class with out initialising the properties, reverse of Obj C. So you have to initialise all properties before calling "super.init".

Please go to http://blog.scottlogic.com/2014/11/20/swift-initialisation.html. It gives a nice explanation to your problem.

React Native TextInput that only accepts numeric characters

Using a RegExp to replace any non digit is faster than using a for loop with a whitelist, like other answers do.

Use this for your onTextChange handler:

onChanged (text) {
    this.setState({
        mobile: text.replace(/[^0-9]/g, ''),
    });
}

Performance test here: https://jsperf.com/removing-non-digit-characters-from-a-string

Check whether there is an Internet connection available on Flutter app

The connectivity plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet

Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

You can use

import 'dart:io';
...
try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}

equivalent of vbCrLf in c#

Add a reference to Microsoft.VisualBasic to your project.

Then insert the using statement

using Microsoft.VisualBasic;

Use the defined constant vbCrLf:

private const string myString = "abc" + Constants.vbCrLf;

How to SFTP with PHP?

I found that "phpseclib" should help you with this (SFTP and many more features). http://phpseclib.sourceforge.net/

To Put the file to the server, simply call (Code example from http://phpseclib.sourceforge.net/sftp/examples.html#put)

<?php
include('Net/SFTP.php');

$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
    exit('Login Failed');
}

// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);

Nullable property to entity field, Entity Framework through Code First

In Ef .net core there are two options that you can do; first with data annotations:

public class Blog
{
    public int BlogId { get; set; }
    [Required]
    public string Url { get; set; }
}

Or with fluent api:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired(false)//optinal case
            .IsRequired()//required case
            ;
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

There are more details here

Read CSV with Scanner()

scanner.useDelimiter(",");

This should work.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class TestScanner {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("/Users/pankaj/abc.csv"));
        scanner.useDelimiter(",");
        while(scanner.hasNext()){
            System.out.print(scanner.next()+"|");
        }
        scanner.close();
    }

}

For CSV File:

a,b,c d,e
1,2,3 4,5
X,Y,Z A,B

Output is:

a|b|c d|e
1|2|3 4|5
X|Y|Z A|B|

How to use Angular4 to set focus by element id

One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:

const element = this.renderer.selectRootElement('#input1');

// setTimeout(() => element.focus, 0);
setTimeout(() => element.focus(), 0);

Thank you @MrBlaise for the solution!

Screenshot sizes for publishing android app on Google Play

At last! I got the answer to this, the size to edit it in photoshop is: 379x674

You are welcome

Why can't I inherit static classes?

You can do something that will look like static inheritance.

Here is the trick:

public abstract class StaticBase<TSuccessor>
    where TSuccessor : StaticBase<TSuccessor>, new()
{
    protected static readonly TSuccessor Instance = new TSuccessor();
}

Then you can do this:

public class Base : StaticBase<Base>
{
    public Base()
    {
    }

    public void MethodA()
    {
    }
}

public class Inherited : Base
{
    private Inherited()
    {
    }

    public new static void MethodA()
    {
        Instance.MethodA();
    }
}

The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.

There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.

P.S. We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.

Cannot call getSupportFragmentManager() from activity

extend class to AppCompatActivity instead of Activity

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

button image as form input submit button?

Make the submit button the main image you are using. So the form tags would come first then submit button which is your only image so the image is your clickable image form. Then just make sure to put whatever you are passing before the submit button code.

How to change Visual Studio 2012,2013 or 2015 License Key?

The solution with removing the license information from the registry also works with Visual Studio 2013, but as described in the answer above, it is important to execute a "repair" on Visual Studio.

ng-change get new value and original value

Just keep a currentValue variable in your controller that you update on every change. You can then compare that to the new value every time before you update it.'

The idea of using a watch is good as well, but I think a simple variable is the simplest and most logical solution.

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

Read environment variables in Node.js

To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.

Avoid Boolean Logic

Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.

if (process.env.SHOULD_SEND) {
 mailer.send();
} else {
  console.log("this won't be reached with values like false and 0");
}

Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.

 db.connect({
  debug: process.env.NODE_ENV === 'development'
 });

How do I import other TypeScript files?

From TypeScript version 1.8 you can use simple import statements just like in ES6:

import { ZipCodeValidator } from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();

https://www.typescriptlang.org/docs/handbook/modules.html

Old answer: From TypeScript version 1.5 you can use tsconfig.json: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

It completely eliminates the need of the comment style referencing.

Older answer:

You need to reference the file on the top of the current file.

You can do this like this:

/// <reference path="../typings/jquery.d.ts"/>
/// <reference path="components/someclass.ts"/>

class Foo { }

etc.

These paths are relative to the current file.

Your example:

/// <reference path="moo.ts"/>

class bar extends moo.foo
{
}

How to automatically start a service when running a docker container?

docker export -o <nameOfContainer>.tar <nameOfContainer>

Might need to prune the existing container using docker prune ...

Import with required modifications:

cat <nameOfContainer>.tar | docker import -c "ENTRYPOINT service mysql start && /bin/bash" - <nameOfContainer>

Run the container for example with always restart option to make sure it will auto resume after host/daemon recycle:

docker run -d -t -i --restart always --name <nameOfContainer> <nameOfContainer> /bin/bash

Side note: In my opinion reasonable is to start only cron service leaving container as clean as possible then just modify crontab or cron.hourly, .daily etc... with corresponding checkup/monitoring scripts. Reason is You rely only on one daemon and in case of changes it is easier with ansible or puppet to redistribute cron scripts instead of track services that start at boot.

ArrayList of int array in java

You have to use <Integer> instead of <int>:

int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
    arl.add(i);        
    System.out.println("Arraylist contains:" + arl.get(0));
}

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

This is how you can read data from .csv file using OLEDB provider.

  If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
        Try
            Dim fi As New FileInfo(OpenFileDialog1.FileName)
            Dim sConnectionStringz As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
            Dim objConn As New OleDbConnection(sConnectionStringz)
            objConn.Open()
            'DataGridView1.TabIndex = 1
            Dim objCmdSelect As New OleDbCommand("SELECT * FROM " & fi.Name, objConn)
            Dim objAdapter1 As New OleDbDataAdapter
            objAdapter1.SelectCommand = objCmdSelect
            Dim objDataset1 As New DataSet
            objAdapter1.Fill(objDataset1)

            '--objAdapter1.Update(objDataset1) '--updating
            DataGridView1.DataSource = objDataset1.Tables(0).DefaultView
        Catch ex as Exception
           MsgBox("Error: " + ex.Message)
        Finally
            objConn.Close()
        End Try
    End If