Programs & Examples On #Select

Select is a common keyword used to query data. 'select()' is also a programming function for triggering code based on file handle or other system activity. Not to be confused with the HTML `select` tag, use [html-select] for that.

jQuery: Best practice to populate drop down?

Sure - make options an array of strings and use .join('') rather than += every time through the loop. Slight performance bump when dealing with large numbers of options...

var options = [];
$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        options.push('<option value="',
          result[i].ImageFolderID, '">',
          result[i].Name, '</option>');
    }
    $("#theSelect").html(options.join(''));
});

Yes. I'm still working with strings the whole time. Believe it or not, that's the fastest way to build a DOM fragment... Now, if you have only a few options, it won't really matter - use the technique Dreas demonstrates if you like the style. But bear in mind, you're invoking the browser's internal HTML parser i*2 times, rather than just once, and modifying the DOM each time through the loop... with a sufficient number of options. you'll end up paying for it, especially on older browsers.

Note: As Justice points out, this will fall apart if ImageFolderID and Name are not encoded properly...

SELECT INTO Variable in MySQL DECLARE causes syntax error?

Per the MySQL docs DECLARE works only at the start of a BEGIN...END block as in a stored program.

Datatable select with multiple conditions

    protected void FindCsv()
    {
        string strToFind = "2";

        importFolder = @"C:\Documents and Settings\gmendez\Desktop\";

        fileName = "CSVFile.csv";

        connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
        conn = new OdbcConnection(connectionString);

        System.Data.Odbc.OdbcDataAdapter  da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dt.Columns[0].ColumnName = "id";

        DataRow[] dr = dt.Select("id=" + strToFind);

        Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());
    }

SQL: how to use UNION and order by a specific select?

@Adrian's answer is perfectly suitable, I just wanted to share another way of achieving the same result:

select nvl(a.id, b.id)
from a full outer join b on a.id = b.id
order by b.id;

How to add results of two select commands in same query

Repeat for Multiple aggregations like:

SELECT sum(AMOUNT) AS TOTAL_AMOUNT FROM ( 
    SELECT AMOUNT FROM table_1
    UNION ALL 
    SELECT AMOUNT FROM table_2 
    UNION ALL 
    SELECT ASSURED_SUM FROM table_3
)

Select arrow style change

You can also try this:

Heres a Picture of it!

And also run code snippet!

CSS and then HTML:

_x000D_
_x000D_
           #select-category {
            font-size: 100%;
            padding: 10px;
            padding-right: 180px;
            margin-left: 30px;
            border-radius: 1000000px;
            border: 1px solid #707070;
            outline: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background: transparent;
            background-image: url("data:image/svg+xml;utf8,<svg fill='black' height='34' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/><path d='M0 0h24v24H0z' fill='none'/></svg>");
            background-repeat: no-repeat;
            background-position-x: 100%;
            background-position-y: 5px;
            margin-right: 2rem;
        }
_x000D_
                <select id="select-category">
                    <option>Category</option>
                    <option>Category 2</option>
                    <option>Category 3</option>
                    <option>Category 4</option>
                    <option>Category 5</option>
                    <option>Category 6</option>
                    <option>Category 7</option>
                    <option>Category 8</option>
                    <option>Category 9</option>
                    <option>Category 10</option>
                    <option>Category 11</option>
                    <option>Category 12</option>
                </select>
_x000D_
_x000D_
_x000D_

CodeIgniter Select Query

Here is the example of the code:

public function getItemName()
{
    $this->db->select('Id,Name');
    $this->db->from('item');
    $this->db->where(array('Active' => 1));
    return $this->db->get()->result();
}

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

Select 2 columns in one and combine them

Yes,

SELECT CONCAT(field1, field2) AS WHOLENAME FROM TABLE
WHERE ...

will result in data set like:

WHOLENAME
field1field2

How do I select an element in jQuery by using a variable for the ID?

row = $("body").find('#' + row_id);

More importantly doing the additional body.find has no impact on performance. The proper way to do this is simply:

row = $('#' + row_id);

Jquery- Get the value of first td in table

This should work:

$(".hit").click(function(){    
   var value=$(this).closest('tr').children('td:first').text();
   alert(value);    
});

Explanation:

  • .closest('tr') gets the nearest ancestor that is a <tr> element (so in this case the row where the <a> element is in).
  • .children('td:first') gets all the children of this element, but with the :first selector we reduce it to the first <td> element.
  • .text() gets the text inside the element

As you can see from the other answers, there is more than only one way to do this.

Python: Tuples/dictionaries as keys, select, sort

Database, dict of dicts, dictionary of list of dictionaries, named tuple (it's a subclass), sqlite, redundancy... I didn't believe my eyes. What else ?

"It might well be that dictionaries with tuples as keys are not the proper way to handle this situation."

"my gut feeling is that a database is overkill for the OP's needs; "

Yeah! I thought

So, in my opinion, a list of tuples is plenty enough :

from operator import itemgetter

li = [  ('banana',     'blue'   , 24) ,
        ('apple',      'green'  , 12) ,
        ('strawberry', 'blue'   , 16 ) ,
        ('banana',     'yellow' , 13) ,
        ('apple',      'gold'   , 3 ) ,
        ('pear',       'yellow' , 10) ,
        ('strawberry', 'orange' , 27) ,
        ('apple',      'blue'   , 21) ,
        ('apple',      'silver' , 0 ) ,
        ('strawberry', 'green'  , 4 ) ,
        ('banana',     'brown'  , 14) ,
        ('strawberry', 'yellow' , 31) ,
        ('apple',      'pink'   , 9 ) ,
        ('strawberry', 'gold'   , 0 ) ,
        ('pear',       'gold'   , 66) ,
        ('apple',      'yellow' , 9 ) ,
        ('pear',       'brown'  , 5 ) ,
        ('strawberry', 'pink'   , 8 ) ,
        ('apple',      'purple' , 7 ) ,
        ('pear',       'blue'   , 51) ,
        ('chesnut',    'yellow',  0 )   ]


print set( u[1] for u in li ),': all potential colors'
print set( c for f,c,n in li if n!=0),': all effective colors'
print [ c for f,c,n in li if f=='banana' ],': all potential colors of bananas'
print [ c for f,c,n in li if f=='banana' and n!=0],': all effective colors of bananas'
print

print set( u[0] for u in li ),': all potential fruits'
print set( f for f,c,n in li if n!=0),': all effective fruits'
print [ f for f,c,n in li if c=='yellow' ],': all potential fruits being yellow'
print [ f for f,c,n in li if c=='yellow' and n!=0],': all effective fruits being yellow'
print

print len(set( u[1] for u in li )),': number of all potential colors'
print len(set(c for f,c,n in li if n!=0)),': number of all effective colors'
print len( [c for f,c,n in li if f=='strawberry']),': number of potential colors of strawberry'
print len( [c for f,c,n in li if f=='strawberry' and n!=0]),': number of effective colors of strawberry'
print

# sorting li by name of fruit
print sorted(li),'  sorted li by name of fruit'
print

# sorting li by number 
print sorted(li, key = itemgetter(2)),'  sorted li by number'
print

# sorting li first by name of color and secondly by name of fruit
print sorted(li, key = itemgetter(1,0)),'  sorted li first by name of color and secondly by name of fruit'
print

result

set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange', 'silver']) : all potential colors
set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange']) : all effective colors
['blue', 'yellow', 'brown'] : all potential colors of bananas
['blue', 'yellow', 'brown'] : all effective colors of bananas

set(['strawberry', 'chesnut', 'pear', 'banana', 'apple']) : all potential fruits
set(['strawberry', 'pear', 'banana', 'apple']) : all effective fruits
['banana', 'pear', 'strawberry', 'apple', 'chesnut'] : all potential fruits being yellow
['banana', 'pear', 'strawberry', 'apple'] : all effective fruits being yellow

9 : number of all potential colors
8 : number of all effective colors
6 : number of potential colors of strawberry
5 : number of effective colors of strawberry

[('apple', 'blue', 21), ('apple', 'gold', 3), ('apple', 'green', 12), ('apple', 'pink', 9), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'blue', 24), ('banana', 'brown', 14), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'blue', 51), ('pear', 'brown', 5), ('pear', 'gold', 66), ('pear', 'yellow', 10), ('strawberry', 'blue', 16), ('strawberry', 'gold', 0), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('strawberry', 'pink', 8), ('strawberry', 'yellow', 31)]   sorted li by name of fruit

[('apple', 'silver', 0), ('strawberry', 'gold', 0), ('chesnut', 'yellow', 0), ('apple', 'gold', 3), ('strawberry', 'green', 4), ('pear', 'brown', 5), ('apple', 'purple', 7), ('strawberry', 'pink', 8), ('apple', 'pink', 9), ('apple', 'yellow', 9), ('pear', 'yellow', 10), ('apple', 'green', 12), ('banana', 'yellow', 13), ('banana', 'brown', 14), ('strawberry', 'blue', 16), ('apple', 'blue', 21), ('banana', 'blue', 24), ('strawberry', 'orange', 27), ('strawberry', 'yellow', 31), ('pear', 'blue', 51), ('pear', 'gold', 66)]   sorted li by number

[('apple', 'blue', 21), ('banana', 'blue', 24), ('pear', 'blue', 51), ('strawberry', 'blue', 16), ('banana', 'brown', 14), ('pear', 'brown', 5), ('apple', 'gold', 3), ('pear', 'gold', 66), ('strawberry', 'gold', 0), ('apple', 'green', 12), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('apple', 'pink', 9), ('strawberry', 'pink', 8), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'yellow', 10), ('strawberry', 'yellow', 31)]   sorted li first by name of color and secondly by name of fruit

MySQL - How to select data by string length

select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*

Example if you want to select from customer the entry's with a name shorter then 2 chars.

select * from customer where 1 **having length(name)<2**

MySQL Query - Records between Today and Last 30 Days

For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

MySQL - DATE_ADD month interval

Well, for me this is the expected result; adding six months to Jan. 1st July.

mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01                                 | 
+--------------------------------------------+

Best way to do nested case statement logic in SQL Server

This example might help you, the picture shows how SQL case statement will look like when there are if and more than one inner if loops

enter image description here

Select objects based on value of variable in object using jq

To obtain a stream of just the names:

$ jq '.[] | select(.location=="Stockholm") | .name' json

produces:

"Donald"
"Walt"

To obtain a stream of corresponding (key name, "name" attribute) pairs, consider:

$ jq -c 'to_entries[]
        | select (.value.location == "Stockholm")
        | [.key, .value.name]' json

Output:

["FOO","Donald"]
["BAR","Walt"]

SQL: How To Select Earliest Row

Simply use min()

SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

How to remove all options from a dropdown using jQuery / JavaScript

In case .empty() doesn't work for you, which is for me

function SetDropDownToEmpty() 
{           
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");          
}

$(document).ready(
SetDropDownToEmpty() ;
)

How can I select from list of values in Oracle

Starting from Oracle 12.2, you don't need the TABLE function, you can directly select from the built-in collection.

SQL> select * FROM sys.odcinumberlist(5,2,6,3,78);

COLUMN_VALUE
------------
           5
           2
           6
           3
          78

SQL> select * FROM sys.odcivarchar2list('A','B','C','D');

COLUMN_VALUE
------------
A
B
C
D

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

Can I apply the required attribute to <select> fields in HTML5?

You can do it also dynamically with JQuery

Set required

$("#select1").attr('required', 'required');

Remove required

$("#select1").removeAttr('required');

SQLite select where empty?

It looks like you can simply do:

SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';

Test case:

CREATE TABLE your_table (id int, some_column varchar(10));

INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);

Result:

SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';

id        
----------
1         
2         
5    

How can I set the background color of <option> in a <select> element?

I had this problem too. I found setting the appearance to none helped.

.class {
    appearance:none;
    -moz-appearance:none;
    -webkit-appearance:none;

    background-color: red;
}

Find all stored procedures that reference a specific column in some table

You can use ApexSQL Search, it's a free SSMS and Visual Studio add-in and it can list all objects that reference a specific table column. It can also find data stored in tables and views. You can easily filter the results to show a specific database object type that references the column

enter image description here

Disclaimer: I work for ApexSQL as a Support Engineer

Postgresql column reference "id" is ambiguous

SELECT vg.id, 
       vg.name
  FROM v_groups vg INNER JOIN  
       people2v_groups p2vg ON vg.id = p2vg.v_group_id
 WHERE p2vg.people_id = 0;

MySQL Select all columns from one table and some from another table

I need more information really but it will be along the lines of..

SELECT table1.*, table2.col1, table2.col3 FROM table1 JOIN table2 USING(id)

How to select only the first rows for each unique value of a column?

to get every unique value from your customer table, use

SELECT DISTINCT CName FROM customertable;

more in-depth of w3schools: https://www.w3schools.com/sql/sql_distinct.asp

MySQL "Or" Condition

try this

mysql_query("
SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today'
    OR date='$Date_Yesterday', '$Date_TwoDaysAgo', '$Date_ThreeDaysAgo', '$Date_FourDaysAgo', '$Date_FiveDaysAgo', '$Date_SixDaysAgo', '$Date_SevenDaysAgo'"     
   );

my be like this

 OR date='$Date_Yesterday' oR '$Date_TwoDaysAgo'.........

Select specific row from mysql table

You can add an auto generated id field in the table and select by this id

SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = 3;

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

Links in <select> dropdown options

... or if you want / need to keep your option 'value' as it was, just add a new attribute:

<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>

<script>
document.getElementById('my_selection').onchange = function() {
    window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>

Blank HTML SELECT without blank item in dropdown list

You can by setting selectedIndex to -1 using .prop: http://jsfiddle.net/R9auG/.

For older jQuery versions use .attr instead of .prop: http://jsfiddle.net/R9auG/71/.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Users who have one of the 3 countries

SELECT DISTINCT user_id
FROM table
WHERE ancestry IN('England','France','Germany')

Users who have all 3 countries

SELECT DISTINCT A.userID
FROM table A
   INNER JOIN table B on A.user_id = B.user_id
   INNER JOIN table C on A.user_id = C.user_id
WHERE A.ancestry = 'England'
   AND B.ancestry = 'Germany'
   AND C.ancestry = 'France'

How to preSelect an html dropdown list with php?

I suppose that you are using an array to create your select form input. In that case, use an array:

<?php
    $selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
    $fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
 ?>
  <select name=‘yesnofine'>
 <?php foreach ($fields as $k => $v): ?>
  <option value="<?php echo $k;?>" <?php @print($selected[$k]);?>><?php echo $v;?></options>
 <?php endforeach; ?>
 </select>

If not, you may just unroll the above loop, and still use an array.

 <option value="1" <?php @print($selected[$k]);?>>Yes</options>
 <option value="2" <?php @print($selected[$k]);?>>No</options>
 <option value="3" <?php @print($selected[$k]);?>>Fine</options>

Notes that I don't know:

  • how you are naming your input, so I made up a name for it.
  • which way you are handling your form input on server side, I used $_REQUEST,

You will have to adapt the code to match requirements of the framework you are using, if any.

Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.

Mysql select distinct

You can use group by instead of distinct. Because when you use distinct, you'll get struggle to select all values from table. Unlike when you use group by, you can get distinct values and also all fields in table.

MySQL - Select the last inserted row easiest way

You can use ORDER BY ID DESC, but it's WAY faster if you go that way:

SELECT * FROM bugs WHERE ID = (SELECT MAX(ID) FROM bugs WHERE user = 'me')

In case that you have a huge table, it could make a significant difference.

EDIT

You can even set a variable in case you need it more than once (or if you think it is easier to read).

SELECT @bug_id := MAX(ID) FROM bugs WHERE user = 'me';
SELECT * FROM bugs WHERE ID = @bug_id;

MySQL - UPDATE query based on SELECT Query

UPDATE [table_name] AS T1,
      (SELECT [column_name] 
        FROM [table_name] 
        WHERE [column_name] = [value]) AS T2 
  SET T1.[column_name]=T2.[column_name] + 1
WHERE T1.[column_name] = [value];

Explicitly select items from a list or tuple

list( myBigList[i] for i in [87, 342, 217, 998, 500] )

I compared the answers with python 2.5.2:

  • 19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]

  • 20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))

  • 22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)

  • 24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )

Note that in Python 3, the 1st was changed to be the same as the 4th.


Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:

>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])

The tuple doesn't work the same way as those are slices.

JOIN two SELECT statement results

If Age and Palt are columns in the same Table, you can count(*) all tasks and sum only late ones like this:

select ks,
       count(*) tasks,
       sum(case when Age > Palt then 1 end) late
  from Table
 group by ks

How can I do SELECT UNIQUE with LINQ?

var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();

Proper way of checking if row exists in table in PL/SQL block

select nvl(max(1), 0) from mytable;

This statement yields 0 if there are no rows, 1 if you have at least one row in that table. It's way faster than doing a select count(*). The optimizer "sees" that only a single row needs to be fetched to answer the question.

Here's a (verbose) little example:

declare
  YES constant      signtype := 1;
  NO  constant      signtype := 0;
  v_table_has_rows  signtype;
begin

  select nvl(max(YES), NO)
    into v_table_has_rows
    from mytable -- where ...
  ;

  if v_table_has_rows = YES then
    DBMS_OUTPUT.PUT_LINE ('mytable has at least one row');
  end if;

end;

How to kill a running SELECT statement

As you keep getting pages of results I'm assuming you started the session in SQL*Plus. If so, the easy thing to do is to bash ctrl + break many, many times until it stops.

The more complicated and the more generic way(s) I detail below in order of increasing ferocity / evil. The first one will probably work for you but if it doesn't you can keep moving down the list.

Most of these are not recommended and can have unintended consequences.


1. Oracle level - Kill the process in the database

As per ObiWanKenobi's answer and the ALTER SESSION documentation

alter system kill session 'sid,serial#';

To find the sid, session id, and the serial#, serial number, run the following query - summarised from OracleBase - and find your session:

select s.sid, s.serial#, p.spid, s.username, s.schemaname
     , s.program, s.terminal, s.osuser
  from v$session s
  join v$process p
    on s.paddr = p.addr
 where s.type != 'BACKGROUND'

If you're running a RAC then you need to change this slightly to take into account the multiple instances, inst_id is what identifies them:

select s.inst_id, s.sid, s.serial#, p.spid, s.username
     , s.schemaname, s.program, s.terminal, s.osuser
  from Gv$session s
  join Gv$process p
    on s.paddr = p.addr
   and s.inst_id = p.inst_id
 where s.type != 'BACKGROUND'

This query would also work if you're not running a RAC.

If you're using a tool like PL/SQL Developer then the sessions window will also help you find it.

For a slightly stronger "kill" you can specify the IMMEDIATE keyword, which instructs the database to not wait for the transaction to complete:

alter system kill session 'sid,serial#' immediate;

2. OS level - Issue a SIGTERM

kill pid

This assumes you're using Linux or another *nix variant. A SIGTERM is a terminate signal from the operating system to the specific process asking it to stop running. It tries to let the process terminate gracefully.

Getting this wrong could result in you terminating essential OS processes so be careful when typing.

You can find the pid, process id, by running the following query, which'll also tell you useful information like the terminal the process is running from and the username that's running it so you can ensure you pick the correct one.

select p.*
  from v$process p
  left outer join v$session s
    on p.addr = s.paddr
 where s.sid = ?
   and s.serial# = ?

Once again, if you're running a RAC you need to change this slightly to:

select p.*
  from Gv$process p
  left outer join Gv$session s
    on p.addr = s.paddr
 where s.sid = ?
   and s.serial# = ?

Changing the where clause to where s.status = 'KILLED' will help you find already killed process that are still "running".

3. OS - Issue a SIGKILL

kill -9 pid

Using the same pid you picked up in 2, a SIGKILL is a signal from the operating system to a specific process that causes the process to terminate immediately. Once again be careful when typing.

This should rarely be necessary. If you were doing DML or DDL it will stop any rollback being processed and may make it difficult to recover the database to a consistent state in the event of failure.

All the remaining options will kill all sessions and result in your database - and in the case of 6 and 7 server as well - becoming unavailable. They should only be used if absolutely necessary...

4. Oracle - Shutdown the database

shutdown immediate

This is actually politer than a SIGKILL, though obviously it acts on all processes in the database rather than your specific process. It's always good to be polite to your database.

Shutting down the database should only be done with the consent of your DBA, if you have one. It's nice to tell the people who use the database as well.

It closes the database, terminating all sessions and does a rollback on all uncommitted transactions. It can take a while if you have large uncommitted transactions that need to be rolled back.

5. Oracle - Shutdown the database ( the less nice way )

shutdown abort

This is approximately the same as a SIGKILL, though once again on all processes in the database. It's a signal to the database to stop everything immediately and die - a hard crash. It terminates all sessions and does no rollback; because of this it can mean that the database takes longer to startup again. Despite the incendiary language a shutdown abort isn't pure evil and can normally be used safely.

As before inform people the relevant people first.

6. OS - Reboot the server

reboot

Obviously, this not only stops the database but the server as well so use with caution and with the consent of your sysadmins in addition to the DBAs, developers, clients and users.

7. OS - The last stage

I've had reboot not work... Once you've reached this stage you better hope you're using a VM. We ended up deleting it...

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

It doesn't look like DD-MMM-YYYY is supported by default (at least, with dash as separator). However, using the AS clause, you should be able to do something like:

SELECT CONVERT(VARCHAR(11), SYSDATETIME(), 106) AS [DD-MON-YYYY]

See here: http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx

How to get Javascript Select box's selected text

Please try this code:

$("#YourSelect>option:selected").html()

SQL use CASE statement in WHERE IN clause

 select  * from Tran_LibraryBooksTrans LBT  left join
 Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN' AND
 LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
 LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 ELSE 0 END`enter code here`select  * from Tran_LibraryBooksTrans LBT 
 left join Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
 LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
 1 ELSE 0 END

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

select from one table, insert into another table oracle sql query

You can use

insert into <table_name> select <fieldlist> from <tables>

Combine Multiple child rows into one row MYSQL

If you really need multiple columns in your result, and the amount of options is limited, you can even do this:

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
  if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
  if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
  if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
  GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

How to get the text of the selected value of a dropdown list?

The easiest way is through css3 $("select option:selected") and then use the .text() or .html() function. depending on what you want to have.

Grant SELECT on multiple tables oracle

This worked for me on my Oracle database:

SELECT   'GRANT SELECT, insert, update, delete ON mySchema.' || TABLE_NAME || ' to myUser;'
FROM     user_tables
where table_name like 'myTblPrefix%'

Then, copy the results, paste them into your editor, then run them like a script.

You could also write a script and use "Execute Immediate" to run the generated SQL if you don't want the extra copy/paste steps.

AngularJS - value attribute for select

If the model specified for the drop down does not exist then angular will generate an empty options element. So you will have to explicitly specify the model on the select like this:

<select ng-model="regions[index]" ng-options="....">

Refer to the following as it has been answered before:

Why does AngularJS include an empty option in select? and this fiddle

Update: Try this instead:

<select ng-model="regions[index].code" ng-options="i.code as i.name for i in regions">
</select>

or

<select ng-model="regions[2]" ng-options="r.name for r in regions">
</select>

Note that there is no empty options element in the select.

How to check if an option is selected?

In my case I don't know why selected is always true. So the only way I was able to think up is:

var optionSelected = false;
$( '#select_element option' ).each( function( i, el ) {
    var optionHTMLStr = el.outerHTML;

    if ( optionHTMLStr.indexOf( 'selected' ) > 0 ) {
        optionSelected = true;
        return false;
    }
});

jQuery add blank option to top of list and make selected to existing dropdown

Solution native Javascript :

document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);

example : http://codepen.io/anon/pen/GprybL

Notice: Array to string conversion in

mysql_fetch_assoc returns an array so you can not echo an array, need to print_r() otherwise particular string $money['money'].

SQL User Defined Function Within Select

If it's a table-value function (returns a table set) you simply join it as a Table

this function generates one column table with all the values from passed comma-separated list

SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')

Select columns from result set of stored procedure

Create a dynamic view and get result from it.......

CREATE PROCEDURE dbo.usp_userwise_columns_value
(
    @userid BIGINT
)
AS 
BEGIN
        DECLARE @maincmd NVARCHAR(max);
        DECLARE @columnlist NVARCHAR(max);
        DECLARE @columnname VARCHAR(150);
        DECLARE @nickname VARCHAR(50);

        SET @maincmd = '';
        SET @columnname = '';
        SET @columnlist = '';
        SET @nickname = '';

        DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD
        FOR
            SELECT columnname , nickname
            FROM dbo.v_userwise_columns 
            WHERE userid = @userid

        OPEN CUR_COLUMNLIST
        IF @@ERROR <> 0
            BEGIN
                ROLLBACK
                RETURN
            END   

        FETCH NEXT FROM CUR_COLUMNLIST
        INTO @columnname, @nickname

        WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @columnlist = @columnlist + @columnname + ','

                FETCH NEXT FROM CUR_COLUMNLIST
                INTO @columnname, @nickname
            END
        CLOSE CUR_COLUMNLIST
        DEALLOCATE CUR_COLUMNLIST  

        IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
            BEGIN
                SET @maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' 
                            + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' 
                            + @columnlist + ' compcode FROM dbo.SJOTran '
            END
        ELSE
            BEGIN
                SET @maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' 
                            + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' 
                            + @columnlist + ' compcode FROM dbo.SJOTran '
            END

        --PRINT @maincmd
        EXECUTE sp_executesql @maincmd
END

-----------------------------------------------
SELECT * FROM dbo.v_userwise_columns_value

How to get label of select option with jQuery?

Hi first give an id to the select as

<select id=theid>
<option value="test">label </option>
</select>

then you can call the selected label like that:

jQuery('#theid option:selected').text()

Django Multiple Choice Field / Checkbox Select Multiple

The easiest way I found (just I use eval() to convert string gotten from input to tuple to read again for form instance or other place)

This trick works very well

#model.py
class ClassName(models.Model):
    field_name = models.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.field_name:
            self.field_name= eval(self.field_name)



#form.py
CHOICES = [('pi', 'PI'), ('ci', 'CI')]

class ClassNameForm(forms.ModelForm):
    field_name = forms.MultipleChoiceField(choices=CHOICES)

    class Meta:
        model = ClassName
        fields = ['field_name',]

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

How to delete from select in MySQL?

SELECT (sub)queries return result sets. So you need to use IN, not = in your WHERE clause.

Additionally, as shown in this answer you cannot modify the same table from a subquery within the same query. However, you can either SELECT then DELETE in separate queries, or nest another subquery and alias the inner subquery result (looks rather hacky, though):

DELETE FROM posts WHERE id IN (
    SELECT * FROM (
        SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 )
    ) AS p
)

Or use joins as suggested by Mchl.

SQL update from one Table to another based on a ID match

I believe an UPDATE FROM with a JOIN will help:

MS SQL

UPDATE
    Sales_Import
SET
    Sales_Import.AccountNumber = RAN.AccountNumber
FROM
    Sales_Import SI
INNER JOIN
    RetrieveAccountNumber RAN
ON 
    SI.LeadID = RAN.LeadID;

MySQL and MariaDB

UPDATE
    Sales_Import SI,
    RetrieveAccountNumber RAN
SET
    SI.AccountNumber = RAN.AccountNumber
WHERE
    SI.LeadID = RAN.LeadID;

How to create virtual column using MySQL SELECT?

You could use a CASE statement, like

SELECT name
       ,address
       ,CASE WHEN a < b THEN '1' 
             ELSE '2' END AS one_or_two
FROM ...

SQL query to check if a name begins and ends with a vowel

Worked for me using simple left, right functions in MS SQL

select city from station where left(city,1) in ('a','e','i','o','u') and right(city,1) in ('a','e','i','o','u')

MySQL Select Query - Get only first 10 characters of a value

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

Right click to select a row in a Datagridview and show a menu to delete it

For completness of this question, better to use a Grid event rather than mouse.

First Set your datagrid properties:

SelectionMode to FullRowSelect and RowTemplate / ContextMenuStrip to a context menu.

Create the CellMouseDown event:-

private void myDatagridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        int rowSelected = e.RowIndex;
        if (e.RowIndex != -1)
        {
            this.myDatagridView.ClearSelection();
            this.myDatagridView.Rows[rowSelected].Selected = true;
        }
        // you now have the selected row with the context menu showing for the user to delete etc.
    }
}

Performing a query on a result from another query?

You just wrap your query in another one:

SELECT COUNT(*), SUM(Age)
FROM (
    SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
    FROM availables
    INNER JOIN rooms
    ON availables.room_id=rooms.id
    WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
    GROUP BY availables.bookdate
) AS tmp;

How to select into a variable in PL/SQL when the result might be null?

What about using MAX? That way if no data is found the variable is set to NULL, otherwise the maximum value.
Since you expect either 0 or 1 value, MAX should be OK to use.

v_column my_table.column%TYPE;
select MAX(column) into v_column from my_table where ...;

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

Actually you can do it.

Although, someone should note that repeating the CASE statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE twice so that you won't get any performance hit because of that.

Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)

INSERT INTO dbo.T1
(
    Col1,
    Col2,
    Col3
)
SELECT
    1,
    SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
    SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
    dbo.T1 t
LEFT OUTER JOIN
(
    SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1

This will insert the values (1, 2, 3) for each record in the table T1. This uses a delimiter '%' to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar fields etc.). But the main logic is that you should join the CASE statement and select from the result set of the join with using a split logic.

How to get values from IGrouping

From definition of IGrouping :

IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable

you can just iterate through elements like this:

IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

SQL Server convert select a column and convert it to a string

You can do it like this:

Fiddle demo

declare @results varchar(500)

select @results = coalesce(@results + ',', '') +  convert(varchar(12),col)
from t
order by col

select @results as results

| RESULTS |
-----------
| 1,3,5,9 |

How to select distinct rows in a datatable and store into an array

DataTable dt = new DataTable("EMPLOYEE_LIST");

DataColumn eeCode = dt.Columns.Add("EMPLOYEE_CODE", typeof(String));
DataColumn taxYear = dt.Columns.Add("TAX_YEAR", typeof(String));
DataColumn intData = dt.Columns.Add("INT_DATA", typeof(int));
DataColumn textData = dt.Columns.Add("TEXT_DATA", typeof(String));

dt.PrimaryKey = new DataColumn[] { eeCode, taxYear };

It filters data table with eecode and taxyear combinedly considered as unique

JQuery - how to select dropdown item based on value

$('select#myselect option[value="ab"]').

Why does the jquery change event not trigger when I set the value of a select using val()?

I believe you can manually trigger the change event with trigger():

$("#single").val("Single2").trigger('change');

Though why it doesn't fire automatically, I have no idea.

How to best display in Terminal a MySQL SELECT returning too many fields?

You might also find this useful (non-Windows only):

mysql> pager less -SFX
mysql> SELECT * FROM sometable;

This will pipe the outut through the less command line tool which - with these parameters - will give you a tabular output that can be scrolled horizontally and vertically with the cursor keys.

Leave this view by hitting the q key, which will quit the less tool.

Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>
</select>

JQuery

var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

Select records from today, this week, this month php mysql

Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:

SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;

So we have a table called Jokes with columns JScore and JDate.

Select records from NOW() -1 Day

Be aware that the result may be slightly different than you expect.

NOW() returns a DATETIME.

And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.

So if your script is cron'd to run at 03:00, it will miss the first three hours of records from the 'oldest' day.

To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get back to the beginning of the previous day regardless of when the script is run.

Select all columns except one in MySQL?

May be I have a solution to Jan Koritak's pointed out discrepancy

SELECT CONCAT('SELECT ',
( SELECT GROUP_CONCAT(t.col)
FROM
(
    SELECT CASE
    WHEN COLUMN_NAME = 'eid' THEN NULL
    ELSE COLUMN_NAME
    END AS col 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'
) t
WHERE t.col IS NOT NULL) ,
' FROM employee' );

Table :

SELECT table_name,column_name 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'

================================

table_name  column_name
employee    eid
employee    name_eid
employee    sal

================================

Query Result:

'SELECT name_eid,sal FROM employee'

MySQL SELECT WHERE datetime matches day (and not necessarily time)

SELECT * FROM table where Date(col) = 'date'

How to open a new HTML page using jQuery?

If you want to use jQuery, the .load() function is the correct function you are after;

But you are missing the # from the div1 id selector in the example 2)

This should work:

$("#div1").load("file2.html");

SQL conditional SELECT

@selectField1 AS bit
@selectField2 AS bit

SELECT
CASE 
    WHEN @selectField1 THEN Field1
    WHEN @selectField2 THEN Field2
    ELSE someDefaultField
END
FROM Table

Is this what you're looking for?

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Assuming that your search is stylus photo 2100. Try the following example is using RLIKE.

SELECT * FROM `buckets` WHERE `bucketname` RLIKE REPLACE('stylus photo 2100', ' ', '+.*');

EDIT

Another way is to use FULLTEXT index on bucketname and MATCH ... AGAINST syntax in your SELECT statement. So to re-write the above example...

SELECT * FROM `buckets` WHERE MATCH(`bucketname`) AGAINST (REPLACE('stylus photo 2100', ' ', ','));

Javascript to sort contents of select element

Another option:

function sortSelect(elem) {
    var tmpAry = [];
    // Retain selected value before sorting
    var selectedValue = elem[elem.selectedIndex].value;
    // Grab all existing entries
    for (var i=0;i<elem.options.length;i++) tmpAry.push(elem.options[i]);
    // Sort array by text attribute
    tmpAry.sort(function(a,b){ return (a.text < b.text)?-1:1; });
    // Wipe out existing elements
    while (elem.options.length > 0) elem.options[0] = null;
    // Restore sorted elements
    var newSelectedIndex = 0;
    for (var i=0;i<tmpAry.length;i++) {
        elem.options[i] = tmpAry[i];
        if(elem.options[i].value == selectedValue) newSelectedIndex = i;
    }
    elem.selectedIndex = newSelectedIndex; // Set new selected index after sorting
    return;
}

Select 50 items from list at random to write to file

I think random.choice() is a better option.

import numpy as np

mylist = [13,23,14,52,6,23]

np.random.choice(mylist, 3, replace=False)

the function returns an array of 3 randomly chosen values from the list

MySQL SELECT only not null values

Select * from your_table 
WHERE col1 and col2 and col3 and col4 and col5 IS NOT NULL;

The only disadvantage of this approach is that you can only compare 5 columns, after that the result will always be false, so I do compare only the fields that can be NULL.

Get index of selected option with jQuery

I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.

var vOptionSelect = "#productcodeSelect1";

The index is returned with:

$(vOptionSelect).find(":selected").index();

Oracle Insert via Select from multiple tables where one table may not have a row

A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:

INSERT INTO account_type_standard   
  (account_type_Standard_id, tax_status_id, recipient_id) 
VALUES(   
  account_type_standard_seq.nextval,
  (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
  (SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

There's a bit of confusion in your question:

  • a Date datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE into a Date.
  • When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the TO_CHAR function. In Oracle, a Date has no format: it is a point in time.
  • Reciprocally, you would use TO_TIMESTAMP_TZ to convert a VARCHAR2 to a TIMESTAMP, but this won't convert a Date to a TIMESTAMP.
  • You use FROM_TZ to add the time zone information to a TIMESTAMP (or a Date).
  • In Oracle, CST is a time zone but CDT is not. CDT is a daylight saving information.
  • To complicate things further, CST/CDT (-05:00) and CST/CST (-06:00) will have different values obviously, but the time zone CST will inherit the daylight saving information depending upon the date by default.

So your conversion may not be as simple as it looks.

Assuming that you want to convert a Date d that you know is valid at time zone CST/CST to the equivalent at time zone CST/CDT, you would use:

SQL> SELECT from_tz(d, '-06:00') initial_ts,
  2         from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
  3    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  4                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  5            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00

My default timestamp format has been used here. I can specify a format explicitely:

SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
  2         to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
  3                 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
  4    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  5                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  6            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00      2012-10-09 02:10:21 -05:00

SELECT using 'CASE' in SQL

This is just the syntax of the case statement, it looks like this.

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END AS FRUIT
FROM FRUIT_TABLE;

As a reminder remember; no assignment is performed the value becomes the column contents. (If you wanted to assign that to a variable you would put it before the CASE statement).

Oracle date difference to get number of years

I'd use months_between, possibly combined with floor:

select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;

select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;

floor makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor.

how to dynamically add options to an existing select in vanilla javascript

Try this;

   var data = "";
   data = "<option value = Some value> Some Option </option>";         
   options = [];
   options.push(data);
   select = document.getElementById("drop_down_id");
   select.innerHTML = optionsHTML.join('\n'); 

Insert data into table with result from another select query

Below is an example of such a query:

INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

Google Script to see if text contains a value

Update 2020:

You can now use Modern ECMAScript syntax thanks to V8 Runtime.

You can use includes():

var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}

General error: 1364 Field 'user_id' doesn't have a default value

 Post::create([
      'title' => request('title'),
      'body' => request('body'),
      'user_id' => auth()->id()
    ]);

you dont need the request() as you doing that already pulling the value of body and title

libclntsh.so.11.1: cannot open shared object file.

Possibly you want to specify PATH — and also ORACLE_HOME and LD_LIBRARY_PATH — so that cron(1) knows where to find binaries.
Read "5 Crontab environment" here.

Java 8 List<V> into Map<K, V>

If your key is NOT guaranteed to be unique for all elements in the list, you should convert it to a Map<String, List<Choice>> instead of a Map<String, Choice>

Map<String, List<Choice>> result =
 choices.stream().collect(Collectors.groupingBy(Choice::getName));

High-precision clock in Python

I observed that the resolution of time.time() is different between Windows 10 Professional and Education versions.

On a Windows 10 Professional machine, the resolution is 1 ms. On a Windows 10 Education machine, the resolution is 16 ms.

Fortunately, there's a tool that increases Python's time resolution in Windows: https://vvvv.org/contribution/windows-system-timer-tool

With this tool, I was able to achieve 1 ms resolution regardless of Windows version. You will need to be keep it running while executing your Python codes.

How can I access getSupportFragmentManager() in a fragment?

The following code does the trick for me

 SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
    mapFragment.getMapAsync(this);

An existing connection was forcibly closed by the remote host

I had this issue when i tried to connect to postgresql while i'm using microsoft sutdio for mssql :)

get size of json object

Consider using underscore.js. It will allow you to check the size i.e. like that:

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3

RESTful web service - how to authenticate requests from other services?

I believe the approach:

  1. First request, client sends id/passcode
  2. Exchange id/pass for unique token
  3. Validate token on each subsequent request until it expires

is pretty standard, regardless of how you implement and other specific technical details.

If you really want to push the envelope, perhaps you could regard the client's https key in a temporarily invalid state until the credentials are validated, limit information if they never are, and grant access when they are validated, based again on expiration.

Hope this helps

Adding header to all request with Retrofit 2

In kotlin adding interceptor looks that way:

.addInterceptor{ it.proceed(it.request().newBuilder().addHeader("Cache-Control", "no-store").build())}

Convert Uri to String and String to Uri

Try this to convert string to uri

String mystring="Hello"
Uri myUri = Uri.parse(mystring);

Uri to String

Uri uri;
String uri_to_string;
uri_to_string= uri.toString();

How to make an android app to always run in background?

You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.

Create a service:

public class YourService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return super.onStartCommand(intent, flags, startId);
    }
}

Create an Application class and start your service:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this, YourService.class));
    }
}

Add "name" attribute into the "application" tag of your AndroidManifest.xml

android:name=".App"

Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml

<service android:name=".YourService"/>

And also this permission request in the "manifest" tag (if API level 28 or higher):

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

UPDATE

After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        // do your jobs here

        startForeground();
        
        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Service is running background")
                .setContentIntent(pendingIntent)
                .build());         
    }
}

EDIT: RESTRICTED OEMS

Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.

If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.

By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)

Getter and Setter?

After reading the other advices, I'm inclined to say that:

As a GENERIC rule, you will not always define setters for ALL properties, specially "internal" ones (semaphores, internal flags...). Read-only properties will not have setters, obviously, so some properties will only have getters; that's where __get() comes to shrink the code:

  • define a __get() (magical global getters) for all those properties which are alike,
  • group them in arrays so:
    • they'll share common characteristics: monetary values will/may come up properly formatted, dates in an specific layout (ISO, US, Intl.), etc.
    • the code itself can verify that only existing & allowed properties are being read using this magical method.
    • whenever you need to create a new similar property, just declare it and add its name to the proper array and it's done. That's way FASTER than defining a new getter, perhaps with some lines of code REPEATED again and again all over the class code.

Yes! we could write a private method to do that, also, but then again, we'll have MANY methods declared (++memory) that end up calling another, always the same, method. Why just not write a SINGLE method to rule them all...? [yep! pun absolutely intended! :)]

Magic setters can also respond ONLY to specific properties, so all date type properties can be screened against invalid values in one method alone. If date type properties were listed in an array, their setters can be defined easily. Just an example, of course. there are way too many situations.

About readability... Well... That's another debate: I don't like to be bound to the uses of an IDE (in fact, I don't use them, they tend to tell me (and force me) how to write... and I have my likes about coding "beauty"). I tend to be consistent about naming, so using ctags and a couple of other aids is sufficient to me... Anyway: once all this magic setters and getters are done, I write the other setters that are too specific or "special" to be generalized in a __set() method. And that covers all I need about getting and setting properties. Of course: there's not always a common ground, or there are such a few properties that is not worth the trouble of coding a magical method, and then there's still the old good traditional setter/getter pair.

Programming languages are just that: human artificial languages. So, each of them has its own intonation or accent, syntax and flavor, so I won't pretend to write a Ruby or Python code using the same "accent" than Java or C#, nor I would write a JavaScript or PHP to resemble Perl or SQL... Use them the way they're meant to be used.

Python [Errno 98] Address already in use

Nothing worked for me except running a subprocess with this command, before calling HTTPServer(('', 443), myHandler):

kill -9 $(lsof -ti tcp:443)

Of course this is only for linux-like OS!

Swap two items in List<T>

There is no existing Swap-method, so you have to create one yourself. Of course you can linqify it, but that has to be done with one (unwritten?) rules in mind: LINQ-operations do not change the input parameters!

In the other "linqify" answers, the (input) list is modified and returned, but this action brakes that rule. If would be weird if you have a list with unsorted items, do a LINQ "OrderBy"-operation and than discover that the input list is also sorted (just like the result). This is not allowed to happen!

So... how do we do this?

My first thought was just to restore the collection after it was finished iterating. But this is a dirty solution, so do not use it:

static public IEnumerable<T> Swap1<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // Swap the items.
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;

    // Return the items in the new order.
    foreach (T item in source)
        yield return item;

    // Restore the collection.
    source[index2] = source[index1];
    source[index1] = temp;
}

This solution is dirty because it does modify the input list, even if it restores it to the original state. This could cause several problems:

  1. The list could be readonly which will throw an exception.
  2. If the list is shared by multiple threads, the list will change for the other threads during the duration of this function.
  3. If an exception occurs during the iteration, the list will not be restored. (This could be resolved to write an try-finally inside the Swap-function, and put the restore-code inside the finally-block).

There is a better (and shorter) solution: just make a copy of the original list. (This also makes it possible to use an IEnumerable as a parameter, instead of an IList):

static public IEnumerable<T> Swap2<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // If nothing needs to be swapped, just return the original collection.
    if (index1 == index2)
        return source;

    // Make a copy.
    List<T> copy = source.ToList();

    // Swap the items.
    T temp = copy[index1];
    copy[index1] = copy[index2];
    copy[index2] = temp;

    // Return the copy with the swapped items.
    return copy;
}

One disadvantage of this solution is that it copies the entire list which will consume memory and that makes the solution rather slow.

You might consider the following solution:

static public IEnumerable<T> Swap3<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using (IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for (int i = 0; i < index1; i++)
            yield return source[i];

        // Return the item at the second index.
        yield return source[index2];

        if (index1 != index2)
        {
            // Return the items between the first and second index.
            for (int i = index1 + 1; i < index2; i++)
                yield return source[i];

            // Return the item at the first index.
            yield return source[index1];
        }

        // Return the remaining items.
        for (int i = index2 + 1; i < source.Count; i++)
            yield return source[i];
    }
}

And if you want to input parameter to be IEnumerable:

static public IEnumerable<T> Swap4<T>(this IEnumerable<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using(IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for(int i = 0; i < index1; i++) 
        {
            if (!e.MoveNext())
                yield break;
            yield return e.Current;
        }

        if (index1 != index2)
        {
            // Remember the item at the first position.
            if (!e.MoveNext())
                yield break;
            T rememberedItem = e.Current;

            // Store the items between the first and second index in a temporary list. 
            List<T> subset = new List<T>(index2 - index1 - 1);
            for (int i = index1 + 1; i < index2; i++)
            {
                if (!e.MoveNext())
                    break;
                subset.Add(e.Current);
            }

            // Return the item at the second index.
            if (e.MoveNext())
                yield return e.Current;

            // Return the items in the subset.
            foreach (T item in subset)
                yield return item;

            // Return the first (remembered) item.
            yield return rememberedItem;
        }

        // Return the remaining items in the list.
        while (e.MoveNext())
            yield return e.Current;
    }
}

Swap4 also makes a copy of (a subset of) the source. So worst case scenario, it is as slow and memory consuming as function Swap2.

Does Git Add have a verbose switch

You can use git add -i to get an interactive version of git add, although that's not exactly what you're after. The simplest thing to do is, after having git added, use git status to see what is staged or not.

Using git add . isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).

Convert an integer to a float number

Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

Which means that you need to use float64(integer_value).

PHP checkbox set to check based on database value

This simplest ways is to add the "checked attribute.

<label for="tag_1">Tag 1</label>
<input type="checkbox" name="tag_1" id="tag_1" value="yes" 
    <?php if($tag_1_saved_value === 'yes') echo 'checked="checked"';?> />

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

The reason why this happened to me was that a remote server was allowing only certain IP addressed but not its own, and I was trying to render the images from the server's URLs... so everything would simply halt, displaying the timeout error that you had...

Make sure that either the server is allowing its own IP, or that you are rendering things from some remote URL that actually exists.

document.getElementById().value doesn't set the value

The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText, contains a string value.

In that constelation, the value cannot be displayed (it would get blank)

Example: http://jsfiddle.net/BmhNL/2/


My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type = number. If there is "only" a white-space issue, you can try to implicitly call the Number() constructor, like

document.getElementById("points").value = +request.responseText;

Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

It sounds like Maven is using the JRE, not the JDK. Perhaps you installed Maven before installing the JDK?

Check the settings files. There are three in total, system, user, and project. It's most likely in the installation configuration ($M2_HOME/conf/settings.xml) or, possibly, the per-user configuration (${user.dir}/.m2/settings.xml).

Mercurial: how to amend the last commit?

Assuming that you have not yet propagated your changes, here is what you can do.

  • Add to your .hgrc:

    [extensions]
    mq =
    
  • In your repository:

    hg qimport -r0:tip
    hg qpop -a
    

    Of course you need not start with revision zero or pop all patches, for the last just one pop (hg qpop) suffices (see below).

  • remove the last entry in the .hg/patches/series file, or the patches you do not like. Reordering is possible too.

  • hg qpush -a; hg qfinish -a
  • remove the .diff files (unapplied patches) still in .hg/patches (should be one in your case).

If you don't want to take back all of your patch, you can edit it by using hg qimport -r0:tip (or similar), then edit stuff and use hg qrefresh to merge the changes into the topmost patch on your stack. Read hg help qrefresh.

By editing .hg/patches/series, you can even remove several patches, or reorder some. If your last revision is 99, you may just use hg qimport -r98:tip; hg qpop; [edit series file]; hg qpush -a; hg qfinish -a.

Of course, this procedure is highly discouraged and risky. Make a backup of everything before you do this!

As a sidenote, I've done it zillions of times on private-only repositories.

mysql datetime comparison

I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :

[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...

What's the Use of '\r' escape sequence?

This is from antiquated technology: The old fashion typewriter style of printer. There was a roller (platen) that advanced the paper and a print head that hammered a metal key against an ink fabric.

\r Return the print head to the left side.

\n Advance the platen one line.

If the \n was not issued, you would type over what was on a line (used mostly for underlining text).

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='') 
BEGIN
   SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
   INSERT INTO TABLE(FieldValue) VALUES('')
   SELECT SCOPE_IDENTITY() AS TableID
END

See here for more information on IF ELSE

Note: written without a SQL Server install handy to double check this but I think it is correct

Also, I've changed the EXISTS bit to do SELECT 1 rather than SELECT * as you don't care what is returned within an EXISTS, as long as something is I've also changed the SCOPE_IDENTITY() bit to return just the identity assuming that TableID is the identity column

How to check which version of Keras is installed?

Simple command to check keras version:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit) 

>>> import keras
Using TensorFlow backend.
>>> keras.__version__
'2.2.4'

Save array in mysql database

To convert any array (or any object) into a string using PHP, call the serialize():

$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;

$string will now hold a string version of the array. The output of the above code is as follows:

a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}

To convert back from the string to the array, use unserialize():

// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );

Get properties of a class

Just for fun

class A {
    private a1 = void 0;
    private a2 = void 0;
}

class B extends A {
    private a3 = void 0;
    private a4 = void 0;
}

class C extends B {
    private a5 = void 0;
    private a6 = void 0;
}

class Describer {
    private static FRegEx = new RegExp(/(?:this\.)(.+?(?= ))/g); 
    static describe(val: Function, parent = false): string[] {
        var result = [];
        if (parent) {
            var proto = Object.getPrototypeOf(val.prototype);
            if (proto) {
                result = result.concat(this.describe(proto.constructor, parent));
            } 
        }
        result = result.concat(val.toString().match(this.FRegEx) || []);
        return result;
    }
}

console.log(Describer.describe(A)); // ["this.a1", "this.a2"]
console.log(Describer.describe(B)); // ["this.a3", "this.a4"]
console.log(Describer.describe(C, true)); // ["this.a1", ..., "this.a6"]

Update: If you are using custom constructors, this functionality will break.

Build error: You must add a reference to System.Runtime

I had this problem in a solution with a Web API project and several library projects. One of the library projects was borking on build, with errors that said the Unity attributes weren't "valid" attributes, and then one error said I needed to reference System.Runtime.

After much searching, reinstalling the 4.5.2 Developer Pack, and nothing working, I figured maybe it was just a version mismatch. So I looked at the properties of every project, and one of the very base libraries was targeting 4.5 while every other one was targeting 4.5.2. I changed that one to also target 4.5.2 and the errors went away.

How to initialize an array's length in JavaScript?

  1. Why do you want to initialize the length? Theoretically there is no need for this. It can even result in confusing behavior, because all tests that use the length to find out whether an array is empty or not will report that the array is not empty.
    Some tests show that setting the initial length of large arrays can be more efficient if the array is filled afterwards, but the performance gain (if any) seem to differ from browser to browser.

  2. jsLint does not like new Array() because the constructer is ambiguous.

    new Array(4);
    

    creates an empty array of length 4. But

    new Array('4');
    

    creates an array containing the value '4'.

Regarding your comment: In JS you don't need to initialize the length of the array. It grows dynamically. You can just store the length in some variable, e.g.

var data = [];
var length = 5; // user defined length

for(var i = 0; i < length; i++) {
    data.push(createSomeObject());
}

Enum String Name from Value

Try this:

string m = Enum.GetName(typeof(MyEnumClass), value);

Calculate row means on subset of columns

You can create a new row with $ in your data frame corresponding to the Means

DF$Mean <- rowMeans(DF[,2:4])

How to use Bootstrap 4 in ASP.NET Core

Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.

Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)

The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write: Bower is maintained only.Recommend using LibManager

Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:

In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]

enter image description here

Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")

How to remove/ignore :hover css style on touch devices

If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the

CURSOR : POINTER; to CURSOR : DEFAULT;

use mediaQuery to hide in mobile phone/Tablet.

This works for me.

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

put this in your "head" of your index.html

 <style>
  html body{
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 0;
  }
  </style>

How to set ObjectId as a data type in mongoose

My solution on using ObjectId

// usermodel.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId


let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

UserSchema.set('autoIndex', true)

module.exports = mongoose.model('User', UserSchema)

Using mongoose's populate method

// controller.js

const mongoose = require('mongoose')
const User = require('./usermodel.js')

let query = User.findOne({ name: "Person" })

query.exec((err, user) => {
  if (err) {
     console.log(err)
  }

  user.events = events
  // user.events is now an array of events
})

Spring boot - Not a managed type

I had this same problem but only when running spring boot tests cases that required JPA. The end result was that our own jpa test configuration was initializing an EntityManagerFactory and setting the packages to scan. This evidently will override the EntityScan parameters if you are setting it manually.

    final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter( vendorAdapter );
    factory.setPackagesToScan( Project.class.getPackage().getName());
    factory.setDataSource( dataSource );

Important to note: if you are still stuck you should set a break point in the org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager on the setPackagesToScan() method and take a look at where this is being called and what packages are being passed to it.

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

MS-DOS Batch file pause with enter key

You can do it with the pause command, example:

dir
pause
echo Now about to end...
pause

How can I reuse a navigation bar on multiple pages?

Brando ZWZ provides some great answers to handling this situation.

Re: Same navbar on multiple pages Aug 21, 2018 10:13 AM|LINK

As far as I know, there are multiple solution.

For example:

The Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar).

Then we could directly load it from the jquery without writing a lot of codes.

Like this:

    <!--Navigation bar-->
    <div id="nav-placeholder">

    </div>

    <script>
    $(function(){
      $("#nav-placeholder").load("nav.html");
    });
    </script>
    <!--end of Navigation bar-->

Solution2:

You could use JavaScript code to generate the whole nav bar.

Like this:

Javascript code:

$(function () {
    var bar = '';
    bar += '<nav class="navbar navbar-default" role="navigation">';
    bar += '<div class="container-fluid">';
    bar += '<div>';
    bar += '<ul class="nav navbar-nav">';
    bar += '<li id="home"><a href="home.html">Home</a></li>';
    bar += '<li id="index"><a href="index.html">Index</a></li>';
    bar += '<li id="about"><a href="about.html">About</a></li>';
    bar += '</ul>';
    bar += '</div>';
    bar += '</div>';
    bar += '</nav>';

    $("#main-bar").html(bar);

    var id = getValueByName("id");
    $("#" + id).addClass("active");
});

function getValueByName(name) {
    var url = document.getElementById('nav-bar').getAttribute('src');
    var param = new Array();
    if (url.indexOf("?") != -1) {
        var source = url.split("?")[1];
        items = source.split("&");
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var parameters = item.split("=");
            if (parameters[0] == "id") {
                return parameters[1];
            }
        }
    }
}

Html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div id="main-bar"></div>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <%--add this line to generate the nav bar--%>
    <script src="../assets/js/nav-bar.js?id=index" id="nav-bar"></script>
</body>
</html>

https://forums.asp.net/t/2145711.aspx?Same+navbar+on+multiple+pages

How to calculate the median of an array?

As @Bruce-Feist mentions, for a large number of elements, I'd avoid any solution involving sort if performance is something you are concerned about. A different approach than those suggested in the other answers is Hoare's algorithm to find the k-th smallest of element of n items. This algorithm runs in O(n).

public int findKthSmallest(int[] array, int k)
{
    if (array.length < 10)
    {
        Arrays.sort(array);
        return array[k];
    }
    int start = 0;
    int end = array.length - 1;
    int x, temp;
    int i, j;
    while (start < end)
    {
        x = array[k];
        i = start;
        j = end;
        do
        {
            while (array[i] < x)
                i++;
            while (x < array[j])
                j--;
            if (i <= j)
            {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
                i++;
                j--;
            }
        } while (i <= j);
        if (j < k)
            start = i;
        if (k < i)
            end = j;
    }
    return array[k];
}

And to find the median:

public int median(int[] array)
{
    int length = array.length;
    if ((length & 1) == 0) // even
        return (findKthSmallest(array, array.length / 2) + findKthSmallest(array, array.length / 2 + 1)) / 2;
    else // odd
        return findKthSmallest(array, array.length / 2);
}

How are "mvn clean package" and "mvn clean install" different?

What clean does (common in both the commands) - removes all files generated by the previous build


Coming to the difference between the commands package and install, you first need to understand the lifecycle of a maven project


These are the default life cycle phases in maven

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • verify - run any checks on results of integration tests to ensure quality criteria are met
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.

How Maven works is, if you run a command for any of the lifecycle phases, it executes each default life cycle phase in order, before executing the command itself.

order of execution

validate >> compile >> test (optional) >> package >> verify >> install >> deploy

So when you run the command mvn package, it runs the commands for all lifecycle phases till package

validate >> compile >> test (optional) >> package

And as for mvn install, it runs the commands for all lifecycle phases till install, which includes package as well

validate >> compile >> test (optional) >> package >> verify >> install


So, effectively what it means is, install commands does everything that package command does and some more (install the package into the local repository, for use as a dependency in other projects locally)

Source: Maven lifecycle reference

Use table row coloring for cells in Bootstrap

You can override the default css rules with this:

.table tbody tr > td.success {
  background-color: #dff0d8 !important;
}

.table tbody tr > td.error {
  background-color: #f2dede !important;
}

.table tbody tr > td.warning {
  background-color: #fcf8e3 !important;
}

.table tbody tr > td.info {
  background-color: #d9edf7 !important;
}

.table-hover tbody tr:hover > td.success {
  background-color: #d0e9c6 !important;
}

.table-hover tbody tr:hover > td.error {
  background-color: #ebcccc !important;
}

.table-hover tbody tr:hover > td.warning {
  background-color: #faf2cc !important;
}

.table-hover tbody tr:hover > td.info {
  background-color: #c4e3f3 !important;
}

!important is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.

Convert column classes in data.table

This is a BAD way to do it! I'm only leaving this answer in case it solves other weird problems. These better methods are the probably partly the result of newer data.table versions... so it's worth while to document this hard way. Plus, this is a nice syntax example for eval substitute syntax.

library(data.table)
dt <- data.table(ID = c(rep("A", 5), rep("B",5)), 
                 fac1 = c(1:5, 1:5), 
                 fac2 = c(1:5, 1:5) * 2, 
                 val1 = rnorm(10),
                 val2 = rnorm(10))

names_factors = c('fac1', 'fac2')
names_values = c('val1', 'val2')

for (col in names_factors){
  e = substitute(X := as.factor(X), list(X = as.symbol(col)))
  dt[ , eval(e)]
}
for (col in names_values){
  e = substitute(X := as.numeric(X), list(X = as.symbol(col)))
  dt[ , eval(e)]
}

str(dt)

which gives you

Classes ‘data.table’ and 'data.frame':  10 obs. of  5 variables:
 $ ID  : chr  "A" "A" "A" "A" ...
 $ fac1: Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5 1 2 3 4 5
 $ fac2: Factor w/ 5 levels "2","4","6","8",..: 1 2 3 4 5 1 2 3 4 5
 $ val1: num  0.0459 2.0113 0.5186 -0.8348 -0.2185 ...
 $ val2: num  -0.0688 0.6544 0.267 -0.1322 -0.4893 ...
 - attr(*, ".internal.selfref")=<externalptr> 

Lombok added but getters and setters not recognized in Intellij IDEA

i had this issue, just make sure

  1. Lombok pulgin is added.
  2. Annotation processor is ticked.
  3. In your build.gradle/ pom.xml, you have set lombok to be the annotation processor.

Eg. for gradle->

annotationProcessor 'org.projectlombok:lombok:1.18.12'

Markdown: continue numbered list

I solved this problem on Github separating the indented sub-block with a newline, for instance, you write the item 1, then hit enter twice (like if it was a new paragraph), indent the block and write what you want (a block of code, text, etc). More information on Markdown lists and Markdown line breaks.

Example:

  1. item one
  2. item two

    this block acts as a new paragraph, above there is a blank line

  3. item three

    some other code

  4. item four

Write Base64-encoded image to file

No need to use BufferedImage, as you already have the image file in a byte array

    byte dearr[] = Base64.decodeBase64(crntImage);
    FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); 
    fos.write(dearr); 
    fos.close();

Remove array element based on object property

Based on some comments above below is the code how to remove an object based on a key name and key value

 var items = [ 
  { "id": 3.1, "name": "test 3.1"}, 
  { "id": 22, "name": "test 3.1" }, 
  { "id": 23, "name": "changed test 23" } 
  ]

    function removeByKey(array, params){
      array.some(function(item, index) {
        return (array[index][params.key] === params.value) ? !!(array.splice(index, 1)) : false;
      });
      return array;
    }

    var removed = removeByKey(items, {
      key: 'id',
      value: 23
    });

    console.log(removed);

Error type 3 Error: Activity class {} does not exist

I had the same error after renaming/refactoring. What I did was add the applicationId property attribute to my build.gradle file, and set its value to the application package.

In build.gradle:

android {
defaultConfig {
    applicationId "com.example.myapp"  
  }
}

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

Select dropdown with fixed width cutting off content in IE

Simply you can use this plugin for jquery ;)

http://plugins.jquery.com/project/skinner

$(function(){
          $('.select1').skinner({'width':'200px'});
});

How do I detect unsigned integer multiply overflow?

There is a way to determine whether an operation is likely to overflow, using the positions of the most-significant one-bits in the operands and a little basic binary-math knowledge.

For addition, any two operands will result in (at most) one bit more than the largest operand's highest one-bit. For example:

bool addition_is_safe(uint32_t a, uint32_t b) {
    size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);
    return (a_bits<32 && b_bits<32);
}

For multiplication, any two operands will result in (at most) the sum of the bits of the operands. For example:

bool multiplication_is_safe(uint32_t a, uint32_t b) {
    size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);
    return (a_bits+b_bits<=32);
}

Similarly, you can estimate the maximum size of the result of a to the power of b like this:

bool exponentiation_is_safe(uint32_t a, uint32_t b) {
    size_t a_bits=highestOneBitPosition(a);
    return (a_bits*b<=32);
}

(Substitute the number of bits for your target integer, of course.)

I'm not sure of the fastest way to determine the position of the highest one-bit in a number, here's a brute-force method:

size_t highestOneBitPosition(uint32_t a) {
    size_t bits=0;
    while (a!=0) {
        ++bits;
        a>>=1;
    };
    return bits;
}

It's not perfect, but that'll give you a good idea whether any two numbers could overflow before you do the operation. I don't know whether it would be faster than simply checking the result the way you suggested, because of the loop in the highestOneBitPosition function, but it might (especially if you knew how many bits were in the operands beforehand).

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

TextAppearance.Holo.Widget.ActionBar.Title appears to have been added in API Level 13. Make sure your build target is set to 13, not just 11.

jQuery autohide element after 5 seconds

This is how you can set the timeout after you click.

$(".selectorOnWhichEventCapture").on('click', function() {
    setTimeout(function(){
        $(".selector").doWhateverYouWantToDo();
    }, 5000);
});

//5000 = 5sec = 5000 milisec

Why does the order in which libraries are linked sometimes cause errors in GCC?

If you add -Wl,--start-group to the linker flags it does not care which order they're in or if there are circular dependencies.

On Qt this means adding:

QMAKE_LFLAGS += -Wl,--start-group

Saves loads of time messing about and it doesn't seem to slow down linking much (which takes far less time than compilation anyway).

Iterate through 2 dimensional array

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

How do I compile with -Xlint:unchecked?

In gradle project, You can added this compile parameter in the following way:

gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked"
    }
}

Docker container will automatically stop after "docker run -d"

According to this answer, adding the -t flag will prevent the container from exiting when running in the background. You can then use docker exec -i -t <image> /bin/bash to get into a shell prompt.

docker run -t -d <image> <command>

It seems that the -t option isn't documented very well, though the help says that it "allocates a pseudo-TTY."

how to always round up to the next integer

(list.Count() + 9) / 10

Everything else here is either overkill or simply wrong (except for bestsss' answer, which is awesome). We do not want the overhead of a function call (Math.Truncate(), Math.Ceiling(), etc.) when simple math is enough.


OP's question generalizes (pigeonhole principle) to:

How many boxes do I need to store x objects if only y objects fit into each box?

The solution:

  1. derives from the realization that the last box might be partially empty, and
  2. is (x + y - 1) ÷ y using integer division.

You'll recall from 3rd grade math that integer division is what we're doing when we say 5 ÷ 2 = 2.

Floating-point division is when we say 5 ÷ 2 = 2.5, but we don't want that here.

Many programming languages support integer division. In languages derived from C, you get it automatically when you divide int types (short, int, long, etc.). The remainder/fractional part of any division operation is simply dropped, thus:

5 / 2 == 2

Replacing our original question with x = 5 and y = 2 we have:

How many boxes do I need to store 5 objects if only 2 objects fit into each box?

The answer should now be obvious: 3 boxes -- the first two boxes hold two objects each and the last box holds one.

(x + y - 1) ÷ y =
(5 + 2 - 1) ÷ 2 =
6 ÷ 2 =
3

So for the original question, x = list.Count(), y = 10, which gives the solution using no additional function calls:

(list.Count() + 9) / 10

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

Zoom to fit: PDF Embedded in HTML

just in case someone need it, in firefox for me it work like this

<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>

wamp server does not start: Windows 7, 64Bit

You just need Visual C++ runtime 2015 installed, if you change your php version to the newest version you will get the error for it. this is why apache has php dependency error.

How to run an EXE file in PowerShell with parameters with spaces and quotes

An alternative answer is to use a Base64 encoded command switch:

powershell -EncodedCommand "QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA=="

When decoded, you'll see it's the OP's original snippet with all arguments and double quotes preserved.

powershell.exe -EncodedCommand

Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.

The original command:

 C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"

It turns into this when encoded as Base64:

QwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAEkASQBTAFwATQBpAGMAcgBvAHMAbwBmAHQAIABXAGUAYgAgAEQAZQBwAGwAbwB5AFwAbQBzAGQAZQBwAGwAbwB5AC4AZQB4AGUAIAAtAHYAZQByAGIAOgBzAHkAbgBjACAALQBzAG8AdQByAGMAZQA6AGQAYgBmAHUAbABsAHMAcQBsAD0AIgBEAGEAdABhACAAUwBvAHUAcgBjAGUAPQBtAHkAcwBvAHUAcgBjAGUAOwBJAG4AdABlAGcAcgBhAHQAZQBkACAAUwBlAGMAdQByAGkAdAB5AD0AZgBhAGwAcwBlADsAVQBzAGUAcgAgAEkARAA9AHMAYQA7AFAAdwBkAD0AcwBhAHAAYQBzAHMAIQA7AEQAYQB0AGEAYgBhAHMAZQA9AG0AeQBkAGIAOwAiACAALQBkAGUAcwB0ADoAZABiAGYAdQBsAGwAcwBxAGwAPQAiAEQAYQB0AGEAIABTAG8AdQByAGMAZQA9AC4AXABtAHkAZABlAHMAdABzAG8AdQByAGMAZQA7AEkAbgB0AGUAZwByAGEAdABlAGQAIABTAGUAYwB1AHIAaQB0AHkAPQBmAGEAbABzAGUAOwBVAHMAZQByACAASQBEAD0AcwBhADsAUAB3AGQAPQBzAGEAcABhAHMAcwAhADsARABhAHQAYQBiAGEAcwBlAD0AbQB5AGQAYgA7ACIALABjAG8AbQBwAHUAdABlAHIAbgBhAG0AZQA9ADEAMAAuADEAMAAuADEAMAAuADEAMAAsAHUAcwBlAHIAbgBhAG0AZQA9AGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIALABwAGEAcwBzAHcAbwByAGQAPQBhAGQAbQBpAG4AcABhAHMAcwAiAA==

and here is how to replicate at home:

$command = 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
$encodedCommand

#  The clip below copies the base64 string to your clipboard for right click and paste.
$encodedCommand | Clip

How to write trycatch in R

tryCatch has a slightly complex syntax structure. However, once we understand the 4 parts which constitute a complete tryCatch call as shown below, it becomes easy to remember:

expr: [Required] R code(s) to be evaluated

error : [Optional] What should run if an error occured while evaluating the codes in expr

warning : [Optional] What should run if a warning occured while evaluating the codes in expr

finally : [Optional] What should run just before quitting the tryCatch call, irrespective of if expr ran successfully, with an error, or with a warning

tryCatch(
    expr = {
        # Your code...
        # goes here...
        # ...
    },
    error = function(e){ 
        # (Optional)
        # Do this if an error is caught...
    },
    warning = function(w){
        # (Optional)
        # Do this if an warning is caught...
    },
    finally = {
        # (Optional)
        # Do this at the end before quitting the tryCatch structure...
    }
)

Thus, a toy example, to calculate the log of a value might look like:

log_calculator <- function(x){
    tryCatch(
        expr = {
            message(log(x))
            message("Successfully executed the log(x) call.")
        },
        error = function(e){
            message('Caught an error!')
            print(e)
        },
        warning = function(w){
            message('Caught an warning!')
            print(w)
        },
        finally = {
            message('All done, quitting.')
        }
    )    
}

Now, running three cases:

A valid case

log_calculator(10)
# 2.30258509299405
# Successfully executed the log(x) call.
# All done, quitting.

A "warning" case

log_calculator(-10)
# Caught an warning!
# <simpleWarning in log(x): NaNs produced>
# All done, quitting.

An "error" case

log_calculator("log_me")
# Caught an error!
# <simpleError in log(x): non-numeric argument to mathematical function>
# All done, quitting.

I've written about some useful use-cases which I use regularly. Find more details here: https://rsangole.netlify.com/post/try-catch/

Hope this is helpful.

Docker and securing passwords

While I totally agree there is no simple solution. There continues to be a single point of failure. Either the dockerfile, etcd, and so on. Apcera has a plan that looks like sidekick - dual authentication. In other words two container cannot talk unless there is a Apcera configuration rule. In their demo the uid/pwd was in the clear and could not be reused until the admin configured the linkage. For this to work, however, it probably meant patching Docker or at least the network plugin (if there is such a thing).

Uncaught ReferenceError: jQuery is not defined

set this jquery min js

script src="http://code.jquery.com/jquery-1.10.1.min.js"

in wp-admin/admin-header.php

How to use Jackson to deserialise an array of objects

you could also create a class which extends ArrayList:

public static class MyList extends ArrayList<Myclass> {}

and then use it like:

List<MyClass> list = objectMapper.readValue(json, MyList.class);

How can I commit a single file using SVN over a network?

You have a file myFile.txt you want to commit.

The right procedure is :

  1. Move to the file folder
  2. svn up
  3. svn commit myFile.txt -m "Insert here a commit message!!!"

Hope this will help someone.

Convert Enumeration to a Set/List

When using guava (See doc) there is Iterators.forEnumeration. Given an Enumeration x you can do the following:

to get a immutable Set:

ImmutableSet.copyOf(Iterators.forEnumeration(x));

to get a immutable List:

ImmutableList.copyOf(Iterators.forEnumeration(x));

to get a hashSet:

Sets.newHashSet(Iterators.forEnumeration(x));

Why is my JQuery selector returning a n.fn.init[0], and what is it?

I just want to add something to these great answers. If your DOM element ins't loading in time. You can still set the value.

let Ctrl = $('#mySelectElement'); ... Ctrl.attr('value', myValue);

after that most DOM elements that accept a value attribute should populate correctly.

How is AngularJS different from jQuery

They work at different levels.

The simplest way to view the difference, from a beginner perspective is that jQuery is essentially an abstract of JavaScript, so the way we design a page for JavaScript is pretty much how we will do it for jQuery. Start with the DOM then build a behavior layer on top of that. Not so with Angular.Js. The process really begins from the ground up, so the end result is the desired view.

With jQuery you do dom-manipulations, with Angular.Js you create whole web-applications.


jQuery was built to abstract away the various browser idiosyncracies, and work with the DOM without having to add IE6 checks and so on. Over time, it developed a nice, robust API which allowed us to do a lot of things, but at its core, it is meant for dealing with the DOM, finding elements, changing UI, and so on. Think of it as working directly with nuts and bolts.

Angular.Js was built as a layer on top of jQuery, to add MVC concepts to front end engineering. Instead of giving you APIs to work with DOM, Angular.Js gives you data-binding, templating, custom components (similar to jQuery UI, but declarative instead of triggering through JS) and a whole lot more. Think of it as working at a higher level, with components that you can hook together, instead of directly at the nuts and bolts level.

Additionally, Angular.Js gives you structures and concepts that apply to various projects, like Controllers, Services, and Directives. jQuery itself can be used in multiple (gazillion) ways to do the same thing. Thankfully, that is way less with Angular.Js, which makes it easier to get into and out of projects. It offers a sane way for multiple people to contribute to the same project, without having to relearn a system from scratch.


A short comparison can be this-

jQuery

  • Can be easily used by those who have proper knowledge on CSS selectors
  • It is a library used for DOM Manipulations
  • Has nothing to do with models
  • Easily manipulate the contents of a webpage
  • Apply styles to make UI more attractive
  • Easy DOM traversal
  • Effects and animation
  • Simple to make AJAX calls and
  • Utilities usability
  • don't have a two-way binding feature
  • becomes complex and difficult to maintain when the size of a project increases
  • Sometimes you have to write more code to achieve the same functionality as in Angular.Js

Angular.Js

  • It is an MVVM Framework
  • Used for creating SPA (Single Page Applications)
  • It has key features like routing, directives, two-way data binding, models, dependency injection, unit tests etc
  • is modular
  • Maintainable, when project size increases
  • is Fast
  • Two-Way data binding REST friendly MVC-based Pattern
  • Deep Linking
  • Templating
  • Build-in form Validation
  • Dependency Injection
  • Localization
  • Full Testing Environment
  • Server Communication

And much more

enter image description here

Think this helps.

More can be found-

Open JQuery Datepicker by clicking on an image w/ no input field

To change the "..." when the mouse hovers over the calendar icon, You need to add the following in the datepicker options:

    showOn: 'button',
    buttonText: 'Click to show the calendar',
    buttonImageOnly: true, 
    buttonImage: 'images/cal2.png',

How to access a value defined in the application.properties file in Spring Boot

1.Injecting a property with the @Value annotation is straightforward:
@Value( "${jdbc.url}" )
private String jdbcUrl;

2. we can obtain the value of a property using the Environment API

@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));

Multiple radio button groups in one form

This is very simple you need to keep different names of every radio input group.

_x000D_
_x000D_
      <input type="radio" name="price">Thousand<br>_x000D_
      <input type="radio" name="price">Lakh<br>_x000D_
      <input type="radio" name="price">Crore_x000D_
      _x000D_
      </br><hr>_x000D_
_x000D_
      <input type="radio" name="gender">Male<br>_x000D_
      <input type="radio" name="gender">Female<br>_x000D_
      <input type="radio" name="gender">Other
_x000D_
_x000D_
_x000D_

HTML - Arabic Support

The W3C has a good introduction.

In short:

HTML is a text markup language. Text means any characters, not just ones in ASCII.

  1. Save your text using a character encoding that includes the characters you want (UTF-8 is a good bet). This will probably require configuring your editor in a way that is specific to the particular editor you are using. (Obviously it also requires that you have a way to input the characters you want)
  2. Make sure your server sends the correct character encoding in the headers (how you do this depends on the server software you us)
  3. If the document you serve over HTTP specifies its encoding internally, then make sure that is correct too
  4. If anything happens to the document between you saving it and it being served up (e.g. being put in a database, being munged by a server side script, etc) then make sure that the encoding isn't mucked about with on the way.

You can also represent any unicode character with ASCII

Redirecting 404 error with .htaccess via 301 for SEO etc

You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:

ErrorDocument 404 /index.php

An error page redirect must be relative to root so you cannot use www.mydomain.com.

If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.

Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

Inversion of Control vs Dependency Injection

DI is a subset of IoC

  • IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside service (for example, xml file or single app service). 2 implementations of IoC, I use, are DI and ServiceLocator.
  • DI means the IoC principle of getting dependent object is done without using concrete objects but abstractions (interfaces). This makes all components chain testable, cause higher level component doesn't depend on lower level component, only from the interface. Mocks implement these interfaces.

Here are some other techniques to achieve IoC.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

As a continuation of MikeS's answer I wanted to add that VS + Visual Studio Visualization and Modeling SDK needs to be installed for this to work, and you need to modify the project file as well. Should also be mentioned I use Jenkins as build server running on a windows 2008 R2 server box with version module, where I get the BUILD_NUMBER.

My Text Template file version.tt looks like this

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#
var build = Environment.GetEnvironmentVariable("BUILD_NUMBER");
build = build == null ? "0" : int.Parse(build).ToString();
var revision = Environment.GetEnvironmentVariable("_BuildVersion");
revision = revision == null ? "5.0.0.0" : revision;    
#>
using System.Reflection;
[assembly: AssemblyVersion("<#=revision#>")]
[assembly: AssemblyFileVersion("<#=revision#>")]

I have the following in the Property Groups

<PropertyGroup>
    <TransformOnBuild>true</TransformOnBuild>
    <OverwriteReadOnlyOutputFiles>true</OverwriteReadOnlyOutputFiles>
    <TransformOutOfDateOnly>false</TransformOutOfDateOnly>
</PropertyGroup>

after import of Microsoft.CSharp.targets, I have this (dependant of where you install VS

<Import Project="C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\TextTemplating\v10.0\Microsoft.TextTemplating.targets" />

On my build server I then have the following script to run the text transformation before the actual build, to get the last changeset number on TFS

set _Path="C:\Build_Source\foo"

pushd %_Path% 
"%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\IDE\tf.exe" history . /r /noprompt /stopafter:1 /Version:W > bar
FOR /f "tokens=1" %%foo in ('findstr /R "^[0-9][0-9]*" bar') do set _BuildVersion=5.0.%BUILD_NUMBER%.%%foo
del bar
popd

echo %BUILD_NUMBER%
echo %_BuildVersion%
cd C:\Program Files (x86)\Jenkins\jobs\MyJob\workspace\MyProject
MSBuild MyProject.csproj /t:TransformAll 
...
<rest of bld script>

This way I can keep track of builds AND changesets, so if I haven't checked anything in since last build, the last digit should not change, however I might have made changes to the build process, hence the need for the second last number. Of course if you make multiple check-ins before a build you only get the last change reflected in the version. I guess you could concatenate of that is required.

I'm sure you can do something fancier and call TFS directly from within the tt Template, however this works for me.

I can then get my version at runtime like this

Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
return fvi.FileVersion;

Sharing a variable between multiple different threads

Using static will not help your case.

Using synchronize locks a variable when it is in use by another thread.

You should use volatile keyword to keep the variable updated among all threads.

Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem.

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

string.isNullOrWhiteSpace(text) should be used in most cases as it also includes a blank string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            var str = "";

            Console.WriteLine(string.IsNullOrWhiteSpace(str));              

        }
    }
}

It returns True!

How to define a circle shape in an Android XML drawable file?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/text_color_green"/>
            <!-- Set the same value for both width and height to get a circular shape -->
            <size android:width="250dp" android:height="250dp"/>
        </shape>
    </item>
</selector>

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Unix epoch time to Java Date object

To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.

long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)

JavaScript window resize event

You can use following approach which is ok for small projects

<body onresize="yourHandler(event)">

_x000D_
_x000D_
function yourHandler(e) {
  console.log('Resized:', e.target.innerWidth)
}
_x000D_
<body onresize="yourHandler(event)">
  Content... (resize browser to see)
</body>
_x000D_
_x000D_
_x000D_

How to sum digits of an integer in java?

In Java 8, this is possible in a single line of code as follows:

int sum = Pattern.compile("")
        .splitAsStream(factorialNumber.toString())
        .mapToInt(Integer::valueOf)
        .sum();

How do I put hint in a asp:textbox

Just write like this:

<asp:TextBox ID="TextBox1" runat="server" placeholder="hi test"></asp:TextBox>

Angular 4: How to include Bootstrap?

Angular 4 - Bootstrap / @ng-bootstrap setup

First install bootstrap into your project using below command:

npm install --save bootstrap

Then add this line "../node_modules/bootstrap/dist/css/bootstrap.min.css" to angular-cli.json file (root folder) in styles

"styles": [
   "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   "styles.css"
],

After installing the above dependencies, install ng-bootstrap via:

npm install --save @ng-bootstrap/ng-bootstrap

Once installed you need to import main module.

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

After this, you can use All the Bootstrap widgets (ex. carousel, modal, popovers, tooltips, tabs etc.) and several additional goodies ( datepicker, rating, timepicker, typeahead).

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

jQuery: how to change title of document during .ready()?

This works fine in all browser...

$(document).attr("title", "New Title");

Works in IE too

TypeError: $(...).autocomplete is not a function

Just add these to libraries to your project:

<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>

Save and reload. You're good to go.

How to Make A Chevron Arrow Using CSS?

You can use the before or after pseudo-element and apply some CSS to it. There are various ways. You can add both before and after, and rotate and position each of them to form one of the bars. An easier solution is adding two borders to just the before element and rotate it using transform: rotate.

Scroll down for a different solution that uses an actual element instead of the pseuso elements

In this case, I've added the arrows as bullets in a list and used em sizes to make them size properly with the font of the list.

_x000D_
_x000D_
ul {_x000D_
    list-style: none;_x000D_
}_x000D_
_x000D_
ul.big {_x000D_
    list-style: none;_x000D_
    font-size: 300%_x000D_
}_x000D_
_x000D_
li::before {_x000D_
    position: relative;_x000D_
    /* top: 3pt; Uncomment this to lower the icons as requested in comments*/_x000D_
    content: "";_x000D_
    display: inline-block;_x000D_
    /* By using an em scale, the arrows will size with the font */_x000D_
    width: 0.4em;_x000D_
    height: 0.4em;_x000D_
    border-right: 0.2em solid black;_x000D_
    border-top: 0.2em solid black;_x000D_
    transform: rotate(45deg);_x000D_
    margin-right: 0.5em;_x000D_
}_x000D_
_x000D_
/* Change color */_x000D_
li:hover {_x000D_
  color: red; /* For the text */_x000D_
}_x000D_
li:hover::before {_x000D_
  border-color: red; /* For the arrow (which is a border) */_x000D_
}
_x000D_
<ul>_x000D_
    <li>Item1</li>_x000D_
    <li>Item2</li>_x000D_
    <li>Item3</li>_x000D_
    <li>Item4</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="big">_x000D_
    <li>Item1</li>_x000D_
    <li>Item2</li>_x000D_
    <li>Item3</li>_x000D_
    <li>Item4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Of course you don't need to use before or after, you can apply the same trick to a normal element as well. For the list above it is convenient, because you don't need additional markup. But sometimes you may want (or need) the markup anyway. You can use a div or span for that, and I've even seen people even recycle the i element for 'icons'. So that markup could look like below. Whether using <i> for this is right is debatable, but you can use span for this as well to be on the safe side.

_x000D_
_x000D_
/* Default icon formatting */_x000D_
i {_x000D_
  display: inline-block;_x000D_
  font-style: normal;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
/* Additional formatting for arrow icon */_x000D_
i.arrow {_x000D_
    /* top: 2pt; Uncomment this to lower the icons as requested in comments*/_x000D_
    width: 0.4em;_x000D_
    height: 0.4em;_x000D_
    border-right: 0.2em solid black;_x000D_
    border-top: 0.2em solid black;_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
And so you can have an <i class="arrow" title="arrow icon"></i> in your text._x000D_
This arrow is <i class="arrow" title="arrow icon"></i> used to be deliberately lowered slightly on request._x000D_
I removed that for the general public <i class="arrow" title="arrow icon"></i> but you can uncomment the line with 'top' <i class="arrow" title="arrow icon"></i> to restore that effect.
_x000D_
_x000D_
_x000D_

If you seek more inspiration, make sure to check out this awesome library of pure CSS icons by Nicolas Gallagher. :)

How to draw a path on a map using kml file?

Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:

 if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                    && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

GeoPoint can be less than zero as well, I switch mine to:

     if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
                    && gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {

Thank you :D

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

document.write(curr_date + "-" + curr_month + "-" + curr_year);

using this you can format date.

you can change the appearance in the way you want then

for more info you can visit here

Calculate correlation for more than two variables?

Use the same function (cor) on a data frame, e.g.:

> cor(VADeaths)
             Rural Male Rural Female Urban Male Urban Female
Rural Male    1.0000000    0.9979869  0.9841907    0.9934646
Rural Female  0.9979869    1.0000000  0.9739053    0.9867310
Urban Male    0.9841907    0.9739053  1.0000000    0.9918262
Urban Female  0.9934646    0.9867310  0.9918262    1.0000000

Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:

> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
            mpg        cyl       disp         hp        drat         wt        qsec         vs          am       gear        carb
mpg   1.0000000 -0.8521620 -0.8475514 -0.7761684  0.68117191 -0.8676594  0.41868403  0.6640389  0.59983243  0.4802848 -0.55092507
cyl  -0.8521620  1.0000000  0.9020329  0.8324475 -0.69993811  0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866  0.52698829
disp -0.8475514  0.9020329  1.0000000  0.7909486 -0.71021393  0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692  0.39497686
hp   -0.7761684  0.8324475  0.7909486  1.0000000 -0.44875912  0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043  0.74981247
drat  0.6811719 -0.6999381 -0.7102139 -0.4487591  1.00000000 -0.7124406  0.09120476  0.4402785  0.71271113  0.6996101 -0.09078980
wt   -0.8676594  0.7824958  0.8879799  0.6587479 -0.71244065  1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870  0.42760594
qsec  0.4186840 -0.5912421 -0.4336979 -0.7082234  0.09120476 -0.1747159  1.00000000  0.7445354 -0.22986086 -0.2126822 -0.65624923
vs    0.6640389 -0.8108118 -0.7104159 -0.7230967  0.44027846 -0.5549157  0.74453544  1.0000000  0.16834512  0.2060233 -0.56960714
am    0.5998324 -0.5226070 -0.5912270 -0.2432043  0.71271113 -0.6924953 -0.22986086  0.1683451  1.00000000  0.7940588  0.05753435
gear  0.4802848 -0.4926866 -0.5555692 -0.1257043  0.69961013 -0.5832870 -0.21268223  0.2060233  0.79405876  1.0000000  0.27407284
carb -0.5509251  0.5269883  0.3949769  0.7498125 -0.09078980  0.4276059 -0.65624923 -0.5696071  0.05753435  0.2740728  1.00000000

Syntax for a single-line Bash infinite while loop

You can also make use of until command:

until ((0)); do foo; sleep 2; done

Note that in contrast to while, until would execute the commands inside the loop as long as the test condition has an exit status which is not zero.


Using a while loop:

while read i; do foo; sleep 2; done < /dev/urandom

Using a for loop:

for ((;;)); do foo; sleep 2; done

Another way using until:

until [ ]; do foo; sleep 2; done

Authorize a non-admin developer in Xcode / Mac OS

Ned Deily's solution works perfectly fine, provided your user is allowed to sudo.

If he's not, you can su to an admin account, then use his dscl . append /Groups/_developer GroupMembership $user, where $user is the username.

However, I mistakenly thought it did not because I wrongly typed in the user's name in the command and it silently fails.

Therefore, after entering this command, you should proof-check it. This will check if $user is in $group, where the variables represent respectively the user name and the group name.

dsmemberutil checkmembership -U $user -G $group

This command will either print the message user is not a member of the group or user is a member of the group.

Getting attributes of a class

If you want to "get" an attribute, there is a very simple answer, which should be obvious: getattr

class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
    return self.a

>>> getattr(MyClass, 'a')
'12'

>>> getattr(MyClass, 'myfunc')
<function MyClass.myfunc at 0x10de45378>

It works dandy both in Python 2.7 and Python 3.x.

If you want a list of these items, you will still need to use inspect.

Android: Tabs at the BOTTOM

I recomend use this code for stable work, it optimized for nested fragments in tab (for example nested MapFragment) and tested on "do not keep activities": https://stackoverflow.com/a/23150258/2765497

Add single element to array in numpy

append() creates a new array which can be the old array with the appended element.

I think it's more normal to use the proper method for adding an element:

a = numpy.append(a, a[0])

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

npm install errors with Error: ENOENT, chmod

  1. Install latest version of node
  2. Run: npm cache clean
  3. Run: npm install cordova -g

Database Diagram Support Objects cannot be Installed ... no valid owner

This fixed it for me. It sets the owner found under the 'files' section of the database properties window, and is as scripted by management studio.

USE [your_db_name]
GO
EXEC dbo.sp_changedbowner @loginame = N'sa', @map = false
GO

According to the sp_changedbowner documentation this is deprecated now.

Based on Israel's answer. Aaron's answer is the non-deprecated variation of this.

CSS Background image not loading

I found the problem was you can't use short URL for image "img/image.jpg"

you should use the full URL "http://www.website.com/img/image.jpg", yet I don't know why !!

How to get an Array with jQuery, multiple <input> with the same name

To catch the names array, i use that:

$("input[name*='task']")

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

fail to change placeholder color with Bootstrap 3

Assign the placeholder to a class selector like this:

.form-control::-webkit-input-placeholder { color: white; }  /* WebKit, Blink, Edge */
.form-control:-moz-placeholder { color: white; }  /* Mozilla Firefox 4 to 18 */
.form-control::-moz-placeholder { color: white; }  /* Mozilla Firefox 19+ */
.form-control:-ms-input-placeholder { color: white; }  /* Internet Explorer 10-11 */
.form-control::-ms-input-placeholder { color: white; }  /* Microsoft Edge */

It will work then since a stronger selector was probably overriding your global. I'm on a tablet so i cant inspect and confirm which stronger selector it was :) But it does work I tried it in your fiddle.

This also answers your second question. By assigning it to a class or id and giving an input only that class you can control what inputs to style.

failed to find target with hash string 'android-22'

I created a new Cordova project, which created with latest android target android level 23. when i run it works. if i changed desire android target value from 23 to 22. and refresh the Gradle build from the Andoid Studio. now it's fail when i run it. i got the following build error.

project-android /CordovaLib/src/org/apache/cordova/CordovaInterfaceImpl.java Error:(217, 22) error: cannot find symbol method requestPermissions(String[],int)

I changed the target level in these files.

project.properties
AndroidManifest.xml

and inside CordovaLib folder.

project.properties

However, i also have another project which is using the android target level 22, whenever i run that project, it runs. Now my question is can we specify the desire android level at the time of creating the project?

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I recently ran into the same problem. I had to change my virtual hosts from:

<VirtualHost *:80>
  ServerName local.example.com

  DocumentRoot /home/example/public

  <Directory />
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

To:

<VirtualHost *:80>
  ServerName local.example.com

  DocumentRoot /home/example/public

  <Directory />
    Options All
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

Trim specific character from a string

The best way to resolve this task is (similar with PHP trim function):

_x000D_
_x000D_
function trim( str, charlist ) {_x000D_
  if ( typeof charlist == 'undefined' ) {_x000D_
    charlist = '\\s';_x000D_
  }_x000D_
  _x000D_
  var pattern = '^[' + charlist + ']*(.*?)[' + charlist + ']*$';_x000D_
  _x000D_
  return str.replace( new RegExp( pattern ) , '$1' )_x000D_
}_x000D_
_x000D_
document.getElementById( 'run' ).onclick = function() {_x000D_
  document.getElementById( 'result' ).value = _x000D_
  trim( document.getElementById( 'input' ).value,_x000D_
  document.getElementById( 'charlist' ).value);_x000D_
}
_x000D_
<div>_x000D_
  <label for="input">Text to trim:</label><br>_x000D_
  <input id="input" type="text" placeholder="Text to trim" value="dfstextfsd"><br>_x000D_
  <label for="charlist">Charlist:</label><br>_x000D_
  <input id="charlist" type="text" placeholder="Charlist" value="dfs"><br>_x000D_
  <label for="result">Result:</label><br>_x000D_
  <input id="result" type="text" placeholder="Result" disabled><br>_x000D_
  <button type="button" id="run">Trim it!</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

P.S.: why i posted my answer, when most people already done it before? Because i found "the best" mistake in all of there answers: all used the '+' meta instead of '*', 'cause trim must remove chars IF THEY ARE IN START AND/OR END, but it return original string in else case.

sorting integers in order lowest to highest java

For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n), where n is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.

So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....

How do I import other TypeScript files?

Quick Easy Process in Visual Studio

Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..

/// <reference path="../../components/someclass.ts"/>

how to configure hibernate config file for sql server

The connection URL should look like this for SQL Server:

jdbc:sqlserver://serverName[\instanceName][:port][;databaseName=your_db_name]

Examples:

jdbc:sqlserver://localhost
jdbc:sqlserver://127.0.0.1\INGESQL:1433;databaseName=datatest
...

Session timeout in ASP.NET

That is usually all that you need to do...

Are you sure that after 20 minutes, the reason that the session is being lost is from being idle though...

There are many reasons as to why the session might be cleared. You can enable event logging for IIS and can then use the event viewer to see reasons why the session was cleared...you might find that it is for other reasons perhaps?

You can also read the documentation for event messages and the associated table of events.

How to sort a list of strings?

It is also worth noting the sorted() function:

for x in sorted(list):
    print x

This returns a new, sorted version of a list without changing the original list.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

Oracle SQL Query for listing all Schemas in a DB

select distinct owner 
from dba_segments
where owner in (select username from dba_users where default_tablespace not in ('SYSTEM','SYSAUX'));

SQL Server function to return minimum date (January 1, 1753)

As I can not comment on the accepted answer due to insufficeint reputation points my comment comes as a reply.

using the select cast('1753-1-1' as datetime) is due to fail if run on a database with regional settings not accepting a datestring of YYYY-MM-DD format.

Instead use the select cast(-53690 as datetime) or a Convert with specified datetime format.

Put request with simple string as request body

axios.put(url,{body},{headers:{}})

example:

const body = {title: "what!"}
const api = {
  apikey: "safhjsdflajksdfh",
  Authorization: "Basic bwejdkfhasjk"
}

axios.put('https://api.xxx.net/xx', body, {headers: api})

Python read next()

next() does not work in your case because you first call readlines() which basically sets the file iterator to point to the end of file.

Since you are reading in all the lines anyway you can refer to the next line using an index:

filne = "in"
with open(filne, 'r+') as f:
    lines = f.readlines()
    for i in range(0, len(lines)):
        line = lines[i]
        print line
        if line[:5] == "anim ":
            ne = lines[i + 1] # you may want to check that i < len(lines)
            print ' ne ',ne,'\n'
            break

Responsive Bootstrap Jumbotron Background Image

You could try this:

Simply place the code in a style tag in the head of the html file

_x000D_
_x000D_
<style>_x000D_
        .jumbotron {_x000D_
            background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
        }_x000D_
</style>
_x000D_
_x000D_
_x000D_

or put it in a separate css file as shown below

_x000D_
_x000D_
        .jumbotron {_x000D_
            background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
        }
_x000D_
_x000D_
_x000D_

use center center to center the image horizontally and vertically. use cover to make the image fill out the jumbotron space and finally no-repeat so that the image is not repeated.

Download TS files from video stream

I needed to download HLS video and audio streams from a e-learning portal with session-protected content with application/mp2t MIME content type.

Manually copying all authentication headers into the downloading scripts would be too cumbersome.

But the task got much easier with help of Video DownloadHelper Firefox extension and it's Companion App. It allowed to download both m3u8 playlists with TS chunks lists and actual video and audio streams into mp4 files via a click of button while correctly preserving authentication headers.

The resulting separate video and audio files can be merged with ffmpeg:

ffmpeg -i video.mp4 -i audio.mp4 -acodec copy -vcodec copy video-and-audio.mp4 

or with mp4box:

mp4box -add audio.mp4#audio video.mp4 -out video-and-audio.mp4

Tried Video DownloadHelper Chrome extension too, but it didn't work for me.

C# elegant way to check if a property's property is null

I saw something in the new C# 6.0, this is by using '?' instead of checking

for example instead of using

if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)
{ 
  var city = person.contact.address.city;
}

you simply use

var city = person?.contact?.address?.city;

I hope it helped somebody.


UPDATE:

You could do like this now

 var city = (Person != null)? 
           ((Person.Contact!=null)? 
              ((Person.Contact.Address!= null)?
                      ((Person.Contact.Address.City!=null)? 
                                 Person.Contact.Address.City : null )
                       :null)
               :null)
            : null;

How to implement a binary search tree in Python?

class Node:
    rChild,lChild,parent,data = None,None,None,0    

def __init__(self,key):
    self.rChild = None
    self.lChild = None
    self.parent = None
    self.data = key 

class Tree:
    root,size = None,0
    def __init__(self):
        self.root = None
        self.size = 0
    def insert(self,someNumber):
        self.size = self.size+1
        if self.root is None:
            self.root = Node(someNumber)
        else:
            self.insertWithNode(self.root, someNumber)    

    def insertWithNode(self,node,someNumber):
        if node.lChild is None and node.rChild is None:#external node
            if someNumber > node.data:
                newNode = Node(someNumber)
                node.rChild = newNode
                newNode.parent = node
            else:
                newNode = Node(someNumber)
                node.lChild = newNode
                newNode.parent = node
        else: #not external
            if someNumber > node.data:
                if node.rChild is not None:
                    self.insertWithNode(node.rChild, someNumber)
                else: #if empty node
                    newNode = Node(someNumber)
                    node.rChild = newNode
                    newNode.parent = node 
            else:
                if node.lChild is not None:
                    self.insertWithNode(node.lChild, someNumber)
                else:
                    newNode = Node(someNumber)
                    node.lChild = newNode
                    newNode.parent = node                    

    def printTree(self,someNode):
        if someNode is None:
            pass
        else:
            self.printTree(someNode.lChild)
            print someNode.data
            self.printTree(someNode.rChild)

def main():  
    t = Tree()
    t.insert(5)  
    t.insert(3)
    t.insert(7)
    t.insert(4)
    t.insert(2)
    t.insert(1)
    t.insert(6)
    t.printTree(t.root)

if __name__ == '__main__':
    main()

My solution.

ASP.NET MVC - Extract parameter of an URL

public ActionResult Index(int id,string value)

This function get values form URL After that you can use below function

Request.RawUrl - Return complete URL of Current page

RouteData.Values - Return Collection of Values of URL

Request.Params - Return Name Value Collections

How to add multiple jar files in classpath in linux

For linux users, you should know the following:

  1. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp (--classpath) requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I think your EmpID column is string and you forget to use ' ' in your value.

Because when you write EmpID=" + id.Text, your command looks like EmpID = 12345 instead of EmpID = '12345'

Change your SqlCommand to

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);

Or as a better way you can (and should) always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

I think your EmpID column keeps your employee id's, so it's type should some numerical type instead of character.

PKIX path building failed in Java application

If you are using Eclipse just cross check in Eclipse Windows--> preferences---->java---> installed JREs is pointing the current JRE and the JRE where you have configured your certificate. If not remove the JRE and add the jre where your certificate is installed

Insert string in beginning of another string

private static void appendZeroAtStart() {
        String strObj = "11";
        int maxLegth = 5;

        StringBuilder sb = new StringBuilder(strObj);
        if (sb.length() <= maxLegth) {
            while (sb.length() < maxLegth) {
                sb.insert(0, '0');
            }
        } else {
            System.out.println("error");
        }

        System.out.println("result: " + sb);

    }

How can I concatenate a string within a loop in JSTL/JSP?

Is JSTL's join(), what you searched for?

<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />

Read properties file outside JAR file

This works for me. Load your properties file from current directory.

Attention: The method Properties#load uses ISO-8859-1 encoding.

Properties properties = new Properties();
properties.load(new FileReader(new File(".").getCanonicalPath() + File.separator + "java.properties"));
properties.forEach((k, v) -> {
            System.out.println(k + " : " + v);
        });

Make sure, that java.properties is at the current directory . You can just write a little startup script that switches into to the right directory in before, like

#! /bin/bash
scriptdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 
cd $scriptdir
java -jar MyExecutable.jar
cd -

In your project just put the java.properties file in your project root, in order to make this code work from your IDE as well.

Range of values in C Int and Long 32 - 64 bits

In fact, unsigned int on most modern processors (ARM, Intel/AMD, Alpha, SPARC, Itanium ,PowerPC) will have a range of 0 to 2^32 - 1 which is 4,294,967,295 = 0xffffffff because int (both signed and unsigned) will be 32 bits long and the largest one is as stated.

(unsigned short will have maximal value 2^16 - 1 = 65,535 )

(unsigned) long long int will have a length of 64 bits (long int will be enough under most 64 bit Linuxes, etc, but the standard promises 64 bits for long long int). Hence these have the range 0 to 2^64 - 1 = 18446744073709551615

From Now() to Current_timestamp in Postgresql

You can also use now() in Postgres. The problem is you can't add/subtract integers from timestamp or timestamptz. You can either do as Mark Byers suggests and subtract an interval, or use the date type which does allow you to add/subtract integers

SELECT now()::date + 100 AS date1, current_date - 100 AS date2

Getting list of files in documents folder

Apple states about NSSearchPathForDirectoriesInDomains(_:_:_:):

You should consider using the FileManager methods urls(for:in:) and url(for:in:appropriateFor:create:) which return URLs, which are the preferred format.


With Swift 5, FileManager has a method called contentsOfDirectory(at:includingPropertiesForKeys:options:). contentsOfDirectory(at:includingPropertiesForKeys:options:) has the following declaration:

Performs a shallow search of the specified directory and returns URLs for the contained items.

func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]

Therefore, in order to retrieve the urls of the files contained in documents directory, you can use the following code snippet that uses FileManager's urls(for:in:) and contentsOfDirectory(at:includingPropertiesForKeys:options:) methods:

guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

do {
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])

    // Print the urls of the files contained in the documents directory
    print(directoryContents)
} catch {
    print("Could not search for urls of files in documents directory: \(error)")
}

As an example, the UIViewController implementation below shows how to save a file from app bundle to documents directory and how to get the urls of the files saved in documents directory:

import UIKit

class ViewController: UIViewController {

    @IBAction func copyFile(_ sender: UIButton) {
        // Get file url
        guard let fileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }

        // Create a destination url in document directory for file
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")

        // Copy file to document directory
        if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
            do {
                try FileManager.default.copyItem(at: fileUrl, to: documentDirectoryFileUrl)
                print("Copy item succeeded")
            } catch {
                print("Could not copy file: \(error)")
            }
        }
    }

    @IBAction func displayUrls(_ sender: UIButton) {
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

        do {
            let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])

            // Print the urls of the files contained in the documents directory
            print(directoryContents) // may print [] or [file:///private/var/mobile/Containers/Data/Application/.../Documents/Movie.mov]
        } catch {
            print("Could not search for urls of files in documents directory: \(error)")
        }
    }

}

How to automatically crop and center an image

One solution is to use a background image centered within an element sized to the cropped dimensions.


Basic example

_x000D_
_x000D_
.center-cropped {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-position: center center;_x000D_
  background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="center-cropped" _x000D_
     style="background-image: url('http://placehold.it/200x200');">_x000D_
</div>
_x000D_
_x000D_
_x000D_


Example with img tag

This version retains the img tag so that we do not lose the ability to drag or right-click to save the image. Credit to Parker Bennett for the opacity trick.

_x000D_
_x000D_
.center-cropped {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-position: center center;_x000D_
  background-repeat: no-repeat;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
/* Set the image to fill its parent and make transparent */_x000D_
.center-cropped img {_x000D_
  min-height: 100%;_x000D_
  min-width: 100%;_x000D_
  /* IE 8 */_x000D_
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
  /* IE 5-7 */_x000D_
  filter: alpha(opacity=0);_x000D_
  /* modern browsers */_x000D_
  opacity: 0;_x000D_
}
_x000D_
<div class="center-cropped" _x000D_
     style="background-image: url('http://placehold.it/200x200');">_x000D_
  <img src="http://placehold.it/200x200" />_x000D_
</div>
_x000D_
_x000D_
_x000D_


object-fit/-position

See supported browsers.

The CSS3 Images specification defines the object-fit and object-position properties which together allow for greater control over the scale and position of the image content of an img element. With these, it will be possible to achieve the desired effect:

_x000D_
_x000D_
.center-cropped {_x000D_
  object-fit: none; /* Do not scale the image */_x000D_
  object-position: center; /* Center the image within the element */_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<img class="center-cropped" src="http://placehold.it/200x200" />
_x000D_
_x000D_
_x000D_

DateTime.MinValue and SqlDateTime overflow

Well... its quite simple to get a SQL min date

DateTime sqlMinDateAsNetDateTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value;

How can I make an entire HTML form "readonly"?

Another simple way that's supported by all browsers would be:

HTML:

<form class="disabled">
  <input type="text" name="name" />
  <input type="radio" name="gender" value="male">
  <input type="radio" name="gender" value="female">
  <input type="checkbox" name="vegetarian">
</form>

CSS:

.disabled {
  pointer-events: none;
  opacity: .4;
}

But be aware, that the tabbing still works with this approach and the elements with focus can still be manipulated by the user.

What is difference between mutable and immutable String in java

A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.

PHP + MySQL transactions examples

When using PDO connection:

$pdo = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8', $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // this is important
]);

I often use the following code for transaction management:

function transaction(Closure $callback)
{
    global $pdo; // let's assume our PDO connection is in a global var

    // start the transaction outside of the try block, because
    // you don't want to rollback a transaction that failed to start
    $pdo->beginTransaction(); 
    try
    {
        $callback();
        $pdo->commit(); 
    }
    catch (Exception $e) // it's better to replace this with Throwable on PHP 7+
    {
        $pdo->rollBack();
        throw $e; // we still have to complain about the exception
    }
}

Usage example:

transaction(function()
{
    global $pdo;

    $pdo->query('first query');
    $pdo->query('second query');
    $pdo->query('third query');
});

This way the transaction-management code is not duplicated across the project. Which is a good thing, because, judging from other PDO-ralated answers in this thread, it's easy to make mistakes in it. The most common ones being forgetting to rethrow the exception and starting the transaction inside the try block.

Getting data-* attribute for onclick event for an html element

Check if the data attribute is present, then do the stuff...

$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
                        if(e.target.getAttribute('data-title')) {
                            var careerTitle = $(this).attr('data-title');
                            if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
                        }
                });

Div not expanding even with content inside

Floated elements don’t take up any vertical space in their containing element.

All of your elements inside #albumhold are floated, apart from #albumhead, which doesn’t look like it’d take up much space.

However, if you add overflow: hidden; to #albumhold (or some other CSS to clear floats inside it), it will expand its height to encompass its floated children.

Understanding unique keys for array children in React.js

Be careful when iterating over arrays!!

It is a common misconception that using the index of the element in the array is an acceptable way of suppressing the error you are probably familiar with:

Each child in an array should have a unique "key" prop.

However, in many cases it is not! This is anti-pattern that can in some situations lead to unwanted behavior.


Understanding the key prop

React uses the key prop to understand the component-to-DOM Element relation, which is then used for the reconciliation process. It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one. It is also important that these keys remain static throughout all re-renders in order to maintain best performance.

That being said, one does not always need to apply the above, provided it is known that the array is completely static. However, applying best practices is encouraged whenever possible.

A React developer said in this GitHub issue:

  • key is not really about performance, it's more about identity (which in turn leads to better performance). randomly assigned and changing values are not identity
  • We can't realistically provide keys [automatically] without knowing how your data is modeled. I would suggest maybe using some sort of hashing function if you don't have ids
  • We already have internal keys when we use arrays, but they are the index in the array. When you insert a new element, those keys are wrong.

In short, a key should be:

  • Unique - A key cannot be identical to that of a sibling component.
  • Static - A key should not ever change between renders.

Using the key prop

As per the explanation above, carefully study the following samples and try to implement, when possible, the recommended approach.


Bad (Potentially)

<tbody>
    {rows.map((row, i) => {
        return <ObjectRow key={i} />;
    })}
</tbody>

This is arguably the most common mistake seen when iterating over an array in React. This approach isn't technically "wrong", it's just... "dangerous" if you don't know what you are doing. If you are iterating through a static array then this is a perfectly valid approach (e.g. an array of links in your navigation menu). However, if you are adding, removing, reordering or filtering items, then you need to be careful. Take a look at this detailed explanation in the official documentation.

_x000D_
_x000D_
class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      arr: ["Item 1"]
    }
  }
  
  click = () => {
    this.setState({
      arr: ['Item ' + (this.state.arr.length+1)].concat(this.state.arr),
    });
  }
  
  render() {
    return(
      <div>
        <button onClick={this.click}>Add</button>
        <ul>
          {this.state.arr.map(
            (item, i) => <Item key={i} text={"Item " + i}>{item + " "}</Item>
          )}
        </ul>
      </div>
    );
  }
}

const Item = (props) => {
  return (
    <li>
      <label>{props.children}</label>
      <input value={props.text} />
    </li>
  );
}

ReactDOM.render(<MyApp />, document.getElementById("app"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
_x000D_
_x000D_
_x000D_

In this snippet we are using a non-static array and we are not restricting ourselves to using it as a stack. This is an unsafe approach (you'll see why). Note how as we add items to the beginning of the array (basically unshift), the value for each <input> remains in place. Why? Because the key doesn't uniquely identify each item.

In other words, at first Item 1 has key={0}. When we add the second item, the top item becomes Item 2, followed by Item 1 as the second item. However, now Item 1 has key={1} and not key={0} anymore. Instead, Item 2 now has key={0}!!

As such, React thinks the <input> elements have not changed, because the Item with key 0 is always at the top!

So why is this approach only sometimes bad?

This approach is only risky if the array is somehow filtered, rearranged, or items are added/removed. If it is always static, then it's perfectly safe to use. For example, a navigation menu like ["Home", "Products", "Contact us"] can safely be iterated through with this method because you'll probably never add new links or rearrange them.

In short, here's when you can safely use the index as key:

  • The array is static and will never change.
  • The array is never filtered (display a subset of the array).
  • The array is never reordered.
  • The array is used as a stack or LIFO (last in, first out). In other words, adding can only be done at the end of the array (i.e push), and only the last item can ever be removed (i.e pop).

Had we instead, in the snippet above, pushed the added item to the end of the array, the order for each existing item would always be correct.


Very bad

<tbody>
    {rows.map((row) => {
        return <ObjectRow key={Math.random()} />;
    })}
</tbody>

While this approach will probably guarantee uniqueness of the keys, it will always force react to re-render each item in the list, even when this is not required. This a very bad solution as it greatly impacts performance. Not to mention that one cannot exclude the possibility of a key collision in the event that Math.random() produces the same number twice.

Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.


Very good

<tbody>
    {rows.map((row) => {
        return <ObjectRow key={row.uniqueId} />;
    })}
</tbody>

This is arguably the best approach because it uses a property that is unique for each item in the dataset. For example, if rows contains data fetched from a database, one could use the table's Primary Key (which typically is an auto-incrementing number).

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys


Good

componentWillMount() {
  let rows = this.props.rows.map(item => { 
    return {uid: SomeLibrary.generateUniqueID(), value: item};
  });
}

...

<tbody>
    {rows.map((row) => {
        return <ObjectRow key={row.uid} />;
    })}
</tbody>

This is also a good approach. If your dataset does not contain any data that guarantees uniqueness (e.g. an array of arbitrary numbers), there is a chance of a key collision. In such cases, it is best to manually generate a unique identifier for each item in the dataset before iterating over it. Preferably when mounting the component or when the dataset is received (e.g. from props or from an async API call), in order to do this only once, and not each time the component re-renders. There are already a handful of libraries out there that can provide you such keys. Here is one example: react-key-index.

Deprecated meaning?

Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.

  1. Yes, otherwise it wouldn't be called "deprecated"

  2. Unless stated otherwise in docs, it should be the same as before

  3. No, but if there were problems in v1 they aren't about to fix them

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Here are the significant differences between lateinit var and by lazy { ... } delegated property:

  • lazy { ... } delegate can only be used for val properties, whereas lateinit can only be applied to vars, because it can't be compiled to a final field, thus no immutability can be guaranteed;

  • lateinit var has a backing field which stores the value, and by lazy { ... } creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use lateinit;

  • In addition to vals, lateinit cannot be used for nullable properties or Java primitive types (this is because of null used for uninitialized value);

  • lateinit var can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. by lazy { ... }, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

  • Initialization by lazy { ... } is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using another lazy overload). In the case of lateinit var, it's up to the user's code to initialize the property correctly in multi-threaded environments.

  • A Lazy instance can be saved, passed around and even used for multiple properties. On contrary, lateinit vars do not store any additional runtime state (only null in the field for uninitialized value).

  • If you hold a reference to an instance of Lazy, isInitialized() allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can use property::isInitialized since Kotlin 1.2.

  • A lambda passed to by lazy { ... } may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.

Also, there's another way not mentioned in the question: Delegates.notNull(), which is suitable for deferred initialization of non-null properties, including those of Java primitive types.

How to skip "are you sure Y/N" when deleting files in batch files

You have the following options on Windows command line:

net use [DeviceName [/home[{Password | *}] [/delete:{yes | no}]]

Try like:

net use H: /delete /y

Reinitialize Slick js after successful ajax call

The best way is you should destroy the slick slider after reinitializing it.

function slickCarousel() {
  $('.skills_section').slick({
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1
  });
}
function destroyCarousel() {
  if ($('.skills_section').hasClass('slick-initialized')) {
    $('.skills_section').slick('destroy');
  }      
}

$.ajax({
  type: 'get',
  url: '/public/index',
  dataType: 'script',
  data: data_send,
  success: function() {
    destroyCarousel()
    slickCarousel();
  }
});

Python: Adding element to list while iterating

You could use the islice from itertools to create an iterator over a smaller portion of the list. Then you can append entries to the list without impacting the items you're iterating over:

islice(myarr, 0, len(myarr)-1)

Even better, you don't even have to iterate over all the elements. You can increment a step size.

How to sort an array of ints using a custom comparator?

If you don't want to copy the array (say it is very large), you might want to create a wrapper List<Integer> that can be used in a sort:

final int[] elements = {1, 2, 3, 4};
List<Integer> wrapper = new AbstractList<Integer>() {

        @Override
        public Integer get(int index) {
            return elements[index];
        }

        @Override
        public int size() {
            return elements.length;
        }

        @Override
        public Integer set(int index, Integer element) {
            int v = elements[index];
            elements[index] = element;
            return v;
        }

    };

And now you can do a sort on this wrapper List using a custom comparator.

how to append a css class to an element by javascript?

When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.

Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

document.addClass= function(el, css){
    var tem, C= el.className.split(/\s+/), A=[];    
    while(C.length){
        tem= C.shift();
        if(tem && tem!= css) A[A.length]= tem;
    }
    A[A.length]= css;
    return el.className= A.join(' ');   
}

How do I measure separate CPU core usage for a process?

dstat -C 0,1,2,3 

Will also give you the CPU usage of first 4 cores. Of course, if you have 32 cores then this command gets a little bit longer but useful if you only interested in few cores.

For example, if you only interested in core 3 and 7 then you could do

dstat -C 3,7

AngularJS ng-repeat handle empty list case

Here's a different approach using CSS instead of JavaScript/AngularJS.

CSS:

.emptymsg {
  display: list-item;
}

li + .emptymsg {
  display: none;
}

Markup:

<ul>
    <li ng-repeat="item in filteredItems"> ... </li>
    <li class="emptymsg">No items found</li>
</ul>

If the list is empty, <li ng-repeat="item in filteredItems">, etc. will get commented out and will become a comment instead of a li element.

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

Find where java class is loaded from

Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: -verbose:class

Passing arguments to JavaScript function from code-behind

include script manager

code behind function

ScriptManager.RegisterStartupScript(this, this.GetType(), "HideConfirmBox", "javascript:HideAAConfirmBox(); ", true);

is there any IE8 only css hack?

There are various ways to get a class onto the HTML element, identifying which IE version you're contending with: Modernizr, the HTML 5 Boilerplate, etc - or just roll your own. Then you can use that class (eg .lt-ie9) in a normal CSS selector, no hack needed. If you only want to affect IE8 and not previous versions, put the old value back using a .lt-ie8 selector.

What is Node.js?

I use Node.js at work, and find it to be very powerful. Forced to choose one word to describe Node.js, I'd say "interesting" (which is not a purely positive adjective). The community is vibrant and growing. JavaScript, despite its oddities can be a great language to code in. And you will daily rethink your own understanding of "best practice" and the patterns of well-structured code. There's an enormous energy of ideas flowing into Node.js right now, and working in it exposes you to all this thinking - great mental weightlifting.

Node.js in production is definitely possible, but far from the "turn-key" deployment seemingly promised by the documentation. With Node.js v0.6.x, "cluster" has been integrated into the platform, providing one of the essential building blocks, but my "production.js" script is still ~150 lines of logic to handle stuff like creating the log directory, recycling dead workers, etc. For a "serious" production service, you also need to be prepared to throttle incoming connections and do all the stuff that Apache does for PHP. To be fair, Ruby on Rails has this exact problem. It is solved via two complementary mechanisms: 1) Putting Ruby on Rails/Node.js behind a dedicated webserver (written in C and tested to hell and back) like Nginx (or Apache / Lighttd). The webserver can efficiently serve static content, access logging, rewrite URLs, terminate SSL, enforce access rules, and manage multiple sub-services. For requests that hit the actual node service, the webserver proxies the request through. 2) Using a framework like Unicorn that will manage the worker processes, recycle them periodically, etc. I've yet to find a Node.js serving framework that seems fully baked; it may exist, but I haven't found it yet and still use ~150 lines in my hand-rolled "production.js".

Reading frameworks like Express makes it seem like the standard practice is to just serve everything through one jack-of-all-trades Node.js service ... "app.use(express.static(__dirname + '/public'))". For lower-load services and development, that's probably fine. But as soon as you try to put big time load on your service and have it run 24/7, you'll quickly discover the motivations that push big sites to have well baked, hardened C-code like Nginx fronting their site and handling all of the static content requests (...until you set up a CDN, like Amazon CloudFront)). For a somewhat humorous and unabashedly negative take on this, see this guy.

Node.js is also finding more and more non-service uses. Even if you are using something else to serve web content, you might still use Node.js as a build tool, using npm modules to organize your code, Browserify to stitch it into a single asset, and uglify-js to minify it for deployment. For dealing with the web, JavaScript is a perfect impedance match and frequently that makes it the easiest route of attack. For example, if you want to grovel through a bunch of JSON response payloads, you should use my underscore-CLI module, the utility-belt of structured data.

Pros / Cons:

  • Pro: For a server guy, writing JavaScript on the backend has been a "gateway drug" to learning modern UI patterns. I no longer dread writing client code.
  • Pro: Tends to encourage proper error checking (err is returned by virtually all callbacks, nagging the programmer to handle it; also, async.js and other libraries handle the "fail if any of these subtasks fails" paradigm much better than typical synchronous code)
  • Pro: Some interesting and normally hard tasks become trivial - like getting status on tasks in flight, communicating between workers, or sharing cache state
  • Pro: Huge community and tons of great libraries based on a solid package manager (npm)
  • Con: JavaScript has no standard library. You get so used to importing functionality that it feels weird when you use JSON.parse or some other build in method that doesn't require adding an npm module. This means that there are five versions of everything. Even the modules included in the Node.js "core" have five more variants should you be unhappy with the default implementation. This leads to rapid evolution, but also some level of confusion.

Versus a simple one-process-per-request model (LAMP):

  • Pro: Scalable to thousands of active connections. Very fast and very efficient. For a web fleet, this could mean a 10X reduction in the number of boxes required versus PHP or Ruby
  • Pro: Writing parallel patterns is easy. Imagine that you need to fetch three (or N) blobs from Memcached. Do this in PHP ... did you just write code the fetches the first blob, then the second, then the third? Wow, that's slow. There's a special PECL module to fix that specific problem for Memcached, but what if you want to fetch some Memcached data in parallel with your database query? In Node.js, because the paradigm is asynchronous, having a web request do multiple things in parallel is very natural.
  • Con: Asynchronous code is fundamentally more complex than synchronous code, and the up-front learning curve can be hard for developers without a solid understanding of what concurrent execution actually means. Still, it's vastly less difficult than writing any kind of multithreaded code with locking.
  • Con: If a compute-intensive request runs for, for example, 100 ms, it will stall processing of other requests that are being handled in the same Node.js process ... AKA, cooperative-multitasking. This can be mitigated with the Web Workers pattern (spinning off a subprocess to deal with the expensive task). Alternatively, you could use a large number of Node.js workers and only let each one handle a single request concurrently (still fairly efficient because there is no process recycle).
  • Con: Running a production system is MUCH more complicated than a CGI model like Apache + PHP, Perl, Ruby, etc. Unhandled exceptions will bring down the entire process, necessitating logic to restart failed workers (see cluster). Modules with buggy native code can hard-crash the process. Whenever a worker dies, any requests it was handling are dropped, so one buggy API can easily degrade service for other cohosted APIs.

Versus writing a "real" service in Java / C# / C (C? really?)

  • Pro: Doing asynchronous in Node.js is easier than doing thread-safety anywhere else and arguably provides greater benefit. Node.js is by far the least painful asynchronous paradigm I've ever worked in. With good libraries, it is only slightly harder than writing synchronous code.
  • Pro: No multithreading / locking bugs. True, you invest up front in writing more verbose code that expresses a proper asynchronous workflow with no blocking operations. And you need to write some tests and get the thing to work (it is a scripting language and fat fingering variable names is only caught at unit-test time). BUT, once you get it to work, the surface area for heisenbugs -- strange problems that only manifest once in a million runs -- that surface area is just much much lower. The taxes writing Node.js code are heavily front-loaded into the coding phase. Then you tend to end up with stable code.
  • Pro: JavaScript is much more lightweight for expressing functionality. It's hard to prove this with words, but JSON, dynamic typing, lambda notation, prototypal inheritance, lightweight modules, whatever ... it just tends to take less code to express the same ideas.
  • Con: Maybe you really, really like coding services in Java?

For another perspective on JavaScript and Node.js, check out From Java to Node.js, a blog post on a Java developer's impressions and experiences learning Node.js.


Modules When considering node, keep in mind that your choice of JavaScript libraries will DEFINE your experience. Most people use at least two, an asynchronous pattern helper (Step, Futures, Async), and a JavaScript sugar module (Underscore.js).

Helper / JavaScript Sugar:

  • Underscore.js - use this. Just do it. It makes your code nice and readable with stuff like _.isString(), and _.isArray(). I'm not really sure how you could write safe code otherwise. Also, for enhanced command-line-fu, check out my own Underscore-CLI.

Asynchronous Pattern Modules:

  • Step - a very elegant way to express combinations of serial and parallel actions. My personal reccomendation. See my post on what Step code looks like.
  • Futures - much more flexible (is that really a good thing?) way to express ordering through requirements. Can express things like "start a, b, c in parallel. When A, and B finish, start AB. When A, and C finish, start AC." Such flexibility requires more care to avoid bugs in your workflow (like never calling the callback, or calling it multiple times). See Raynos's post on using futures (this is the post that made me "get" futures).
  • Async - more traditional library with one method for each pattern. I started with this before my religious conversion to step and subsequent realization that all patterns in Async could be expressed in Step with a single more readable paradigm.
  • TameJS - Written by OKCupid, it's a precompiler that adds a new language primative "await" for elegantly writing serial and parallel workflows. The pattern looks amazing, but it does require pre-compilation. I'm still making up my mind on this one.
  • StreamlineJS - competitor to TameJS. I'm leaning toward Tame, but you can make up your own mind.

Or to read all about the asynchronous libraries, see this panel-interview with the authors.

Web Framework:

  • Express Great Ruby on Rails-esk framework for organizing web sites. It uses JADE as a XML/HTML templating engine, which makes building HTML far less painful, almost elegant even.
  • jQuery While not technically a node module, jQuery is quickly becoming a de-facto standard for client-side user interface. jQuery provides CSS-like selectors to 'query' for sets of DOM elements that can then be operated on (set handlers, properties, styles, etc). Along the same vein, Twitter's Bootstrap CSS framework, Backbone.js for an MVC pattern, and Browserify.js to stitch all your JavaScript files into a single file. These modules are all becoming de-facto standards so you should at least check them out if you haven't heard of them.

Testing:

  • JSHint - Must use; I didn't use this at first which now seems incomprehensible. JSLint adds back a bunch of the basic verifications you get with a compiled language like Java. Mismatched parenthesis, undeclared variables, typeos of many shapes and sizes. You can also turn on various forms of what I call "anal mode" where you verify style of whitespace and whatnot, which is OK if that's your cup of tea -- but the real value comes from getting instant feedback on the exact line number where you forgot a closing ")" ... without having to run your code and hit the offending line. "JSHint" is a more-configurable variant of Douglas Crockford's JSLint.
  • Mocha competitor to Vows which I'm starting to prefer. Both frameworks handle the basics well enough, but complex patterns tend to be easier to express in Mocha.
  • Vows Vows is really quite elegant. And it prints out a lovely report (--spec) showing you which test cases passed / failed. Spend 30 minutes learning it, and you can create basic tests for your modules with minimal effort.
  • Zombie - Headless testing for HTML and JavaScript using JSDom as a virtual "browser". Very powerful stuff. Combine it with Replay to get lightning fast deterministic tests of in-browser code.
  • A comment on how to "think about" testing:
    • Testing is non-optional. With a dynamic language like JavaScript, there are very few static checks. For example, passing two parameters to a method that expects 4 won't break until the code is executed. Pretty low bar for creating bugs in JavaScript. Basic tests are essential to making up the verification gap with compiled languages.
    • Forget validation, just make your code execute. For every method, my first validation case is "nothing breaks", and that's the case that fires most often. Proving that your code runs without throwing catches 80% of the bugs and will do so much to improve your code confidence that you'll find yourself going back and adding the nuanced validation cases you skipped.
    • Start small and break the inertial barrier. We are all lazy, and pressed for time, and it's easy to see testing as "extra work". So start small. Write test case 0 - load your module and report success. If you force yourself to do just this much, then the inertial barrier to testing is broken. That's <30 min to do it your first time, including reading the documentation. Now write test case 1 - call one of your methods and verify "nothing breaks", that is, that you don't get an error back. Test case 1 should take you less than one minute. With the inertia gone, it becomes easy to incrementally expand your test coverage.
    • Now evolve your tests with your code. Don't get intimidated by what the "correct" end-to-end test would look like with mock servers and all that. Code starts simple and evolves to handle new cases; tests should too. As you add new cases and new complexity to your code, add test cases to exercise the new code. As you find bugs, add verifications and / or new cases to cover the flawed code. When you are debugging and lose confidence in a piece of code, go back and add tests to prove that it is doing what you think it is. Capture strings of example data (from other services you call, websites you scrape, whatever) and feed them to your parsing code. A few cases here, improved validation there, and you will end up with highly reliable code.

Also, check out the official list of recommended Node.js modules. However, GitHub's Node Modules Wiki is much more complete and a good resource.


To understand Node, it's helpful to consider a few of the key design choices:

Node.js is EVENT BASED and ASYNCHRONOUS / NON-BLOCKING. Events, like an incoming HTTP connection will fire off a JavaScript function that does a little bit of work and kicks off other asynchronous tasks like connecting to a database or pulling content from another server. Once these tasks have been kicked off, the event function finishes and Node.js goes back to sleep. As soon as something else happens, like the database connection being established or the external server responding with content, the callback functions fire, and more JavaScript code executes, potentially kicking off even more asynchronous tasks (like a database query). In this way, Node.js will happily interleave activities for multiple parallel workflows, running whatever activities are unblocked at any point in time. This is why Node.js does such a great job managing thousands of simultaneous connections.

Why not just use one process/thread per connection like everyone else? In Node.js, a new connection is just a very small heap allocation. Spinning up a new process takes significantly more memory, a megabyte on some platforms. But the real cost is the overhead associated with context-switching. When you have 10^6 kernel threads, the kernel has to do a lot of work figuring out who should execute next. A bunch of work has gone into building an O(1) scheduler for Linux, but in the end, it's just way way more efficient to have a single event-driven process than 10^6 processes competing for CPU time. Also, under overload conditions, the multi-process model behaves very poorly, starving critical administration and management services, especially SSHD (meaning you can't even log into the box to figure out how screwed it really is).

Node.js is SINGLE THREADED and LOCK FREE. Node.js, as a very deliberate design choice only has a single thread per process. Because of this, it's fundamentally impossible for multiple threads to access data simultaneously. Thus, no locks are needed. Threads are hard. Really really hard. If you don't believe that, you haven't done enough threaded programming. Getting locking right is hard and results in bugs that are really hard to track down. Eliminating locks and multi-threading makes one of the nastiest classes of bugs just go away. This might be the single biggest advantage of node.

But how do I take advantage of my 16 core box?

Two ways:

  1. For big heavy compute tasks like image encoding, Node.js can fire up child processes or send messages to additional worker processes. In this design, you'd have one thread managing the flow of events and N processes doing heavy compute tasks and chewing up the other 15 CPUs.
  2. For scaling throughput on a webservice, you should run multiple Node.js servers on one box, one per core, using cluster (With Node.js v0.6.x, the official "cluster" module linked here replaces the learnboost version which has a different API). These local Node.js servers can then compete on a socket to accept new connections, balancing load across them. Once a connection is accepted, it becomes tightly bound to a single one of these shared processes. In theory, this sounds bad, but in practice it works quite well and allows you to avoid the headache of writing thread-safe code. Also, this means that Node.js gets excellent CPU cache affinity, more effectively using memory bandwidth.

Node.js lets you do some really powerful things without breaking a sweat. Suppose you have a Node.js program that does a variety of tasks, listens on a TCP port for commands, encodes some images, whatever. With five lines of code, you can add in an HTTP based web management portal that shows the current status of active tasks. This is EASY to do:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(myJavascriptObject.getSomeStatusInfo());
}).listen(1337, "127.0.0.1");

Now you can hit a URL and check the status of your running process. Add a few buttons, and you have a "management portal". If you have a running Perl / Python / Ruby script, just "throwing in a management portal" isn't exactly simple.

But isn't JavaScript slow / bad / evil / spawn-of-the-devil? JavaScript has some weird oddities, but with "the good parts" there's a very powerful language there, and in any case, JavaScript is THE language on the client (browser). JavaScript is here to stay; other languages are targeting it as an IL, and world class talent is competing to produce the most advanced JavaScript engines. Because of JavaScript's role in the browser, an enormous amount of engineering effort is being thrown at making JavaScript blazing fast. V8 is the latest and greatest javascript engine, at least for this month. It blows away the other scripting languages in both efficiency AND stability (looking at you, Ruby). And it's only going to get better with huge teams working on the problem at Microsoft, Google, and Mozilla, competing to build the best JavaScript engine (It's no longer a JavaScript "interpreter" as all the modern engines do tons of JIT compiling under the hood with interpretation only as a fallback for execute-once code). Yeah, we all wish we could fix a few of the odder JavaScript language choices, but it's really not that bad. And the language is so darn flexible that you really aren't coding JavaScript, you are coding Step or jQuery -- more than any other language, in JavaScript, the libraries define the experience. To build web applications, you pretty much have to know JavaScript anyway, so coding with it on the server has a sort of skill-set synergy. It has made me not dread writing client code.

Besides, if you REALLY hate JavaScript, you can use syntactic sugar like CoffeeScript. Or anything else that creates JavaScript code, like Google Web Toolkit (GWT).

Speaking of JavaScript, what's a "closure"? - Pretty much a fancy way of saying that you retain lexically scoped variables across call chains. ;) Like this:

var myData = "foo";
database.connect( 'user:pass', function myCallback( result ) {
    database.query("SELECT * from Foo where id = " + myData);
} );
// Note that doSomethingElse() executes _BEFORE_ "database.query" which is inside a callback
doSomethingElse();

See how you can just use "myData" without doing anything awkward like stashing it into an object? And unlike in Java, the "myData" variable doesn't have to be read-only. This powerful language feature makes asynchronous-programming much less verbose and less painful.

Writing asynchronous code is always going to be more complex than writing a simple single-threaded script, but with Node.js, it's not that much harder and you get a lot of benefits in addition to the efficiency and scalability to thousands of concurrent connections...

SQL Server - Adding a string to a text column (concat equivalent)

UPDATE test SET a = CONCAT(a, "more text")

Metadata file '.dll' could not be found

For me it was wrong folder name. If you close from source that replaces spaces with '%20', you will get such errors. Solution - just rename badly named folders.

Launch a shell command with in a python script, wait for the termination and return to the script

The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

How do I display Ruby on Rails form validation error messages one at a time?

A better idea,

if you want to put the error message just beneath the text field, you can do like this

.row.spacer20top
  .col-sm-6.form-group
    = f.label :first_name, "*Your First Name:"
    = f.text_field :first_name, :required => true, class: "form-control"
    = f.error_message_for(:first_name)

What is error_message_for?
--> Well, this is a beautiful hack to do some cool stuff

# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
  def error_message_for(field_name)
    if self.object.errors[field_name].present?
      model_name              = self.object.class.name.downcase
      id_of_element           = "error_#{model_name}_#{field_name}"
      target_elem_id          = "#{model_name}_#{field_name}"
      class_name              = 'signup-error alert alert-danger'
      error_declaration_class = 'has-signup-error'

      "<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
      "#{self.object.errors[field_name].join(', ')}"\
      "</div>"\
      "<!-- Later JavaScript to add class to the parent element -->"\
      "<script>"\
          "document.onreadystatechange = function(){"\
            "$('##{id_of_element}').parent()"\
            ".addClass('#{error_declaration_class}');"\
          "}"\
      "</script>".html_safe
    end
  rescue
    nil
  end
end

Result enter image description here

Markup Generated after error

<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>

Corresponding SCSS

  .has-signup-error{
    .signup-error{
      background: transparent;
      color: $brand-danger;
      border: none;
    }

    input, select{
      background-color: $bg-danger;
      border-color: $brand-danger;
      color: $gray-base;
      font-weight: 500;
    }

    &.checkbox{
      label{
        &:before{
          background-color: $bg-danger;
          border-color: $brand-danger;
        }
      }
    }

Note: Bootstrap variables used here

Where to put default parameter value in C++?

One more point I haven't found anyone mentioned:

If you have virtual method, each declaration can have its own default value!

It depends on the interface you are calling which value will be used.

Example on ideone

struct iface
{
    virtual void test(int a = 0) { std::cout << a; }
};

struct impl : public iface
{
    virtual void test(int a = 5) override { std::cout << a; }
};

int main()
{
    impl d;
    d.test();
    iface* a = &d;
    a->test();
}

It prints 50

I strongly discourage you to use it like this

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

CSS: styled a checkbox to look like a button, is there a hover?

Do what Kelly said...

BUT. Instead of having the input positioned absolute and top -20px (just hiding it off the page), make the input box hidden.

example:

<input type="checkbox" hidden> 

Works better and can put it anywhere on the page.

How do I delete everything in Redis?

  1. Stop Redis instance.
  2. Delete RDB file.
  3. Start Redis instance.

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

How to create a sleep/delay in nodejs that is Blocking?

It's pretty trivial to implement with native addon, so someone did that: https://github.com/ErikDubbelboer/node-sleep.git

Named parameters in JDBC

To avoid including a large framework, I think a simple homemade class can do the trick.

Example of class to handle named parameters:

public class NamedParamStatement {
    public NamedParamStatement(Connection conn, String sql) throws SQLException {
        int pos;
        while((pos = sql.indexOf(":")) != -1) {
            int end = sql.substring(pos).indexOf(" ");
            if (end == -1)
                end = sql.length();
            else
                end += pos;
            fields.add(sql.substring(pos+1,end));
            sql = sql.substring(0, pos) + "?" + sql.substring(end);
        }       
        prepStmt = conn.prepareStatement(sql);
    }

    public PreparedStatement getPreparedStatement() {
        return prepStmt;
    }
    public ResultSet executeQuery() throws SQLException {
        return prepStmt.executeQuery();
    }
    public void close() throws SQLException {
        prepStmt.close();
    }

    public void setInt(String name, int value) throws SQLException {        
        prepStmt.setInt(getIndex(name), value);
    }

    private int getIndex(String name) {
        return fields.indexOf(name)+1;
    }
    private PreparedStatement prepStmt;
    private List<String> fields = new ArrayList<String>();
}

Example of calling the class:

String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();

Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I don't have the reputation yet to up vote Steve's suggestion, but it solved my problem.

In my case, I received this error because the two table where created using different database engines--one was Innodb and the other MyISAM.

You can change the database type using : ALTER TABLE t ENGINE = MYISAM;

@see http://dev.mysql.com/doc/refman/5.1/en/storage-engine-setting.html

How do I edit $PATH (.bash_profile) on OSX?

If you are using MAC Catalina you need to update the .zshrc file instead of .bash_profile or .profile

How to change visibility of layout programmatically

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I had the same problem today. To fix I downgraded firefox version 51 to 47 and it's working.

Note: I'm using a Linux Ubuntu Mate, in a Virtual Box, with host being another Ubuntu Mate. All OS are 64 bits and firefox also.

How to convert JSON to CSV format and store in a variable

Personally I would use d3-dsv library to do this. Why to reinvent the wheel?


import { csvFormat } from 'd3-dsv';
/**
 * Based on input data convert it to csv formatted string
 * @param (Array) columnsToBeIncluded array of column names (strings)
 *                which needs to be included in the formated csv
 * @param {Array} input array of object which need to be transformed to string
 */
export function convertDataToCSVFormatString(input, columnsToBeIncluded = []) {
  if (columnsToBeIncluded.length === 0) {
    return csvFormat(input);
  }
  return csvFormat(input, columnsToBeIncluded);
}

With tree-shaking you can just import that particular function from d3-dsv library

Parse an URL in JavaScript

This should fix a few edge-cases in kobe's answer:

function getQueryParam(url, key) {
  var queryStartPos = url.indexOf('?');
  if (queryStartPos === -1) {
    return;
  }
  var params = url.substring(queryStartPos + 1).split('&');
  for (var i = 0; i < params.length; i++) {
    var pairs = params[i].split('=');
    if (decodeURIComponent(pairs.shift()) == key) {
      return decodeURIComponent(pairs.join('='));
    }
  }
}

getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"

Function to check if a string is a date

I found my answer here https://stackoverflow.com/a/19271434/1363220, bassically

$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
if($d && $d->format($format) === $date) {
    //it's a proper date!
}
else {
    //it's not a proper date
}

Http Post request with content type application/x-www-form-urlencoded not working in Spring

replace contentType : "application/x-www-form-urlencoded", by dataType : "text" as wildfly 11 doesn't support mentioned contenttype..

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

My App.config looks as below:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

I noticed that there is localDB in the path that you mentioned above and has the version v11.0. So I entered (LocalDB\V11.0) in Add Connection dialogue and it worked for me.

How to concatenate string variables in Bash

Even if the += operator is now permitted, it has been introduced in Bash 3.1 in 2004.

Any script using this operator on older Bash versions will fail with a "command not found" error if you are lucky, or a "syntax error near unexpected token".

For those who cares about backward compatibility, stick with the older standard Bash concatenation methods, like those mentioned in the chosen answer:

foo="Hello"
foo="$foo World"
echo $foo
> Hello World

Letter Count on a string

count_letters=""

number=count_letters.count("")

print number

OS X Bash, 'watch' command

If watch doesn't want to install via

brew install watch

There is another similar/copy version that installed and worked perfectly for me

brew install visionmedia-watch

https://github.com/tj/watch

Java Webservice Client (Best way)

What is the best approach to do this JAVA?

I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:

  1. I don't like its architecture and hate its counter productive deployment model.
  2. I find it to be low quality project.
  3. I don't like its performances (see this benchmark against JAX-WS RI).
  4. It's always a nightmare to setup dependencies (I use Maven and I always have to fight with the gazillion of dependencies) (see #2)
  5. Axis sucked big time and Axis2 isn't better. No, this is not a personal opinion, there is a consensus.
  6. I suffered once, never again.

The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.

I read about SAAJ, looks like that will be more granular level of approach?

To do what?

Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?

Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport.

Can someone send the links for some good tutorials on these topics?

That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:

What are the options we need to use while generating the code using the WSDL2Java?

No options, use wsimport :)

See also

Related questions

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'

This will almost certainly be faster than the conversion to and from a date.

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Can't find @Nullable inside javax.annotation.*

you can add latest version of this by adding following line inside your gradle.build.

implementation group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2'

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Open the project after deleting .idea folder and .dart_tool

How to delete duplicate rows in SQL Server?

I like CTEs and ROW_NUMBER as the two combined allow us to see which rows are deleted (or updated), therefore just change the DELETE FROM CTE... to SELECT * FROM CTE:

WITH CTE AS(
   SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
       RN = ROW_NUMBER()OVER(PARTITION BY col1 ORDER BY col1)
   FROM dbo.Table1
)
DELETE FROM CTE WHERE RN > 1

DEMO (result is different; I assume that it's due to a typo on your part)

COL1    COL2    COL3    COL4    COL5    COL6    COL7
john    1        1       1       1       1       1
sally   2        2       2       2       2       2

This example determines duplicates by a single column col1 because of the PARTITION BY col1. If you want to include multiple columns simply add them to the PARTITION BY:

ROW_NUMBER()OVER(PARTITION BY Col1, Col2, ... ORDER BY OrderColumn)

What is the difference between substr and substring?

The difference is second parameter. Their second parameters, while both numbers, are expecting two different things:

When using substring the second parameter is the first index not to include:

var s = "string";
s.substring(1, 3); // would return 'tr'

var s = "another example";
s.substring(3, 7); // would return 'ther'

When using substr the second parameter is the number of characters to include in the substring:

var s = "string";
s.substr(1, 3); // would return 'tri'

var s = "another example";
s.substr(3, 7); // would return 'ther ex'

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

How to set text size of textview dynamically for different screens

I think You should use the textView.setTextSize(float size) method to set the size of text. textView.setText(arg) used to set the text in the Text View.

How can I overwrite file contents with new content in PHP?

Use file_put_contents()

file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo

Alternatively, if you're stuck with fopen() you can use the w or w+ modes:

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

http://linuxcommand.org/lc3_man_pages/readh.html

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

How to refresh activity after changing language (Locale) inside application

The way we have done it was using Broadcasts:

  1. Send the broadcast every time the user changes language
  2. Register the broadcast receiver in the AppActivity.onCreate() and unregister in AppActivity.onDestroy()
  3. In BroadcastReceiver.onReceive() just restart the activity.

AppActivity is the parent activity which all other activities subclass.


Below is the snippet from my code, not tested outside the project, but should give you a nice idea.

When the user changes the language

sendBroadcast(new Intent("Language.changed"));

And in the parent activity

public class AppActivity extends Activity {

    /**
     * The receiver that will handle the change of the language.
     */
    private BroadcastReceiver mLangaugeChangedReceiver;

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

        // ...
        // Other code here
        // ...

        // Define receiver
        mLangaugeChangedReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(final Context context, final Intent intent) {
                startActivity(getIntent());
                finish();
            }
        };

        // Register receiver
        registerReceiver(mLangaugeChangedReceiver, new IntentFilter("Language.changed"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // ...
        // Other cleanup code here
        // ...

        // Unregister receiver
        if (mLangaugeChangedReceiver != null) {
            try {
                unregisterReceiver(mLangaugeChangedReceiver);
                mLangaugeChangedReceiver = null;
            } catch (final Exception e) {}
        }
    }
}

This will also refresh the activity which changed the language (if it subclasses the above activity).

This will make you lose any data, but if it is important you should already have taken care of this using Actvity.onSaveInstanceState() and Actvity.onRestoreInstanceState() (or similar).

Let me know your thoughts about this.

Cheers!

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using %lf, %lg or %le (or %la in C99) to read in doubles.

onclick go full screen

var elem = document.getElementById("myvideo");
function openFullscreen() {
  if (elem.requestFullscreen) {
      elem.requestFullscreen();
  } else if (elem.mozRequestFullScreen) { /* Firefox */
      elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE/Edge */
      elem.msRequestFullscreen();
  }
}
//Internet Explorer 10 and earlier does not support the msRequestFullscreen() method.

Select method in List<t> Collection

Generic List<T> have the Where<T>(Func<T, Boolean>) extension method that can be used to filter data.

In your case with a row array:

var rows = rowsArray.Where(row => row["LastName"].ToString().StartsWith("a"));

If you are using DataRowCollection, you need to cast it first.

var rows = dataTableRows.Cast<DataRow>().Where(row => row["LastName"].ToString().StartsWith("a"));

Close/kill the session when the browser or tab is closed

Please refer the below steps:

  1. First create a page SessionClear.aspx and write the code to clear session
  2. Then add following JavaScript code in your page or Master Page:

    <script language="javascript" type="text/javascript">
        var isClose = false;
    
        //this code will handle the F5 or Ctrl+F5 key
        //need to handle more cases like ctrl+R whose codes are not listed here
        document.onkeydown = checkKeycode
        function checkKeycode(e) {
        var keycode;
        if (window.event)
        keycode = window.event.keyCode;
        else if (e)
        keycode = e.which;
        if(keycode == 116)
        {
        isClose = true;
        }
        }
        function somefunction()
        {
        isClose = true;
        }
    
        //<![CDATA[
    
            function bodyUnload() {
    
          if(!isClose)
          {
                  var request = GetRequest();
                  request.open("GET", "SessionClear.aspx", true);
                  request.send();
          }
            }
            function GetRequest() {
                var request = null;
                if (window.XMLHttpRequest) {
                    //incase of IE7,FF, Opera and Safari browser
                    request = new XMLHttpRequest();
                }
                else {
                    //for old browser like IE 6.x and IE 5.x
                    request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
                }
                return request;
            } 
        //]]>
    </script>
    
  3. Add the following code in the body tag of master page.

    <body onbeforeunload="bodyUnload();" onmousedown="somefunction()">
    

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Well you could solve this with a temp table..

DECLARE @RoleToAdds TABLE
([RoleID] int, [PageID] int)

INSERT INTO @RoleToAdds ([RoleID], [PageID])
    VALUES
    (1, 2),
    (1, 3),
    (1, 4),
    (2, 5)

INSERT INTO [dbo].[RolePages] ([RoleID], [PageID])
    SELECT rta.[RoleID], rta.[PageID] FROM @RoleToAdds rta WHERE NOT EXISTS 
        (SELECT * FROM [RolePages] rp WHERE rp.PageID = rta.PageID AND rp.RoleID = rta.RoleID)

This might not work for big amounts of data but for a few rows it should work!

Convert char to int in C#

I am agree with @Chad Grant

Also right if you convert to string then you can use that value as numeric as said in the question

int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2

I tried to create a more simple and understandable example

char v = '1';
int vv = (int)char.GetNumericValue(v); 

char.GetNumericValue(v) returns as double and converts to (int)

More Advenced usage as an array

int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();