Programs & Examples On #Group by

GROUP BY is a command in the SQL relational database standard for collapsing a group of rows that share common field value(s) into a single row. Aggregate functions can be performed on other fields in the group, such as SUM() or AVG(), to collate related data into a single value.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

As already mentioned, creating your own aggregate function is the right thing to do. Here is my concatenation aggregate function (you can find details in French):

CREATE OR REPLACE FUNCTION concat2(text, text) RETURNS text AS '
    SELECT CASE WHEN $1 IS NULL OR $1 = \'\' THEN $2
            WHEN $2 IS NULL OR $2 = \'\' THEN $1
            ELSE $1 || \' / \' || $2
            END; 
'
 LANGUAGE SQL;

CREATE AGGREGATE concatenate (
  sfunc = concat2,
  basetype = text,
  stype = text,
  initcond = ''

);

And then use it as:

SELECT company_id, concatenate(employee) AS employees FROM ...

Is it possible to GROUP BY multiple columns using MySQL?

To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.

SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

SQL: Group by minimum value in one field while selecting distinct rows

I could get to your expected result just by doing this in :

 SELECT id, min(record_date), other_cols 
  FROM mytable
  GROUP BY id

Does this work for you?

How to access pandas groupby dataframe by key

Rather than

gb.get_group('foo')

I prefer using gb.groups

df.loc[gb.groups['foo']]

Because in this way you can choose multiple columns as well. for example:

df.loc[gb.groups['foo'],('A','B')]

Group By Multiple Columns

group x by new { x.Col, x.Col}

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

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

Count unique values using pandas groupby

This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:

df.groupby(['group']).agg(['min','max','count','nunique'])

Hope you find it useful

mysql query: SELECT DISTINCT column1, GROUP BY column2

you can use COUNT(DISTINCT ip), this will only count distinct values

Pandas group-by and sum

If you want to keep the original columns Fruit and Name, use reset_index(). Otherwise Fruit and Name will become part of the index.

df.groupby(['Fruit','Name'])['Number'].sum().reset_index()

Fruit   Name       Number
Apples  Bob        16
Apples  Mike        9
Apples  Steve      10
Grapes  Bob        35
Grapes  Tom        87
Grapes  Tony       15
Oranges Bob        67
Oranges Mike       57
Oranges Tom        15
Oranges Tony        1

As seen in the other answers:

df.groupby(['Fruit','Name'])['Number'].sum()

               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

LINQ with groupby and count

After calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set. You just have to call Count() on that Grouping to get the subtotal.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric))
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}

> This was a brilliantly quick reply but I'm having a bit of an issue with the first line, specifically "data.groupby(info=>info.metric)"

I'm assuming you already have a list/array of some class that looks like

class UserInfo {
    string name;
    int metric;
    ..etc..
} 
...
List<UserInfo> data = ..... ;

When you do data.GroupBy(x => x.metric), it means "for each element x in the IEnumerable defined by data, calculate it's .metric, then group all the elements with the same metric into a Grouping and return an IEnumerable of all the resulting groups. Given your example data set of

    <DATA>           | Grouping Key (x=>x.metric) |
joe  1 01/01/2011 5  | 1
jane 0 01/02/2011 9  | 0
john 2 01/03/2011 0  | 2
jim  3 01/04/2011 1  | 3
jean 1 01/05/2011 3  | 1
jill 2 01/06/2011 5  | 2
jeb  0 01/07/2011 3  | 0
jenn 0 01/08/2011 7  | 0

it would result in the following result after the groupby:

(Group 1): [joe  1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb  0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim  3 01/04/2011 1]

How to use Oracle's LISTAGG function with a unique filter?

below is undocumented and not recomended by oracle. and can not apply in function, show error

select wm_concat(distinct name) as names from demotable group by group_id

regards zia

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

COUNT / GROUP BY with active record?

I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select, group_by, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id. After this query run a query: SELECT FOUND_ROWS(). This will return the desired number.

What does SQL clause "GROUP BY 1" mean?

SELECT account_id, open_emp_id
         ^^^^        ^^^^
          1           2

FROM account
GROUP BY 1;

In above query GROUP BY 1 refers to the first column in select statement which is account_id.

You also can specify in ORDER BY.

Note : The number in ORDER BY and GROUP BY always start with 1 not with 0.

MySQL - sum column value(s) based on row from the same table

I think you're making this a bit more complicated than it needs to be.

SELECT
    ProductID,
    SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
    -- snip
    SUM(Amount) AS Total
FROM
    Payments
WHERE
    SaleDate = '2012-02-10'
GROUP BY
    ProductID

GROUP BY + CASE statement

For TSQL I like to encapsulate case statements in an outer apply. This prevents me from having to have the case statement written twice, allows reference to the case statement by alias in future joins and avoids the need for positional references.

select oa.day, 
model.name, 
attempt.type, 
oa.result
COUNT(*) MyCount 
FROM attempt attempt, prod_hw_id prod_hw_id, model model
WHERE time >= '2013-11-06 00:00:00'  
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
OUTER APPLY (
    SELECT CURRENT_DATE-1 AS day,
     CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END result
    ) oa    
group by oa.day, 
model.name, 
attempt.type, 
oa.result
order by model.name, attempt.type, oa.result;

Select first row in each GROUP BY group?

Use ARRAY_AGG function for PostgreSQL, U-SQL, IBM DB2, and Google BigQuery SQL:

SELECT customer, (ARRAY_AGG(id ORDER BY total DESC))[1], MAX(total)
FROM purchases
GROUP BY customer

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Swiss Army Knife: GroupBy.describe

Returns count, mean, std, and other useful statistics per-group.

df.groupby(['A', 'B'])['C'].describe()

           count  mean   std   min   25%   50%   75%   max
A   B                                                     
bar one      1.0  0.40   NaN  0.40  0.40  0.40  0.40  0.40
    three    1.0  2.24   NaN  2.24  2.24  2.24  2.24  2.24
    two      1.0 -0.98   NaN -0.98 -0.98 -0.98 -0.98 -0.98
foo one      2.0  1.36  0.58  0.95  1.15  1.36  1.56  1.76
    three    1.0 -0.15   NaN -0.15 -0.15 -0.15 -0.15 -0.15
    two      2.0  1.42  0.63  0.98  1.20  1.42  1.65  1.87

To get specific statistics, just select them,

df.groupby(['A', 'B'])['C'].describe()[['count', 'mean']]

           count      mean
A   B                     
bar one      1.0  0.400157
    three    1.0  2.240893
    two      1.0 -0.977278
foo one      2.0  1.357070
    three    1.0 -0.151357
    two      2.0  1.423148

describe works for multiple columns (change ['C'] to ['C', 'D']—or remove it altogether—and see what happens, the result is a MultiIndexed columned dataframe).

You also get different statistics for string data. Here's an example,

df2 = df.assign(D=list('aaabbccc')).sample(n=100, replace=True)

with pd.option_context('precision', 2):
    display(df2.groupby(['A', 'B'])
               .describe(include='all')
               .dropna(how='all', axis=1))

              C                                                   D                
          count  mean       std   min   25%   50%   75%   max count unique top freq
A   B                                                                              
bar one    14.0  0.40  5.76e-17  0.40  0.40  0.40  0.40  0.40    14      1   a   14
    three  14.0  2.24  4.61e-16  2.24  2.24  2.24  2.24  2.24    14      1   b   14
    two     9.0 -0.98  0.00e+00 -0.98 -0.98 -0.98 -0.98 -0.98     9      1   c    9
foo one    22.0  1.43  4.10e-01  0.95  0.95  1.76  1.76  1.76    22      2   a   13
    three  15.0 -0.15  0.00e+00 -0.15 -0.15 -0.15 -0.15 -0.15    15      1   c   15
    two    26.0  1.49  4.48e-01  0.98  0.98  1.87  1.87  1.87    26      2   b   15

For more information, see the documentation.


pandas >= 1.1: DataFrame.value_counts

This is available from pandas 1.1 if you just want to capture the size of every group, this cuts out the GroupBy and is faster.

df.value_counts(subset=['col1', 'col2'])

Minimal Example

# Setup
np.random.seed(0)
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                          'foo', 'bar', 'foo', 'foo'],
                   'B' : ['one', 'one', 'two', 'three',
                          'two', 'two', 'one', 'three'],
                   'C' : np.random.randn(8),
                   'D' : np.random.randn(8)})

df.value_counts(['A', 'B']) 

A    B    
foo  two      2
     one      2
     three    1
bar  two      1
     three    1
     one      1
dtype: int64

Other Statistical Analysis Tools

If you didn't find what you were looking for above, the User Guide has a comprehensive listing of supported statical analysis, correlation, and regression tools.

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

Grouping into interval of 5 minutes within a time range

You're probably going to have to break up your timestamp into ymd:HM and use DIV 5 to split the minutes up into 5-minute bins -- something like

select year(a.timestamp), 
       month(a.timestamp), 
       hour(a.timestamp), 
       minute(a.timestamp) DIV 5,
       name, 
       count(b.name)
FROM time a, id b
WHERE a.user = b.user AND a.id = b.id AND b.name = 'John' 
      AND a.timestamp BETWEEN '2010-11-16 10:30:00' AND '2010-11-16 11:00:00'
GROUP BY year(a.timestamp), 
       month(a.timestamp), 
       hour(a.timestamp), 
       minute(a.timestamp) DIV 12

...and then futz the output in client code to appear the way you like it. Or, you can build up the whole date string using the sql concat operatorinstead of getting separate columns, if you like.

select concat(year(a.timestamp), "-", month(a.timestamp), "-" ,day(a.timestamp), 
       " " , lpad(hour(a.timestamp),2,'0'), ":", 
       lpad((minute(a.timestamp) DIV 5) * 5, 2, '0'))

...and then group on that

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

SQL query to group by day

For PostgreSQL:

GROUP BY to_char(timestampfield, 'yyyy-mm-dd')

or using cast:

GROUP BY timestampfield::date

if you want speed, use the second option and add an index:

CREATE INDEX tablename_timestampfield_date_idx ON  tablename(date(timestampfield));

How to combine GROUP BY and ROW_NUMBER?

Wow, the other answers look complex - so I'm hoping I've not missed something obvious.

You can use OVER/PARTITION BY against aggregates, and they'll then do grouping/aggregating without a GROUP BY clause. So I just modified your query to:

select T2.ID AS T2ID
    ,T2.Name as T2Name
    ,T2.Orders
    ,T1.ID AS T1ID
    ,T1.Name As T1Name
    ,T1Sum.Price
FROM @t2 T2
INNER JOIN (
    SELECT Rel.t2ID
        ,Rel.t1ID
 --       ,MAX(Rel.t1ID)AS t1ID 
-- the MAX returns an arbitrary ID, what i need is: 
      ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
        ,SUM(Price)OVER(PARTITION BY Rel.t2ID) AS Price
        FROM @t1 T1 
        INNER JOIN @relation Rel ON Rel.t1ID=T1.ID
--        GROUP BY Rel.t2ID
)AS T1Sum ON  T1Sum.t2ID = T2.ID
INNER JOIN @t1 T1 ON T1Sum.t1ID=T1.ID
where t1Sum.PriceList = 1

Which gives the requested result set.

pandas groupby sort within groups

Here's other example of taking top 3 on sorted order, and sorting within the groups:

In [43]: import pandas as pd                                                                                                                                                       

In [44]:  df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})

In [45]: df                                                                                                                                                                        
Out[45]: 
   count_1  count_2  name
0        5      100   Foo
1       10      150   Foo
2       12      100  Baar
3       15       25   Foo
4       20      250  Baar
5       25      300   Foo
6       30      400  Baar
7       35      500  Baar


### Top 3 on sorted order:
In [46]: df.groupby(["name"])["count_1"].nlargest(3)                                                                                                                               
Out[46]: 
name   
Baar  7    35
      6    30
      4    20
Foo   5    25
      3    15
      1    10
dtype: int64


### Sorting within groups based on column "count_1":
In [48]: df.groupby(["name"]).apply(lambda x: x.sort_values(["count_1"], ascending = False)).reset_index(drop=True)
Out[48]: 
   count_1  count_2  name
0       35      500  Baar
1       30      400  Baar
2       20      250  Baar
3       12      100  Baar
4       25      300   Foo
5       15       25   Foo
6       10      150   Foo
7        5      100   Foo

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

getting "No column was specified for column 2 of 'd'" in sql server cte?

[edit]

I tried to rewrite your query, but even yours will work once you associate aliases to the aggregate columns in the query that defines 'd'.


I think you are looking for the following:

First one:

select 
    c.duration, 
    c.totalbookings, 
    d.bkdqty 
from
    (select 
               month(bookingdate) as duration, 
               count(*) as totalbookings 
           from 
               entbookings
           group by month(bookingdate)
    ) AS c 
    inner join 
    (SELECT 
               duration, 
               sum(totalitems) 'bkdqty'
           FROM 
               [DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
           group by duration
    ) AS d 
    on c.duration = d.duration

Second one:

select 
    c.duration, 
    c.totalbookings, 
    d.bkdqty 
from
    (select 
               month(bookingdate) as duration, 
               count(*) as totalbookings 
           from 
               entbookings
           group by month(bookingdate)
    ) AS c 
    inner join 
    (select 
               month(clothdeliverydate) 'clothdeliverydatemonth', 
               SUM(CONVERT(INT, deliveredqty)) 'bkdqty'
           FROM 
               barcodetable
           where 
               month(clothdeliverydate) is not null
               group by month(clothdeliverydate)
    ) AS d 
    on c.duration = d.duration

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

Group by in LINQ

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key,
                           /**/car = g.Select(g=>g.car).FirstOrDefault()/**/}

How to group time by hour or by 10 minutes

declare @interval tinyint
set @interval = 30
select dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0), sum(Value_Transaction)
from Transactions
group by dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0)

GROUP BY with MAX(DATE)

SELECT train, dest, time FROM ( 
  SELECT train, dest, time, 
    RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
    FROM traintable
  ) where dest_rank = 1

SQL to Entity Framework Count Group-By

Query syntax

var query = from p in context.People
            group p by p.name into g
            select new
            {
              name = g.Key,
              count = g.Count()
            };

Method syntax

var query = context.People
                   .GroupBy(p => p.name)
                   .Select(g => new { name = g.Key, count = g.Count() });

ORDER BY date and time BEFORE GROUP BY name in mysql

This worked for me:

SELECT *
FROM your_table
WHERE id IN (
    SELECT MAX(id)
    FROM your_table
    GROUP BY name
);

Relative frequencies / proportions with dplyr

@Henrik's is better for usability as this will make the column character and no longer numeric but matches what you asked for...

mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq = paste0(round(100 * n/sum(n), 0), "%"))

##   am gear  n rel.freq
## 1  0    3 15      79%
## 2  0    4  4      21%
## 3  1    4  8      62%
## 4  1    5  5      38%

EDIT Because Spacedman asked for it :-)

as.rel_freq <- function(x, rel_freq_col = "rel.freq", ...) {
    class(x) <- c("rel_freq", class(x))
    attributes(x)[["rel_freq_col"]] <- rel_freq_col
    x
}

print.rel_freq <- function(x, ...) {
    freq_col <- attributes(x)[["rel_freq_col"]]
    x[[freq_col]] <- paste0(round(100 * x[[freq_col]], 0), "%")   
    class(x) <- class(x)[!class(x)%in% "rel_freq"]
    print(x)
}

mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq = n/sum(n)) %>%
  as.rel_freq()

## Source: local data frame [4 x 4]
## Groups: am
## 
##   am gear  n rel.freq
## 1  0    3 15      79%
## 2  0    4  4      21%
## 3  1    4  8      62%
## 4  1    5  5      38%

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

How to use count and group by at the same select statement

if You Want to use Select All Query With Count Option, try this...

 select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name  as a where where Condition

Using LINQ to group a list of objects

var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>{
                                                        u.Name = "User" + u.Name;
                                                        return u;
                                                     }, (key,g)=>g.ToList())
                         .ToList();

If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public Customer CloneWithNamePrepend(string prepend){
    return new Customer(){
          ID = this.ID,
          Name = prepend + this.Name,
          GroupID = this.GroupID
     };
  }
}    
//Then
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
                         .ToList();

I think you may want to display the Customer differently without modifying the original data. If so you should design your class Customer differently, like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public string Prefix {get;set;}
  public string FullName {
    get { return Prefix + Name;}
  }            
}
//then to display the fullname, just get the customer.FullName; 
//You can also try adding some override of ToString() to your class

var groupedCustomerList = CustomerList
                         .GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
                         .ToList();

LINQ: combining join and group by

Once you've done this

group p by p.SomeId into pg  

you no longer have access to the range variables used in the initial from. That is, you can no longer talk about p or bp, you can only talk about pg.

Now, pg is a group and so contains more than one product. All the products in a given pg group have the same SomeId (since that's what you grouped by), but I don't know if that means they all have the same BaseProductId.

To get a base product name, you have to pick a particular product in the pg group (As you are doing with SomeId and CountryCode), and then join to BaseProducts.

var result = from p in Products                         
 group p by p.SomeId into pg                         
 // join *after* group
 join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  // now there is a 'bp' in scope
 };

That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Use subquery

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

Count multiple columns with group by in one query

SELECT COUNT(col1 OR col2) FROM [table_name] GROUP BY col1,col2;

Count unique values with pandas per groups

Generally to count distinct values in single column, you can use Series.value_counts:

df.domain.value_counts()

#'vk.com'          5
#'twitter.com'     2
#'facebook.com'    1
#'google.com'      1
#Name: domain, dtype: int64

To see how many unique values in a column, use Series.nunique:

df.domain.nunique()
# 4

To get all these distinct values, you can use unique or drop_duplicates, the slight difference between the two functions is that unique return a numpy.array while drop_duplicates returns a pandas.Series:

df.domain.unique()
# array(["'vk.com'", "'twitter.com'", "'facebook.com'", "'google.com'"], dtype=object)

df.domain.drop_duplicates()
#0          'vk.com'
#2     'twitter.com'
#4    'facebook.com'
#6      'google.com'
#Name: domain, dtype: object

As for this specific problem, since you'd like to count distinct value with respect to another variable, besides groupby method provided by other answers here, you can also simply drop duplicates firstly and then do value_counts():

import pandas as pd
df.drop_duplicates().domain.value_counts()

# 'vk.com'          3
# 'twitter.com'     2
# 'facebook.com'    1
# 'google.com'      1
# Name: domain, dtype: int64

Select multiple columns from a table, but group by one

mysql GROUP_CONCAT function could help https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat

SELECT ProductID, GROUP_CONCAT(DISTINCT ProductName) as Names, SUM(OrderQuantity)
FROM OrderDetails GROUP BY ProductID

This would return:

ProductID     Names          OrderQuantity
1001          red            5
1002          red,black      6
1003          orange         8
1004          black,orange   15

Similar idea as the one @Urs Marian here posted https://stackoverflow.com/a/38779277/906265

Count number of records returned by group by

In PostgreSQL this works for me:

select count(count.counts) 
from 
    (select count(*) as counts 
     from table 
     group by concept) as count;

MySQL Query GROUP BY day / month / year

You can do this simply Mysql DATE_FORMAT() function in GROUP BY. You may want to add an extra column for added clarity in some cases such as where records span several years then same month occurs in different years.Here so many option you can customize this. Please read this befor starting. Hope it should be very helpful for you. Here is sample query for your understanding

SELECT
    COUNT(id),
    DATE_FORMAT(record_date, '%Y-%m-%d') AS DAY,
    DATE_FORMAT(record_date, '%Y-%m') AS MONTH,
    DATE_FORMAT(record_date, '%Y') AS YEAR

FROM
    stats
WHERE
    YEAR = 2009
GROUP BY
    DATE_FORMAT(record_date, '%Y-%m-%d ');

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

Group By Eloquent ORM

try: ->unique('column')

example:

$users = User::get()->unique('column');

MySQL order by before group by

Just use the max function and group function

    select max(taskhistory.id) as id from taskhistory
            group by taskhistory.taskid
            order by taskhistory.datum desc

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

+--------------------+-------------------+--------+
|                 _c5|                _c7|count(1)|
+--------------------+-------------------+--------+
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|
+--------------------+-------------------+--------+

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

How to get multiple counts with one SQL query?

One way which works for sure

SELECT a.distributor_id,
    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;

EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn?'s answer. I'm leaving this so people can understand their options.

How to group by week in MySQL?

Figured it out... it's a little cumbersome, but here it is.

FROM_DAYS(TO_DAYS(TIMESTAMP) -MOD(TO_DAYS(TIMESTAMP) -1, 7))

And, if your business rules say your weeks start on Mondays, change the -1 to -2.


Edit

Years have gone by and I've finally gotten around to writing this up. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Group by with union mysql select query

select sum(qty), name
from (
    select count(m.owner_id) as qty, o.name
    from transport t,owner o,motorbike m
    where t.type='motobike' and o.owner_id=m.owner_id
        and t.type_id=m.motorbike_id
    group by m.owner_id

    union all

    select count(c.owner_id) as qty, o.name,
    from transport t,owner o,car c
    where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
    group by c.owner_id
) t
group by name

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

Is there any difference between GROUP BY and DISTINCT

Generally we can use DISTINCT for eliminate the duplicates on Specific Column in the table.

In Case of 'GROUP BY' we can Apply the Aggregation Functions like AVG, MAX, MIN, SUM, and COUNT on Specific column and fetch the column name and it aggregation function result on the same column.

Example :

select  specialColumn,sum(specialColumn) from yourTableName group by specialColumn;

MySQL "Group By" and "Order By"

A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:

SELECT * FROM ( 
    SELECT `timestamp`, `fromEmail`, `subject`
    FROM `incomingEmails` 
    ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)

This is similar to using the join but looks much nicer.

Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.

IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)

As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above

See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

Using ORDER BY and GROUP BY together

Just you need to desc with asc. Write the query like below. It will return the values in ascending order.

SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;

Error related to only_full_group_by when executing a query in MySql

Go to mysql or phpmyadmin and select database then simply execute this query and it will work. Its working fine for me.

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

How do I create a new column from the output of pandas groupby().sum()?

How do I create a new column with Groupby().Sum()?

There are two ways - one straightforward and the other slightly more interesting.


Everybody's Favorite: GroupBy.transform() with 'sum'

@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby rather than Series.groupby. This results in simpler syntax.

# The setup.
df[['Date', 'Data3']]

         Date  Data3
0  2015-05-08      5
1  2015-05-07      8
2  2015-05-06      6
3  2015-05-05      1
4  2015-05-08     50
5  2015-05-07    100
6  2015-05-06     60
7  2015-05-05    120

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64 

It's a tad faster,

df2 = pd.concat([df] * 12345)

%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')

10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Unconventional, but Worth your Consideration: GroupBy.sum() + Series.map()

I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform if you instead use a direct function of GroupBy and broadcast it using map:

df.Date.map(df.groupby('Date')['Data3'].sum())

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Date, dtype: int64

Compare with

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64

My tests show that map is a bit faster if you can afford to use the direct GroupBy function (such as mean, min, max, first, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.

(Left: v0.23, Right: v0.24)

Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform as a first choice. Thought this was worth sharing anyway.

Benchmarking code, for reference:

import perfplot

perfplot.show(
    setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
    kernels=[
        lambda df: df.groupby('A')['B'].transform('sum'),
        lambda df:  df.A.map(df.groupby('A')['B'].sum()),
    ],
    labels=['GroupBy.transform', 'GroupBy.sum + map'],
    n_range=[2**k for k in range(5, 20)],
    xlabel='N',
    logy=True,
    logx=True
)

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Renaming Column Names in Pandas Groupby function

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

Deprecated Answer as of pandas version 0.20

This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg method.

These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.

Before we get there, let's create a four column DataFrame.

df = pd.DataFrame({'A' : list('wwwwxxxx'), 
                   'B':list('yyzzyyzz'), 
                   'C':np.random.rand(8), 
                   'D':np.random.rand(8)})

   A  B         C         D
0  w  y  0.643784  0.828486
1  w  y  0.308682  0.994078
2  w  z  0.518000  0.725663
3  w  z  0.486656  0.259547
4  x  y  0.089913  0.238452
5  x  y  0.688177  0.753107
6  x  z  0.955035  0.462677
7  x  z  0.892066  0.368850

Let's say we want to group by columns A, B and aggregate column C with mean and median and aggregate column D with max. The following code would do this.

df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})

            D         C          
          max      mean    median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:

df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'}, 
                            'D':{'D_max': 'max'}})

            D         C          
        D_max    C_mean  C_median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0).

Get top 1 row of each group

I believe this can be done just like this. This might need some tweaking but you can just select the max from the group.

These answers are overkill..

SELECT
  d.DocumentID,
  MAX(d.Status),
  MAX(d1.DateCreated)
FROM DocumentStatusLogs d, DocumentStatusLogs d1
USING(DocumentID)
GROUP BY d.DocumentID
ORDER BY DateCreated DESC

Apply multiple functions to multiple groupby columns

Pandas >= 0.25.0, named aggregations

Since pandas version 0.25.0 or higher, we are moving away from the dictionary based aggregation and renaming, and moving towards named aggregations which accepts a tuple. Now we can simultaneously aggregate + rename to a more informative column name:

Example:

df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]

          a         b         c         d  group
0  0.521279  0.914988  0.054057  0.125668      0
1  0.426058  0.828890  0.784093  0.446211      0
2  0.363136  0.843751  0.184967  0.467351      1
3  0.241012  0.470053  0.358018  0.525032      1

Apply GroupBy.agg with named aggregation:

df.groupby('group').agg(
             a_sum=('a', 'sum'),
             a_mean=('a', 'mean'),
             b_mean=('b', 'mean'),
             c_sum=('c', 'sum'),
             d_range=('d', lambda x: x.max() - x.min())
)

          a_sum    a_mean    b_mean     c_sum   d_range
group                                                  
0      0.947337  0.473668  0.871939  0.838150  0.320543
1      0.604149  0.302074  0.656902  0.542985  0.057681

SQL - using alias in Group By

Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)

Group by month and year in MySQL

SELECT YEAR(t.summaryDateTime) as yr, GROUP_CONCAT(MONTHNAME(t.summaryDateTime)) AS month 
FROM trading_summary t GROUP BY yr

Still you would need to process it in external script to get exactly the structure you're looking for.

For example use PHP's explode to create an array from list of month names and then use json_encode()

Python group by

This answer is similar to @PaulMcG's answer but doesn't require sorting the input.

For those into functional programming, groupBy can be written in one line (not including imports!), and unlike itertools.groupby it doesn't require the input to be sorted:

from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict

def groupBy(key, seq):
 return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))

(The reason for ... or grp in the lambda is that for this reduce() to work, the lambda needs to return its first argument; because list.append() always returns None the or will always return grp. I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)

This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order. For the OP's example, calling this as groupBy(lambda pair: pair[1], input) will return this dict:

{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
 'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
 'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}

And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension. So this will do it:

result = {key: [pair[0] for pair in values],
          for key, values in groupBy(lambda pair: pair[1], input).items()}

Most efficient method to groupby on an array of objects

You can use forEach on array and construct a new group of items. Here is how to do that with FlowType annotation

// @flow

export class Group<T> {
  tag: number
  items: Array<T>

  constructor() {
    this.items = []
  }
}

const groupBy = (items: Array<T>, map: (T) => number) => {
  const groups = []

  let currentGroup = null

  items.forEach((item) => {
    const tag = map(item)

    if (currentGroup && currentGroup.tag === tag) {
      currentGroup.items.push(item)
    } else {
      const group = new Group<T>()
      group.tag = tag
      group.items.push(item)
      groups.push(group)

      currentGroup = group
    }
  })

  return groups
}

export default groupBy

A jest test can be like

// @flow

import groupBy from './groupBy'

test('groupBy', () => {
  const items = [
    { name: 'January', month: 0 },
    { name: 'February', month: 1 },
    { name: 'February 2', month: 1 }
  ]

  const groups = groupBy(items, (item) => {
    return item.month
  })

  expect(groups.length).toBe(2)
  expect(groups[1].items[1].name).toBe('February 2')
})

Linq select to new object

All of the grouped objects, or all of the types? It sounds like you may just want:

var query = types.GroupBy(t => t.Type)
                 .Select(g => new { Type = g.Key, Count = g.Count() });

foreach (var result in query)
{
    Console.WriteLine("{0}, {1}", result.Type, result.Count);
}

EDIT: If you want it in a dictionary, you can just use:

var query = types.GroupBy(t => t.Type)
                 .ToDictionary(g => g.Key, g => g.Count());

There's no need to select into pairs and then build the dictionary.

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

Group dataframe and get sum AND count?

try this:

In [110]: (df.groupby('Company Name')
   .....:    .agg({'Organisation Name':'count', 'Amount': 'sum'})
   .....:    .reset_index()
   .....:    .rename(columns={'Organisation Name':'Organisation Count'})
   .....: )
Out[110]:
          Company Name   Amount  Organisation Count
0  Vifor Pharma UK Ltd  4207.93                   5

or if you don't want to reset index:

df.groupby('Company Name')['Amount'].agg(['sum','count'])

or

df.groupby('Company Name').agg({'Amount': ['sum','count']})

Demo:

In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
                         sum  count
Company Name
Vifor Pharma UK Ltd  4207.93      5

In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
                      Amount
                         sum count
Company Name
Vifor Pharma UK Ltd  4207.93     5

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

You can disable sql_mode=only_full_group_by by some command you can try this by terminal or MySql IDE

mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

SQL query for finding records where count > 1

Use the HAVING clause and GROUP By the fields that make the row unique

The below will find

all users that have more than one payment per day with the same account number

SELECT 
 user_id ,
 COUNT(*) count
FROM 
 PAYMENT
GROUP BY
 account,
 user_id ,
 date
HAVING
COUNT(*) > 1

Update If you want to only include those that have a distinct ZIP you can get a distinct set first and then perform you HAVING/GROUP BY

 SELECT 
    user_id,
    account_no , 
    date,
        COUNT(*)
 FROM
    (SELECT DISTINCT
            user_id,
            account_no , 
            zip, 
            date
         FROM
            payment 
    
        ) 
        payment
 GROUP BY
    
    user_id,
    account_no , 
    
    date
HAVING COUNT(*) > 1

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

SQL Sum Multiple rows into one

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

This will return the sum of bills per account number:

SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber

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

GROUP BY without aggregate function

Let me give some examples.

Consider this data.

CREATE TABLE DATASET ( VAL1 CHAR ( 1 CHAR ),
                   VAL2 VARCHAR2 ( 10 CHAR ),
                   VAL3 NUMBER );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'b', 'b-details', 2 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'a-details', 1 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 3 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'dup', 4 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 5 );

COMMIT;

Whats there in table now

SELECT * FROM DATASET;

VAL1 VAL2             VAL3
---- ---------- ----------
b    b-details           2
a    a-details           1
c    c-details           3
a    dup                 4
c    c-details           5

5 rows selected.

--aggregate with group by

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1;

VAL1   COUNT(*)
---- ----------
b             1
a             2
c             2

3 rows selected.

--aggregate with group by multiple columns but select partial column

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

VAL1  
---- 
b             
c             
a             
a             

4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1,
      VAL2
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b    b-details
    c    c-details
    a    dup
    a    a-details

    4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b
    c
    a
    a

    4 rows selected.

You have N columns in select (excluding aggregations), then you should have N or N+x columns

SQL GROUP BY CASE statement with aggregate function

If you are grouping by some other value, then instead of what you have,

write it as

Sum(CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END) as SumSomeProduct

If, otoh, you want to group By the internal expression, (col3*col4) then

write the group By to match the expression w/o the SUM...

Select Sum(Case When col1 > col2 Then col3*col4 Else 0 End) as SumSomeProduct
From ...

Group By Case When col1 > col2 Then col3*col4 Else 0 End 

Finally, if you want to group By the actual aggregate

Select SumSomeProduct, Count(*), <other aggregate functions>
From (Select <other columns you are grouping By>, 
      Sum(Case When col1 > col2 
          Then col3*col4 Else 0 End) as SumSomeProduct
      From Table
      Group By <Other Columns> ) As Z
Group by SumSomeProduct

must appear in the GROUP BY clause or be used in an aggregate function

In Postgres, you can also use the special DISTINCT ON (expression) syntax:

SELECT DISTINCT ON (cname) 
    cname, wmname, avg
FROM 
    makerar 
ORDER BY 
    cname, avg DESC ;

GroupBy pandas DataFrame and select most common value

If you don't want to include NaN values, using Counter is much much faster than pd.Series.mode or pd.Series.value_counts()[0]:

def get_most_common(srs):
    x = list(srs)
    my_counter = Counter(x)
    return my_counter.most_common(1)[0][0]

df.groupby(col).agg(get_most_common)

should work. This will fail when you have NaN values, as each NaN will be counted separately.

MongoDB SELECT COUNT GROUP BY

If you need multiple columns to group by, follow this model. Here I am conducting a count by status and type:

  db.BusinessProcess.aggregate({
    "$group": {
        _id: {
            status: "$status",
            type: "$type"
        },
        count: {
            $sum: 1
        }
    }
   })

pandas GroupBy columns with NaN (missing) values

All answers provided thus far result in potentially dangerous behavior as it is quite possible you select a dummy value that is actually part of the dataset. This is increasingly likely as you create groups with many attributes. Simply put, the approach doesn't always generalize well.

A less hacky solve is to use pd.drop_duplicates() to create a unique index of value combinations each with their own ID, and then group on that id. It is more verbose but does get the job done:

def safe_groupby(df, group_cols, agg_dict):
    # set name of group col to unique value
    group_id = 'group_id'
    while group_id in df.columns:
        group_id += 'x'
    # get final order of columns
    agg_col_order = (group_cols + list(agg_dict.keys()))
    # create unique index of grouped values
    group_idx = df[group_cols].drop_duplicates()
    group_idx[group_id] = np.arange(group_idx.shape[0])
    # merge unique index on dataframe
    df = df.merge(group_idx, on=group_cols)
    # group dataframe on group id and aggregate values
    df_agg = df.groupby(group_id, as_index=True)\
               .agg(agg_dict)
    # merge grouped value index to results of aggregation
    df_agg = group_idx.set_index(group_id).join(df_agg)
    # rename index
    df_agg.index.name = None
    # return reordered columns
    return df_agg[agg_col_order]

Note that you can now simply do the following:

data_block = [np.tile([None, 'A'], 3),
              np.repeat(['B', 'C'], 3),
              [1] * (2 * 3)]

col_names = ['col_a', 'col_b', 'value']

test_df = pd.DataFrame(data_block, index=col_names).T

grouped_df = safe_groupby(test_df, ['col_a', 'col_b'],
                          OrderedDict([('value', 'sum')]))

This will return the successful result without having to worry about overwriting real data that is mistaken as a dummy value.

Distinct pair of values SQL

This will give you the result you're giving as an example:

SELECT DISTINCT a, b
FROM pairs

Retrieving the last record in each group - MySQL

The below query will work fine as per your question.

SELECT M1.* 
FROM MESSAGES M1,
(
 SELECT SUBSTR(Others_data,1,2),MAX(Others_data) AS Max_Others_data
 FROM MESSAGES
 GROUP BY 1
) M2
WHERE M1.Others_data = M2.Max_Others_data
ORDER BY Others_data;

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Your query will work in MYSQL if you set to disable ONLY_FULL_GROUP_BY server mode (and by default It is). But in this case, you are using different RDBMS. So to make your query work, add all non-aggregated columns to your GROUP BY clause, eg

SELECT col1, col2, SUM(col3) totalSUM
FROM tableName
GROUP BY col1, col2

Non-Aggregated columns means the column is not pass into aggregated functions like SUM, MAX, COUNT, etc..

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

I came researching the options that I would have to do this, however, I believe the method I use is the simplest:

SELECT COUNT(*), 
       DATEADD(dd, DATEDIFF(dd, 0, date_field),0) as dtgroup 
FROM TABLE 
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, date_field),0) 
ORDER BY dtgroup ASC;

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

This is not a rule

For each query .... try separately distinct and then group by ... compare the time to complete each query and use the faster ....

In my project sometime I use group by and others distinct

Naming returned columns in Pandas aggregate function?

I agree with the OP that it seems more natural and consistent to name and define the output columns in the same place (e.g. as is done with tidyverse's summarize in R), but a work-around in pandas for now is to create the new columns with desired names via assign before doing the aggregation:

data.assign(
    f=data['column1'],
    mean=data['column2'],
    std=data['column2']
).groupby('Country').agg(dict(f=sum, mean=np.mean, std=np.std)).reset_index()

(Using reset_index turns 'Country', 'f', 'mean', and 'std' all into regular columns with a separate integer index.)

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

How to select the first row for each group in MySQL?

From MySQL 5.7 documentation

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.

This means that @Jader Dias's solution wouldn't work everywhere.

Here is a solution that would work when ONLY_FULL_GROUP_BY is enabled:

SET @row := NULL;
SELECT
    SomeColumn,
    AnotherColumn
FROM (
    SELECT
        CASE @id <=> SomeColumn AND @row IS NOT NULL 
            WHEN TRUE THEN @row := @row+1 
            ELSE @row := 0 
        END AS rownum,
        @id := SomeColumn AS SomeColumn,
        AnotherColumn
    FROM
        SomeTable
    ORDER BY
        SomeColumn, -AnotherColumn DESC
) _values
WHERE rownum = 0
ORDER BY SomeColumn;

Pandas count(distinct) equivalent

Using crosstab, this will return more information than groupby nunique

pd.crosstab(df.YEARMONTH,df.CLIENTCODE)
Out[196]: 
CLIENTCODE  1  2  3
YEARMONTH          
201301      2  1  0
201302      1  2  1

After a little bit modify ,yield the result

pd.crosstab(df.YEARMONTH,df.CLIENTCODE).ne(0).sum(1)
Out[197]: 
YEARMONTH
201301    2
201302    3
dtype: int64

What should every programmer know about security?

  • Remember that you (the programmer) has to secure all parts, but the attacker only has to succeed in finding one kink in your armour.
  • Security is an example of "unknown unknowns". Sometimes you won't know what the possible security flaws are (until afterwards).
  • The difference between a bug and a security hole depends on the intelligence of the attacker.

Replace non-numeric with empty string

You can do it easily with regex:

string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"

How to compare two Carbon Timestamps?

First, convert the timestamp using the built-in eloquent functionality, as described in this answer.

Then you can just use Carbon's min() or max() function for comparison. For example:

$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1->min($dt2);

This will echo the lesser of the two dates, which in this case is $dt1.

See http://carbon.nesbot.com/docs/

mysql update column with value from another table

If you have common field in both table then it's so easy !....

Table-1 = table where you want to update. Table-2 = table where you from take data.

  1. make query in Table-1 and find common field value.
  2. make a loop and find all data from Table-2 according to table 1 value.
  3. again make update query in table 1.

$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");

$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}



foreach($resultArray as $rec) {

    $a = $rec['primary key field'];

    $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");

    $cuttable = mysql_fetch_assoc($cuttable_qry);



    echo $x= $cuttable['Table-2 field']; echo " ! ";
    echo $y= $cuttable['Table-2 field'];echo " ! ";
    echo $z= $cuttable['Table-2 field'];echo " ! ";


    $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");

    if ($k) {
        echo "done";
    } else {
        echo mysql_error();
    }


}

sudo in php exec()

php: the bash console is created, and it executes 1st script, which call sudo to the second one, see below:

$dev = $_GET['device'];
$cmd = '/bin/bash /home/www/start.bash '.$dev;
echo $cmd;
shell_exec($cmd);
  1. /home/www/start.bash

    #!/bin/bash
    /usr/bin/sudo /home/www/myMount.bash $1
    
  2. myMount.bash:

    #!/bin/bash
    function error_exit
    {
      echo "Wrong parameter" 1>&2
      exit 1
    }
    ..........
    

oc, you want to run script from root level without root privileges, to do that create and modify the /etc/sudoers.d/mount file:

www-data ALL=(ALL:ALL) NOPASSWD:/home/www/myMount.bash

dont forget to chmod:

sudo chmod 0440 /etc/sudoers.d/mount

Select by partial string from a pandas DataFrame

A more generalised example - if looking for parts of a word OR specific words in a string:

df = pd.DataFrame([('cat andhat', 1000.0), ('hat', 2000000.0), ('the small dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

Specific parts of sentence or word:

searchfor = '.*cat.*hat.*|.*the.*dog.*'

Creat column showing the affected rows (can always filter out as necessary)

df["TrueFalse"]=df['col1'].str.contains(searchfor, regex=True)

    col1             col2           TrueFalse
0   cat andhat       1000.0         True
1   hat              2000000.0      False
2   the small dog    1000.0         True
3   fog              330000.0       False
4   pet 3            30000.0        False

Detect if PHP session exists

According to the PHP.net manual:

If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use isset() to check a variable is registered in $_SESSION.

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

Button button = findViewById(R.id.button) always resolves to null in Android Studio

R.id.button is not part of R.layout.activity_main. How should the activity find it in the content view?

The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

SQL Update Multiple Fields FROM via a SELECT Statement

Something like this should work (can't test it right now - from memory):

UPDATE SHIPMENT
SET
  OrgAddress1     = BD.OrgAddress1,
  OrgAddress2     = BD.OrgAddress2,
  OrgCity         = BD.OrgCity,
  OrgState        = BD.OrgState,
  OrgZip          = BD.OrgZip,
  DestAddress1    = BD.DestAddress1,
  DestAddress2    = BD.DestAddress2,
  DestCity        = BD.DestCity,
  DestState       = BD.DestState,
  DestZip         = BD.DestZip
FROM
   BookingDetails BD
WHERE 
   SHIPMENT.MyID2 = @MyID2
   AND
   BD.MyID = @MyID

Does that help?

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

How do I auto-resize an image to fit a 'div' container?

All the provided answers, including the accepted one, work only under the assumption that the div wrapper is of a fixed size. So this is how to do it whatever the size of the div wrapper is and this is very useful if you develop a responsive page:

Write these declarations inside your DIV selector:

width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */

Then put these declarations inside your IMG selector:

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

VERY IMPORTANT:

The value of maxHeight must be the same for both the DIV and IMG selectors.

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

How to conditionally take action if FINDSTR fails to find a string

I tried to get this working using FINDSTR, but for some reason my "debugging" command always output an error level of 0:

ECHO %ERRORLEVEL%

My workaround is to use Grep from Cygwin, which outputs the right errorlevel (it will give an errorlevel greater than 0) if a string is not found:

dir c:\*.tib >out 2>>&1
grep "1 File(s)" out
IF %ERRORLEVEL% NEQ 0 "Run other commands" ELSE "Run Errorlevel 0 commands"

Cygwin's grep will also output errorlevel 2 if the file is not found. Here's the hash from my version:

C:\temp\temp>grep --version grep (GNU grep) 2.4.2

C:\cygwin64\bin>md5sum grep.exe c0a50e9c731955628ab66235d10cea23 *grep.exe

C:\cygwin64\bin>sha1sum grep.exe ff43a335bbec71cfe99ce8d5cb4e7c1ecdb3db5c *grep.exe

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

Select multiple value in DropDownList using ASP.NET and C#

In that case you should use ListBox control instead of dropdown and Set the SelectionMode property to Multiple

<asp:ListBox runat="server" SelectionMode="Multiple" >
  <asp:ListItem Text="test1"></asp:ListItem>
  <asp:ListItem Text="test2"></asp:ListItem>
  <asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>

Check whether specific radio button is checked

You should remove the '@' before 'name'; it's not needed anymore (for current jQuery versions).

You're want to return all checked elements with name 'test2', but you don't have any elements with that name, you're using an id of 'test2'.

If you're going to use IDs, just try:

return $('#test2').attr('checked');

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

UIView background color in Swift

I see that this question is solved, but, I want to add some information than can help someone.

if you want use hex to set background color, I found this function and work:

func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
    let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
    let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
    let blue = CGFloat(rgbValue & 0xFF)/256.0

    return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}

I use this function as follows:

view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)

some times you must use self:

self.view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)

Well that was it, I hope it helps someone .

sorry for my bad english.

this work on iOS 7.1+

Delete files older than 15 days using PowerShell

Another alternative (15. gets typed to [timespan] automatically):

ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose

Auto start print html page using javascript

Use this script

 <script type="text/javascript">
      window.onload = function() { window.print(); }
 </script>

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

How do I view the list of functions a Linux shared library is exporting?

On a MAC, you need to use nm *.o | c++filt, as there is no -C option in nm.

Less aggressive compilation with CSS3 calc

A very common usecase of calc is take 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable = 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

Remove all special characters from a string

This should do what you're looking for:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

Usage:

echo clean('a|"bc!@£de^&$f g');

Will output: abcdef-g

Edit:

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

C/C++ Struct vs Class

C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.

How can I trigger the click event of another element in ng-click using angularjs?

best and simple way to use native java Script which is one liner code.

document.querySelector('#id').click();

Just add 'id' to your html element like

<button id="myId1" ng-click="someFunction()"></button>

check condition in javascript code

if(condition) { document.querySelector('#myId1').click(); }

error::make_unique is not a member of ‘std’

make_unique is an upcoming C++14 feature and thus might not be available on your compiler, even if it is C++11 compliant.

You can however easily roll your own implementation:

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

(FYI, here is the final version of make_unique that was voted into C++14. This includes additional functions to cover arrays, but the general idea is still the same.)

Phonegap Cordova installation Windows

Phonegap can be a little tricky for freshers. I spent much time trying to find the optimum way for creating a robust android application which can access the phone's native features.

This link provides a step wise method for creating a Phonegap android application using windows, html and javascript.

Set selected item of spinner programmatically

In my case, this code saved my day:

public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SpinnerAdapter adapter = spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}

How to wrap text in textview in Android

Use app:breakStrategy="simple" in AppCompatTextView, it will control over paragraph layout.

It has three constant values

  • balanced
  • high_quality
  • simple

Designing in your TextView xml

<android.support.v7.widget.AppCompatTextView
        android:id="@+id/textquestion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:scrollHorizontally="false"
        android:text="Your Question Display Hear....Your Question Display Hear....Your Question Display Hear....Your Question Display Hear...."
        android:textColor="@android:color/black"
        android:textSize="20sp"
        android:textStyle="bold"
        app:breakStrategy="simple" />

If your current minimum api level is 23 or more then in Coding

yourtextview.setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE);

For more refrence refer this BreakStrategy

Textview breakStrategy image

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

Detect HTTP or HTTPS then force HTTPS in JavaScript

Setting location.protocol navigates to a new URL. No need to parse/slice anything.

if (location.protocol !== "https:") {
  location.protocol = "https:";
}

Firefox 49 has a bug where https works but https: does not. Said to be fixed in Firefox 54.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Free Online Team Foundation Server

You can use Visual Studio Team Services for free. Also you can import a TFS repo to this cloud space.

Change text (html) with .animate

refer to official jquery example: and play with it.

.animate({
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );

Replace Fragment inside a ViewPager

tl;dr: Use a host fragment that is responsible for replacing its hosted content and keeps track of a back navigation history (like in a browser).

As your use case consists of a fixed amount of tabs my solution works well: The idea is to fill the ViewPager with instances of a custom class HostFragment, that is able to replace its hosted content and keeps its own back navigation history. To replace the hosted fragment you make a call to the method hostfragment.replaceFragment():

public void replaceFragment(Fragment fragment, boolean addToBackstack) {
    if (addToBackstack) {
        getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).addToBackStack(null).commit();
    } else {
        getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).commit();
    }
}

All that method does is to replace the frame layout with the id R.id.hosted_fragment with the fragment provided to the method.

Check my tutorial on this topic for further details and a complete working example on GitHub!

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

Difference between uint32 and uint32_t

uint32_t is standard, uint32 is not. That is, if you include <inttypes.h> or <stdint.h>, you will get a definition of uint32_t. uint32 is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.

Android emulator-5554 offline

Simply delete and created gear avd again.It will work.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How to remove specific substrings from a set of strings in Python?

# practices 2
str = "Amin Is A Good Programmer"
new_set = str.replace('Good', '')
print(new_set)

 

print : Amin Is A  Programmer

How to use unicode characters in Windows command line?

Try:

chcp 65001

which will change the code page to UTF-8. Also, you need to use Lucida console fonts.

How to sort by column in descending order in Spark SQL?

import org.apache.spark.sql.functions.desc

df.orderBy(desc("columnname1"),desc("columnname2"),asc("columnname3"))

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

Using WAMP is perforce option if we want to use more then one version of php.

CSS media query to target iPad and iPad only?

Well quite same question and there is also an answer =)

http://css-tricks.com/forums/discussion/12708/target-ipad-ipad-only./p1

@media only screen and (device-width: 768px) ...
@media only screen and (max-device-width: 1024px) ...

I can not test it currently so please test it =)

Also found some more:

http://perishablepress.com/press/2010/10/20/target-iphone-and-ipad-with-css3-media-queries/

Or you check the navigator with some javascript and generate / add a css file with javascript

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

How to connect android wifi to adhoc wifi?

You are correct that this is currently not natively supported in Android, although Google has been saying it will be coming ever since Android was officially launched.

While not natively supported, the hardware on every android device released to date do support it. It is just disabled in software, and you would need to enable it in order to use these features.

It is however, fairly easy to do this, but you need to be root, and the specifics may be slightly different between different devices. Your best source for more informationa about this, would be XDA developers: http://forum.xda-developers.com/forumdisplay.php?f=564. Most of the existing solutions are based on replacing wpa_supplicant, and is the method I would recommend if possible on your device. For more details, see http://szym.net/2010/12/adhoc-wifi-in-android/.

Update: Its been a few years now, and whenever I need an ad hoc network connection on my phone I use CyanogenMod. It gives you both programmatic and scripted access to these functions, and the ability to create ad hoc (ibss) networks in the WiFi settings menu.

Mocking HttpClient in unit tests

This is an old question, but I feel the urge to extend the answers with a solution I didn't see here.
You can fake the Microsoft assemly (System.Net.Http) and then use ShinsContext during the test.

  1. In VS 2017, right click on the System.Net.Http assembly and choose "Add Fakes Assembly"
  2. Put your code in the unit test method under a ShimsContext.Create() using. This way, you can isolate the code where you are planning to fake the HttpClient.
  3. Depends on your implementation and test, I would suggest to implement all the desired acting where you call a method on the HttpClient and want to fake the returned value. Using ShimHttpClient.AllInstances will fake your implementation in all the instances created during your test. For example, if you want to fake the GetAsync() method, do the following:

    [TestMethod]
    public void FakeHttpClient()
    {
        using (ShimsContext.Create())
        {
            System.Net.Http.Fakes.ShimHttpClient.AllInstances.GetAsyncString = (c, requestUri) =>
            {
              //Return a service unavailable response
              var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
              var task = Task.FromResult(httpResponseMessage);
              return task;
            };
    
            //your implementation will use the fake method(s) automatically
            var client = new Connection(_httpClient);
            client.doSomething(); 
        }
    }
    

Create auto-numbering on images/figures in MS Word

  • Select whole document (Ctrl+A)
  • Press F9
  • Save

Should update the figure caption automatically.

My question is tho, how can one also 'assign' referenced figures '(Fig.4)' in the text to do the same thing - aka change when an image is added above it?

EDIT: Figured it out.. In word go to Insert and Cross-ref and assign the ref. Then Ctrl+A and F9 and everything should sort itself out.

WCF - How to Increase Message Size Quota

If you're still getting this error message while using the WCF Test Client, it's because the client has a separate MaxBufferSize setting.

To correct the issue:

  1. Right-Click on the Config File node at the bottom of the tree
  2. Select Edit with SvcConfigEditor

A list of editable settings will appear, including MaxBufferSize.

Note: Auto-generated proxy clients also set MaxBufferSize to 65536 by default.

How to run composer from anywhere?

How to run Composer From Anywhere (on MacOS X) via Terminal

Background:

Actually in getComposer website it clearly states that, install the Composer by using the following curl command,

curl -sS https://getcomposer.org/installer |php

And it certainly does what it's intended to do. And then it says to move the composer.phar to the directory /usr/local/bin/composer and then composer will be available Globally, by using the following command line in terminal!

mv composer.phar /usr/local/bin/composer

Question:

So the problem which leads me to Google over it is when I executed the above line in Mac OS X Terminal, it said that, Permission denied. Like as follows:

mv: rename composer.phar to /usr/local/bin/composer: Permission denied

Answer:

Following link led me to the solution like a charm and I'm thankful to that. The thing I just missed was sudo command before the above stated "Move" command line. Now my Move command is as follows:

sudo mv composer.phar /usr/local/bin/composer
Password:

It directly prompts you to authenticate yourself and see if you are authorized. So if you enter a valid password, then the Moving will be done, and you can just check if composer is globally installed, by using the following line.

composer about

I hope this answer helped you to broaden your view and finally resolve your problem.

Cheers!

pip issue installing almost any library

To install any other package I have to use the latest version of pip, since the 9.0.1 has this SSL problem. To upgrade the pip by pip itself, I have to solve this SSL problem first. To jump out of this endless loop, I find this only way that works for me.

  1. Find the latest version of pip in this page: https://pypi.org/simple/pip/
  2. Download the .whl file of the latest version.
  3. Use pip to install the latest pip. (Use your own latest version here)

sudo pip install pip-10.0.1-py2.py3-none-any.whl

Now the pip is the latest version and can install anything.

How can I detect the touch event of an UIImageView?

First, you should place an UIButton and then either you can add a background image for this button, or you need to place an UIImageView over the button.

Or:

You can add the tap gesture to a UIImageView so that get the click action when tap on the UIImageView.

Android get image path from drawable as string

based on the some of above replies i improvised it a bit

create this method and call it by passing your resource

Reusable Method

public String getURLForResource (int resourceId) {
    //use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
    return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}

Sample call

getURLForResource(R.drawable.personIcon)

complete example of loading image

String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
 Glide.with(patientProfileImageView.getContext())
          .load(imageUrl)
          .into(patientProfileImageView);

you can move the function getURLForResource to a Util file and make it static so it can be reused

How to list active connections on PostgreSQL?

Following will give you active connections/ queries in postgres DB-

SELECT 
    pid
    ,datname
    ,usename
    ,application_name
    ,client_hostname
    ,client_port
    ,backend_start
    ,query_start
    ,query
    ,state
FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

How many bytes in a JavaScript string?

A single element in a JavaScript String is considered to be a single UTF-16 code unit. That is to say, Strings characters are stored in 16-bit (1 code unit), and 16-bit is equal to 2 bytes (8-bit = 1 byte).

The charCodeAt() method can be used to return an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

The codePointAt() can be used to return the entire code point value for Unicode characters, e.g. UTF-32.

When a UTF-16 character can't be represented in a single 16-bit code unit, it will have a surrogate pair and therefore use two code units( 2 x 16-bit = 4 bytes)

See Unicode encodings for different encodings and their code ranges.

How do I drop a function if it already exists?

You have two options to drop and recreate the procedure in SQL Server 2016.

Starting from SQL Server 2016 - use IF EXISTS

DROP FUNCTION [ IF EXISTS ] { [ schema_name. ] function_name } [ ,...n ]   [;]

Starting from SQL Server 2016 SP1 - use OR ALTER

CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name   

Launching a website via windows commandline

IE has a setting, located in Tools / Internet options / Advanced / Browsing, called Reuse windows for launching shortcuts, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).

Can not find the tag library descriptor of springframework

I finally configured RAD to build my Maven-based project, but was getting the following exception when I navigate to a page that uses the Spring taglib:

JSPG0047E: Unable to locate tag library for uri http://www.springframework.org/tags at com.ibm.ws.jsp.translator.visitor.tagfiledep.TagFileDependencyVisitor.visitCustomTagStart(TagFileDependencyVisitor.java:76) ...

The way I had configured my EAR, all the jars were in the EAR, not in the WAR’s WEB-INF/lib. According to the JSP 2.0 spec, I believe tag libs are searched for in all subdirectories of WEB-INF, hence the issue. My solution was to copy the tld files and place under WEB-INF/lib or WEB-INF.. Then it worked.

Any way to replace characters on Swift String?

you can test this:

let newString = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)

How can I use goto in Javascript?

// example of goto in javascript:

var i, j;
loop_1:
    for (i = 0; i < 3; i++) { //The first for statement is labeled "loop_1"
        loop_2:
            for (j = 0; j < 3; j++) { //The second for statement is labeled "loop_2"
                if (i === 1 && j === 1) {
                    continue loop_1;
                }
                console.log('i = ' + i + ', j = ' + j);
            }
        }

Can I set up HTML/Email Templates with ASP.NET?

@bardev provides a good solution, but unfortunately it's not ideal in all cases. Mine was one of them.

I'm using WebForms in a Website (I swear I'll never use a Website again--what a PITA) in VS 2013.

I tried the Razor suggestion, but mine being a Website I didn't get the all-important IntelliSense that the IDE delivers in an MVC project. I also like to use the designer for my templates--a perfect spot for a UserControl.

Nix on Razor again.

So I came up with this little framework instead (hat tips to @mun for UserControl and @imatoria for Strong Typing). Just about the only potential trouble spot I can see is that you have to be careful to keep your .ASCX filename in sync with its class name. If you stray, you'll get a runtime error.

FWIW: In my testing at least the RenderControl() call doesn't like a Page control, so I went with UserControl.

I'm pretty sure I've included everything here; let me know if I left something out.

HTH

Usage:

Partial Class Purchase
  Inherits UserControl

  Private Sub SendReceipt()
    Dim oTemplate As MailTemplates.PurchaseReceipt

    oTemplate = MailTemplates.Templates.PurchaseReceipt(Me)
    oTemplate.Name = "James Bond"
    oTemplate.OrderTotal = 3500000
    oTemplate.OrderDescription = "Q-Stuff"
    oTemplate.InjectCss("PurchaseReceipt")

    Utils.SendMail("{0} <[email protected]>".ToFormat(oTemplate.Name), "Purchase Receipt", oTemplate.ToHtml)
  End Sub
End Class

Base Class:

Namespace MailTemplates
  Public MustInherit Class BaseTemplate
    Inherits UserControl

    Public Shared Function GetTemplate(Caller As TemplateControl, Template As Type) As BaseTemplate
      Return Caller.LoadControl("~/MailTemplates/{0}.ascx".ToFormat(Template.Name))
    End Function



    Public Sub InjectCss(FileName As String)
      If Me.Styler IsNot Nothing Then
        Me.Styler.Controls.Add(New Controls.Styler(FileName))
      End If
    End Sub



    Private ReadOnly Property Styler As PlaceHolder
      Get
        If _Styler Is Nothing Then
          _Styler = Me.FindNestedControl(GetType(PlaceHolder))
        End If

        Return _Styler
      End Get
    End Property
    Private _Styler As PlaceHolder
  End Class
End Namespace

"Factory" Class:

Namespace MailTemplates
  Public Class Templates
    Public Shared ReadOnly Property PurchaseReceipt(Caller As TemplateControl) As PurchaseReceipt
      Get
        Return BaseTemplate.GetTemplate(Caller, GetType(PurchaseReceipt))
      End Get
    End Property
  End Class
End Namespace

Template Class:

Namespace MailTemplates
  Public MustInherit Class PurchaseReceipt
    Inherits BaseTemplate

    Public MustOverride WriteOnly Property Name As String
    Public MustOverride WriteOnly Property OrderTotal As Decimal
    Public MustOverride WriteOnly Property OrderDescription As String
  End Class
End Namespace

ASCX Header:

<%@ Control Language="VB" ClassName="_Header" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!--
  See https://www.campaignmonitor.com/blog/post/3317/ for discussion of DocType in HTML Email
-->

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <asp:PlaceHolder ID="plcStyler" runat="server"></asp:PlaceHolder>
</head>
<body>

ASCX Footer:

<%@ Control Language="VB" ClassName="_Footer" %>

</body>
</html>

ASCX Template:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="PurchaseReceipt.ascx.vb" Inherits="PurchaseReceipt" %>

<%@ Register Src="_Header.ascx" TagName="Header" TagPrefix="uc" %>
<%@ Register Src="_Footer.ascx" TagName="Footer" TagPrefix="uc" %>

<uc:Header ID="ctlHeader" runat="server" />

  <p>Name: <asp:Label ID="lblName" runat="server"></asp:Label></p>
  <p>Order Total: <asp:Label ID="lblOrderTotal" runat="server"></asp:Label></p>
  <p>Order Description: <asp:Label ID="lblOrderDescription" runat="server"></asp:Label></p>

<uc:Footer ID="ctlFooter" runat="server" />

ASCX Template CodeFile:

Partial Class PurchaseReceipt
  Inherits MailTemplates.PurchaseReceipt

  Public Overrides WriteOnly Property Name As String
    Set(Value As String)
      lblName.Text = Value
    End Set
  End Property



  Public Overrides WriteOnly Property OrderTotal As Decimal
    Set(Value As Boolean)
      lblOrderTotal.Text = Value
    End Set
  End Property



  Public Overrides WriteOnly Property OrderDescription As Decimal
    Set(Value As Boolean)
      lblOrderDescription.Text = Value
    End Set
  End Property
End Class

Helpers:

'
' FindNestedControl helpers based on tip by @andleer
' at http://stackoverflow.com/questions/619449/
'

Public Module Helpers
  <Extension>
  Public Function AllControls(Control As Control) As List(Of Control)
    Return Control.Controls.Flatten
  End Function



  <Extension>
  Public Function FindNestedControl(Control As Control, Id As String) As Control
    Return Control.Controls.Flatten(Function(C) C.ID = Id).SingleOrDefault
  End Function



  <Extension>
  Public Function FindNestedControl(Control As Control, Type As Type) As Control
    Return Control.Controls.Flatten(Function(C) C.GetType = Type).SingleOrDefault
  End Function



  <Extension>
  Public Function Flatten(Controls As ControlCollection) As List(Of Control)
    Flatten = New List(Of Control)

    Controls.Traverse(Sub(Control) Flatten.Add(Control))
  End Function


  <Extension>
  Public Function Flatten(Controls As ControlCollection, Predicate As Func(Of Control, Boolean)) As List(Of Control)
    Flatten = New List(Of Control)

    Controls.Traverse(Sub(Control)
                        If Predicate(Control) Then
                          Flatten.Add(Control)
                        End If
                      End Sub)
  End Function



  <Extension>
  Public Sub Traverse(Controls As ControlCollection, Action As Action(Of Control))
    Controls.Cast(Of Control).ToList.ForEach(Sub(Control As Control)
                                               Action(Control)

                                               If Control.HasControls Then
                                                 Control.Controls.Traverse(Action)
                                               End If
                                             End Sub)
  End Sub



  <Extension()>
  Public Function ToFormat(Template As String, ParamArray Values As Object()) As String
    Return String.Format(Template, Values)
  End Function



  <Extension()>
  Public Function ToHtml(Control As Control) As String
    Dim oSb As StringBuilder

    oSb = New StringBuilder

    Using oSw As New StringWriter(oSb)
      Using oTw As New HtmlTextWriter(oSw)
        Control.RenderControl(oTw)
        Return oSb.ToString
      End Using
    End Using
  End Function
End Module



Namespace Controls
  Public Class Styler
    Inherits LiteralControl

    Public Sub New(FileName As String)
      Dim _
        sFileName,
        sFilePath As String

      sFileName = Path.GetFileNameWithoutExtension(FileName)
      sFilePath = HttpContext.Current.Server.MapPath("~/Styles/{0}.css".ToFormat(sFileName))

      If File.Exists(sFilePath) Then
        Me.Text = "{0}<style type=""text/css"">{0}{1}</style>{0}".ToFormat(vbCrLf, File.ReadAllText(sFilePath))
      Else
        Me.Text = String.Empty
      End If
    End Sub
  End Class
End Namespace



Public Class Utils
  Public Shared Sub SendMail(Recipient As MailAddress, Subject As String, HtmlBody As String)
    Using oMessage As New MailMessage
      oMessage.To.Add(Recipient)
      oMessage.IsBodyHtml = True
      oMessage.Subject = Subject.Trim
      oMessage.Body = HtmlBody.Trim

      Using oClient As New SmtpClient
        oClient.Send(oMessage)
      End Using
    End Using
  End Sub
End Class

Uncaught ReferenceError: function is not defined with onclick

I think you put the function in the $(document).ready....... The functions are always provided out the $(document).ready.......

Download a file with Android, and showing the progress in a ProgressDialog

Important

AsyncTask is deprecated in Android 11.

For more information please checkout following posts

Probably should move to concorency Framework as suggested by google

How to create python bytes object from long hex string?

Works in Python 2.7 and higher including python3:

result = bytearray.fromhex('deadbeef')

Note: There seems to be a bug with the bytearray.fromhex() function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown:

>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str`

HTML/CSS - Adding an Icon to a button

You could add a span before the link with a specific class like so:

<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>

And then give that a specific width and a background image just like you are doing with the button itself.

.btn span.icon {
    background: url(imgs/icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}

I am no CSS guru but off the top of my head I think that should work.

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

How do I assert an Iterable contains elements with a certain property?

As long as your List is a concrete class, you can simply call the contains() method as long as you have implemented your equals() method on MyItem.

// given 
// some input ... you to complete

// when
List<MyItems> results = service.getMyItems();

// then
assertTrue(results.contains(new MyItem("foo")));
assertTrue(results.contains(new MyItem("bar")));

Assumes you have implemented a constructor that accepts the values you want to assert on. I realise this isn't on a single line, but it's useful to know which value is missing rather than checking both at once.

How to input a regex in string.replace?

I would go like this (regex explained in comments):

import re

# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")

# <\/{0,}\[\d+>
# 
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»

subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>"""

result = pattern.sub("", subject)

print(result)

If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

Convert UTC Epoch to local date

If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.

For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.

The Number and Date extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.

I recommend you to check the Code Snippet down below to test this solution.

Conversions from milliseconds

Number.prototype.toLocalDate = function () {
    var value = new Date(this);

    value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));

    return value;
};

Number.prototype.toUTCDate = function () {
    var value = new Date(this);

    value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));

    return value;
};

Conversions from dates

Date.prototype.getUTCTime = function () {
    return this.getTime() - (this.getTimezoneOffset() * 60000);
};

Usage

// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();

// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();

See it for yourself

_x000D_
_x000D_
// Extending Number_x000D_
_x000D_
Number.prototype.toLocalDate = function () {_x000D_
    var value = new Date(this);_x000D_
_x000D_
    value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));_x000D_
_x000D_
    return value;_x000D_
};_x000D_
_x000D_
Number.prototype.toUTCDate = function () {_x000D_
    var value = new Date(this);_x000D_
_x000D_
    value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));_x000D_
_x000D_
    return value;_x000D_
};_x000D_
_x000D_
// Extending Date_x000D_
_x000D_
Date.prototype.getUTCTime = function () {_x000D_
    return this.getTime() - (this.getTimezoneOffset() * 60000);_x000D_
};_x000D_
_x000D_
// Getting the demo to work_x000D_
document.getElementById('m-to-local-button').addEventListener('click', function () {_x000D_
  var displayElement = document.getElementById('m-to-local-display'),_x000D_
      value = document.getElementById('m-to-local').value,_x000D_
      milliseconds = parseInt(value);_x000D_
  _x000D_
  if (typeof milliseconds === 'number')_x000D_
    displayElement.innerText = (milliseconds).toLocalDate().toISOString();_x000D_
  else_x000D_
    displayElement.innerText = 'Set a value';_x000D_
}, false);_x000D_
_x000D_
document.getElementById('m-to-utc-button').addEventListener('click', function () {_x000D_
  var displayElement = document.getElementById('m-to-utc-display'),_x000D_
      value = document.getElementById('m-to-utc').value,_x000D_
      milliseconds = parseInt(value);_x000D_
  _x000D_
  if (typeof milliseconds === 'number')_x000D_
    displayElement.innerText = (milliseconds).toUTCDate().toISOString();_x000D_
  else_x000D_
    displayElement.innerText = 'Set a value';_x000D_
}, false);_x000D_
_x000D_
document.getElementById('date-to-utc-button').addEventListener('click', function () {_x000D_
  var displayElement = document.getElementById('date-to-utc-display'),_x000D_
      yearValue = document.getElementById('date-to-utc-year').value || '1970',_x000D_
      monthValue = document.getElementById('date-to-utc-month').value || '0',_x000D_
      dayValue = document.getElementById('date-to-utc-day').value || '1',_x000D_
      hourValue = document.getElementById('date-to-utc-hour').value || '0',_x000D_
      minuteValue = document.getElementById('date-to-utc-minute').value || '0',_x000D_
      secondValue = document.getElementById('date-to-utc-second').value || '0',_x000D_
      year = parseInt(yearValue),_x000D_
      month = parseInt(monthValue),_x000D_
      day = parseInt(dayValue),_x000D_
      hour = parseInt(hourValue),_x000D_
      minute = parseInt(minuteValue),_x000D_
      second = parseInt(secondValue);_x000D_
  _x000D_
  displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();_x000D_
}, false);
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="ui container">_x000D_
  <p></p>_x000D_
  _x000D_
  <h3>Milliseconds to local date</h3>_x000D_
  <input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>_x000D_
  <em id="m-to-local-display">Set a value</em>_x000D_
_x000D_
  <h3>Milliseconds to UTC date</h3>_x000D_
  <input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>_x000D_
  <em id="m-to-utc-display">Set a value</em>_x000D_
  _x000D_
  <h3>Date to milliseconds in UTC</h3>_x000D_
  <input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />_x000D_
  <input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />_x000D_
  <input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />_x000D_
  <input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />_x000D_
  <input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />_x000D_
  <input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />_x000D_
  <button id="date-to-utc-button">Convert</button>_x000D_
  <em id="date-to-utc-display">Set the values</em>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Disabling tab focus on form elements

My case may not be typical but what I wanted to do was to have certain columns in a TABLE completely "inert": impossible to tab into them, and impossible to select anything in them. I had found class "unselectable" from other SO answers:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

This actually prevents the user using the mouse to put the focus in the TD ... but I couldn't find a way on SO to prevent tabbing into cells. The TDs in my TABLE actually each has a DIV as their sole child, and using console.log I found that in fact the DIVs would get the focus (without the focus first being obtained by the TDs).

My solution involves keeping track of the "previously focused" element (anywhere on the page):

window.currFocus = document;
//Catch any bubbling focusin events (focus does not bubble)
$(window).on('focusin', function () {
  window.prevFocus = window.currFocus;
  window.currFocus = document.activeElement;
});

I can't really see how you'd get by without a mechanism of this kind... jolly useful for all sorts of purposes ... and of course it'd be simple to transform it into a stack of recently focused elements, if you wanted that...

The simplest answer is then just to do this (to the sole DIV child in every newly created TD):

...
jqNewCellDiv[ 0 ].classList.add( 'unselectable' );
jqNewCellDiv.focus( function() {
    window.prevFocus.focus();
});         

So far so good. It should be clear that this would work if you just have a TD (with no DIV child). Slight issue: this just stops tabbing dead in its tracks. Clearly if the table has any more cells on that row or rows below the most obvious action you'd want is to making tabbing tab to the next non-unselectable cell ... either on the same row or, if there are other rows, on the row below. If it's the very end of the table it gets a bit more tricky: i.e. where should tabbing go then. But all good clean fun.

How to add font-awesome to Angular 2 + CLI project

This post describes how to integrate Fontawesome 5 into Angular 6 (Angular 5 and previous versions will also work, but then you have to adjust my writings)

Option 1: Add the css-Files

Pro: Every icon will be included

Contra: Every icon will be included (bigger app size because all fonts are included)

Add the following package:

npm install @fortawesome/fontawesome-free-webfonts

Afterwards add the following lines to your angular.json:

"app": {
....
"styles": [
....
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fontawesome.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-regular.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-brands.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-solid.css"
],
...    
}

Option 2: Angular package

Pro: Smaller app size

Contra: You have to include every icon you want to use seperatly

Use the FontAwesome 5 Angular package:

npm install @fortawesome/angular-fontawesome

Just follow their documentation to add the icons. They use the svg-icons, so you only have to add the svgs / icons, you really use.

How to detect the screen resolution with JavaScript?

just for future reference:

function getscreenresolution()
{
    window.alert("Your screen resolution is: " + screen.height + 'x' + screen.width);
}

Can Flask have optional URL parameters?

Almost the same as Audrius cooked up some months ago, but you might find it a bit more readable with the defaults in the function head - the way you are used to with python:

@app.route('/<user_id>')
@app.route('/<user_id>/<username>')
def show(user_id, username='Anonymous'):
    return user_id + ':' + username

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

Convert base class to derived class

No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.

Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.

Image convert to Base64

_x000D_
_x000D_
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

/* Simple */
function previewImage( image, preview, string )
{

    var preview     = document.querySelector( preview );
    var fileImage   = image.files[0];

    var reader      = new FileReader();

    reader.addEventListener( "load", function() {

        preview.style.height    = "100";
        preview.title           = fileImage.name;

        // convert image file to base64 string
        preview.src             = reader.result;

        /* --- */

        document.querySelector( string ).value = reader.result;                    

    }, false );

    if ( fileImage )
    {
        reader.readAsDataURL( fileImage );
    }

}

document.querySelector( "#imageID" ).addEventListener( "change", function() {

    previewImage( this, "#imagePreviewID", "#imageStringID" );

} )
/* Simple || */
_x000D_
<form>

    File Upload: <input type="file" id="imageID" /><br />
    Preview: <img src="#" id="imagePreviewID" /><br />    
    String base64: <textarea id="imageStringID" rows="10" cols="50"></textarea>

</form>
_x000D_
_x000D_
_x000D_

codesanbox

How do I include negative decimal numbers in this regular expression?

I have some experiments about regex in django url, which required from negative to positive numbers

^(?P<pid>(\-\d+|\d+))$

Let's we focused on this (\-\d+|\d+) part and ignoring others, this semicolon | means OR in regex, then the negative value will match with this \-\d+ part, and positive value into this \d+

How to pass data in the ajax DELETE request other than headers

Read this Bug Issue: http://bugs.jquery.com/ticket/11586

Quoting the RFC 2616 Fielding

The DELETE method requests that the origin server delete the resource identified by the Request-URI.

So you need to pass the data in the URI

$.ajax({
    url: urlCall + '?' + $.param({"Id": Id, "bolDeleteReq" : bolDeleteReq}),
    type: 'DELETE',
    success: callback || $.noop,
    error: errorCallback || $.noop
});

How to display raw html code in PRE or something like it but without escaping it

xmp is the way to go, i.e.:

<xmp>
  # your code...
</xmp>

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

For anyone landing here who is trying to upgrade from MVC 4 to MVC5, I was able to resolve this issue by following the instructions at http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2.

I also had to install the "Microsoft.AspNet.WebApi.WebHost" package from nuget. But that's it.

Oh, and I had to create this appSetting: <add key="owin:AutomaticAppStartup" value="false" />

:)

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Open a URL without using a browser from a batch file

You can try put in a shortcut to the site and tell the .bat file to open that.

start Google.HTML
exit

How to monitor SQL Server table changes by using c#?

Use SqlTableDependency. It is a c# component raising events when a record is changes. You can find others detail at: https://github.com/christiandelbianco/monitor-table-change-with-sqltabledependency

It is similat to .NET SqlDependency except that SqlTableDependency raise events containing modified / deleted or updated database table values:

string conString = "data source=.;initial catalog=myDB;integrated security=True";

using(var tableDependency = new SqlTableDependency<Customers>(conString))
{
    tableDependency.OnChanged += TableDependency_Changed;
    tableDependency.Start();

    Console.WriteLine("Waiting for receiving notifications...");
    Console.WriteLine("Press a key to stop");
    Console.ReadKey();
}
...
...
void TableDependency_Changed(object sender, RecordChangedEventArgs<Customers> e)
{
    if (e.ChangeType != ChangeType.None)
    {
        var changedEntity = e.Entity;
        Console.WriteLine("DML operation: " + e.ChangeType);
        Console.WriteLine("ID: " + changedEntity.Id);
        Console.WriteLine("Name: " + changedEntity.Name);
        Console.WriteLine("Surname: " + changedEntity.Surname);
    }
}

How to transform currentTimeMillis to a readable date format?

There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

Create a directly-executable cross-platform GUI app using Python

Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed.

Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however.

MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X.

IIS Manager in Windows 10

Windows features, ISS Management Console

Under the windows feature list, make sure to check the IIS Management Console You also need to check additional check boxes as shown below:

Windows features, ISS, HTTP Features

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

In my case the problem was caused due to an apparent lost of permission over mongodb.lock file. I could solve the problem changing the permission with the following command :

sudo chown mongodb:mongodb /var/lib/mongodb/mongodb.lock

There follows my investigation: step-by-step verification

Android BroadcastReceiver within Activity

Your also have to register the receiver in onCreate(), like this:

IntentFilter filter = new IntentFilter();
filter.addAction("csinald.meg");
registerReceiver(receiver, filter);

How do I pass JavaScript values to Scriptlet in JSP?

You cannot do that but you can do the opposite:

In your jsp you can:

String name = "John Allepe";    
request.setAttribute("CustomerName", name);

Access the variable in the js:

var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);

How do I create dynamic variable names inside a loop?

 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

Hiding elements in responsive layout?

I have a couple of clarifications to add here:

1) The list shown (visible-phone, visible-tablet, etc.) is deprecated in Bootstrap 3. The new values are:

  • visible-xs-*
  • visible-sm-*
  • visible-md-*
  • visible-lg-*
  • hidden-xs-*
  • hidden-sm-*
  • hidden-md-*
  • hidden-lg-*

The asterisk translates to the following for each (I show only visible-xs-* below):

  • visible-xs-block
  • visible-xs-inline
  • visible-xs-inline-block

2) When you use these classes, you don't add a period in front (as confusingly shown in part of the answer above).

For example:

<div class="visible-md-block col-md-6 text-right text-muted">
   <h5>Copyright &copy; 2014 Jazimov</h5>
</div>

3) You can use visible-* and hidden-* (for example, visible-xs and hidden-xs) but these have been deprecated in Bootstrap 3.2.0.

For more details and the latest specs, go here and search for "visible": http://getbootstrap.com/css/

Cannot download Docker images behind a proxy

On Ubuntu 14.04 (Trusty Tahr) with Docker 1.9.1, I just uncommented the http_proxy line, updated the value and then restarted the Docker service.

export http_proxy="http://proxy.server.com:80"

and then

service docker restart

.setAttribute("disabled", false); changes editable attribute to false

Using method set and remove attribute

_x000D_
_x000D_
function radioButton(o) {_x000D_
_x000D_
  var text = document.querySelector("textarea");_x000D_
_x000D_
  if (o.value == "on") {_x000D_
    text.removeAttribute("disabled", "");_x000D_
    text.setAttribute("enabled", "");_x000D_
  } else {_x000D_
    text.removeAttribute("enabled", "");_x000D_
    text.setAttribute("disabled", "");_x000D_
  }_x000D_
  _x000D_
}
_x000D_
<input type="radio" name="radioButton" value="on" onclick = "radioButton(this)" />Enable_x000D_
<input type="radio" name="radioButton" value="off" onclick = "radioButton(this)" />Disabled<hr/>_x000D_
_x000D_
<textarea disabled ></textarea>
_x000D_
_x000D_
_x000D_

How to handle Pop-up in Selenium WebDriver using Java

Do not make the situation complex. Use ID if they are available.

driver.get("http://www.rediff.com");
WebElement sign = driver.findElement(By.linkText("Sign in"));
sign.click();
WebElement email_id= driver.findElement(By.id("c_uname"));
email_id.sendKeys("hi");

Adb over wireless without usb cable at all for not rooted phones

For your question

Adb over wireless without USB cable at all for not rooted phones

 You can't do it for now without USB cable.

But you have an option:

Note: You need put USB at least once to achieve the following:

You need to connect your device to your computer via USB cable. Make sure USB debugging is working. You can check if it shows up when running adb devices.

Open cmd in ...\AppData\Local\Android\sdk\platform-tools

Step1: Run adb devices

Ex: C:\pathToSDK\platform-tools>adb devices

You can check if it shows up when running adb devices.

Step2: Run adb tcpip 5555

Ex: C:\pathToSDK\platform-tools>adb tcpip 5555

Disconnect your device (remove the USB cable).

Step3: Go to the Settings -> About phone -> Status to view the IP address of your phone.

.

Step4: Run `adb connect

Ex: C:\pathToSDK\platform-tools>adb connect 192.168.0.2

Step5: Run adb devices again, you should see your device.

Now you can execute adb commands or use your favourite IDE for android development - wireless!

Now you might ask, what do I have to do when I move into a different work space and change WiFi networks? You do not have to repeat steps 1 to 3 (these set your phone into WiFi-debug mode). You do have to connect to your phone again by executing steps 4 to 6.

Unfortunately, the android phones lose the WiFi-debug mode when restarting. Thus, if your battery died, you have to start over. Otherwise, if you keep an eye on your battery and do not restart your phone, you can live without a cable for weeks!

See here for more

Happy wireless coding!

Ref: https://futurestud.io/tutorials/how-to-debug-your-android-app-over-wifi-without-root

UPDATE:

If you set C:\pathToSDK\platform-tools this path in Environment variables then there is no need to repeat all steps, you can simply use only Step 4 that's it, it will connect to your device.

To set path : My Computer-> Right click--> properties -> Advanced system settings -> Environment variables -> edit path in System variables -> paste the platform-tools path in variable value -> ok -> ok -> ok

How to get MD5 sum of a string using python?

Use hashlib.md5 in Python 3.

import hashlib

source = '000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite'.encode()
md5 = hashlib.md5(source).hexdigest() # returns a str
print(md5) # a02506b31c1cd46c2e0b6380fb94eb3d

If you need byte type output, use digest() instead of hexdigest().

AttributeError: Module Pip has no attribute 'main'

I fixed this problem upgrading to latest version

sudo pip install --upgrade pip

My version: pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)

Assembly code vs Machine code vs Object code?

Assembly is short descriptive terms humans can understand that can be directly translated into the machine code that a CPU actually uses.

While somewhat understandable by humans, Assembler is still low level. It takes a lot of code to do anything useful.

So instead we use higher level languages such as C, BASIC, FORTAN (OK I know I've dated myself). When compiled these produce object code. Early languages had machine language as their object code.

Many languages today such a JAVA and C# usually compile into a bytecode that is not machine code, but one that easily be interpreted at run time to produce machine code.

Permutations between two lists of unequal length

Note: This answer is for the specific question asked above. If you are here from Google and just looking for a way to get a Cartesian product in Python, itertools.product or a simple list comprehension may be what you are looking for - see the other answers.


Suppose len(list1) >= len(list2). Then what you appear to want is to take all permutations of length len(list2) from list1 and match them with items from list2. In python:

import itertools
list1=['a','b','c']
list2=[1,2]

[list(zip(x,list2)) for x in itertools.permutations(list1,len(list2))]

Returns

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]

Remove all line breaks from a long string of text

A method taking into consideration

  • additional white characters at the beginning/end of string
  • additional white characters at the beginning/end of every line
  • various end-line characters

it takes such a multi-line string which may be messy e.g.

test_str = '\nhej ho \n aaa\r\n   a\n '

and produces nice one-line string

>>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
'hej ho aaa a'

UPDATE: To fix multiple new-line character producing redundant spaces:

' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])

This works for the following too test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '

Run all SQL files in a directory

You could use ApexSQL Propagate. It is a free tool which executes multiple scripts on multiple databases. You can select as many scripts as you need and execute them against one or multiple databases (even multiple servers). You can create scripts list and save it, then just select that list each time you want to execute those same scripts in the created order (multiple script lists can be added also):

Select scripts

When scripts and databases are selected, they will be shown in the main window and all you have to do is to click the “Execute” button and all scripts will be executed on selected databases in the given order:

Scripts execution

Find the max of 3 numbers in Java with different data types

Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).

How to get the first and last date of the current year?

For start date of current year:

SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())

For end date of current year:

SELECT DATEADD(DD,-1,DATEADD(YY,DATEDIFF(YY,0,GETDATE())+1,0))

How to completely remove Python from a Windows machine?

I had window 7 (64 bit) and Python 2.7.12, I uninstalled it by clicking the python installer from the "download" directory then I selected remove python then I clicked “ finish”.
I also removed the remaining python associated directory & files from the c: drive and also from “my documents” folder, since I created some files there.

Disable beep of Linux Bash on Windows 10

  1. To disable the beep in bash you need to uncomment (or add if not already there) the line set bell-style none in your /etc/inputrc file.

    Note: Since it is a protected file you need to be a privileged user to edit it (i.e. launch your text editor with something like sudo <editor> /etc/inputrc).

  2. To disable the beep also in vim you need to add set visualbell in your ~/.vimrc file.

  3. To disable the beep also in less (i.e. also in man pages and when using "git diff") you need to add export LESS="$LESS -R -Q" in your ~/.profile file.

Most common C# bitwise operations on enums

To test a bit you would do the following: (assuming flags is a 32 bit number)

Test Bit:

if((flags & 0x08) == 0x08)
(If bit 4 is set then its true) Toggle Back (1 - 0 or 0 - 1):
flags = flags ^ 0x08;
Reset Bit 4 to Zero:
flags = flags & 0xFFFFFF7F;

How to download source in ZIP format from GitHub?

As of June 2016, the Download ZIP button is still under the <> Code tab, however it is now inside a button with two options clone or download:

Symfony image example

iPhone system font

If you're doing programatic customisation, don't hard code the system font. Use UIFont systemFontOfSize:, UIFont boldSystemFontOfSize: and UIFont italicSystemFontOfSize (Apple documentation).

This has become especially relevant since iOS 7, which changed the system font to Helvetica Neue.

This has become super especially relevant since iOS 9, which changed the system font again to San Francisco.

d3.select("#element") not working when code above the html element

just add your <script src="./custom.js"></script> before </bod> tag. that is supply time to d3.select(#chart) detect your #chart element in html body

PHP prepend leading zero before single digit number, on-the-fly

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

It will only add the zero if it's less than the required number of characters.

Edit: As pointed out by @FelipeAls:

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

Serving static web resources in Spring Boot & Spring Security application

If you are using webjars. You need to add this in your configure method: http.authorizeRequests().antMatchers("/webjars/**").permitAll();

Make sure this is the first statement. For example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

You will also need to have this in order to have webjars enabled:

@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }

How do I import CSV file into a MySQL table?

The mysql command line is prone to too many problems on import. Here is how you do it:

  • use excel to edit the header names to have no spaces
  • save as .csv
  • use free Navicat Lite Sql Browser to import and auto create a new table (give it a name)
  • open the new table insert a primary auto number column for ID
  • change the type of the columns as desired.
  • done!

Why do we use web.xml?

It says all the requests to go through WicketFilter


Also, if you use wicket WicketApplication for application level settings. Like URL patterns and things that are true at app level


This is what you need really, http://wicket.apache.org/learn/examples/helloworld.html

Linux: where are environment variables stored?

The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in

/proc/pid/environ

This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do

cat /proc/3940/environ | tr '\0' '\n'

Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.

Get min and max value in PHP Array

foreach ($array as $k => $v) {
  $tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);

Update UI from Thread in Android

As recommended by official documentation, you can use AsyncTask to handle work items shorter than 5ms in duration. If your task take more time, lookout for other alternatives.

HandlerThread is one alternative to Thread or AsyncTask. If you need to update UI from HandlerThread, post a message on UI Thread Looper and UI Thread Handler can handle UI updates.

Example code:

Android: Toast in a thread

Is there a limit on how much JSON can hold?

If you are working with ASP.NET MVC, you can solve the problem by adding the MaxJsonLength to your result:

var jsonResult = Json(new
{
    draw = param.Draw,
    recordsTotal = count,
    recordsFiltered = count,
    data = result
}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;

Can't install any packages in Node.js using "npm install"

If you happened to run npm install command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.

How to change Vagrant 'default' machine name?

If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:

Change the basebox name, when using "vagrant status"

 config.vm.define "tendo" do |tendo|
  end

Where "tendo" will be the name that will appear instead of default

What is the GAC in .NET?

GAC (Global Assembly Cache) is where all shared .NET assembly reside.

Checking oracle sid and database name

Type on sqlplus command prompt

SQL> select * from global_name;

then u will be see result on command prompt

SQL ORCL.REGRESS.RDBMS.DEV.US.ORACLE.COM

Here first one "ORCL" is database name,may be your system "XE" and other what was given on oracle downloading time.

JQuery - $ is not defined

I was having this same problem and couldn't figure out what was causing it. I recently converted my HTML files from Japanese to UTF-8, but I didn't do anything with the script files. Somehow jquery-1.10.2.min.js became corrupted in this process (I still have no idea how). Replacing jquery-1.10.2.min.js with the original fixed it.

Uncaught TypeError: Cannot assign to read only property

I tried changing year to a different term, and it worked.

public_methods : {
    get: function() {
        return this._year;
    },

    set: function(newValue) {
        if(newValue > this.originYear) {
            this._year = newValue;
            this.edition += newValue - this.originYear;
        }
    }
}

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

I had the same problem. This is related to hibernate. I changed the database from dev to production in hibernate.cfg.xml but there were catalog attribute in other hbm.xml files with the old database name and it was causing the issue.

Instead of telling incorrect database name, it showed Permission denied error.

So make sure to change the database name everywhere or just remove the catalog attribute

Dynamic SELECT TOP @var In SQL Server

In x0n's example, it should be:

SET ROWCOUNT @top

SELECT * from sometable

SET ROWCOUNT 0

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

How can I split this comma-delimited string in Python?

How about a list?

mystring.split(",")

It might help if you could explain what kind of info we are looking at. Maybe some background info also?

EDIT:

I had a thought you might want the info in groups of two?

then try:

re.split(r"\d*,\d*", mystring)

and also if you want them into tuples

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

in a more readable form:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

Postgresql query between date ranges

With dates (and times) many things become simpler if you use >= start AND < end.

For example:

SELECT
  user_id
FROM
  user_logs
WHERE
      login_date >= '2014-02-01'
  AND login_date <  '2014-03-01'

In this case you still need to calculate the start date of the month you need, but that should be straight forward in any number of ways.

The end date is also simplified; just add exactly one month. No messing about with 28th, 30th, 31st, etc.


This structure also has the advantage of being able to maintain use of indexes.


Many people may suggest a form such as the following, but they do not use indexes:

WHERE
      DATEPART('year',  login_date) = 2014
  AND DATEPART('month', login_date) = 2

This involves calculating the conditions for every single row in the table (a scan) and not using index to find the range of rows that will match (a range-seek).

How to revert to origin's master branch's version of file

If you didn't commit it to the master branch yet, its easy:

  • get off the master branch (like git checkout -b oops/fluke/dang)
  • commit your changes there (like git add -u; git commit;)
  • go back the master branch (like git checkout master)

Your changes will be saved in branch oops/fluke/dang; master will be as it was.

How to change legend title in ggplot

Since you have two densitys I imagine you may be wanting to set your own colours with scale_fill_manual.

If so you can do:

df <- data.frame(x=1:10,group=c(rep("a",5),rep("b",5)))

legend_title <- "OMG My Title"

ggplot(df, aes(x=x, fill=group)) + geom_density(alpha=.3) +   
    scale_fill_manual(legend_title,values=c("orange","red"))

enter image description here

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

What is the path for the startup folder in windows 2008 server

You can easily reach them by using the Run window and entering:

shell:startup

and

shell:common startup

Source.

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

The page cannot be displayed because an internal server error has occurred on server

I've fixed it. I had the following section in web.config :

httpErrors existingResponse="PassThrough"

When I remove it, I got a real error

How do you do a ‘Pause’ with PowerShell 2.0?

I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.

<1> ReadKey (System.Console)

write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Disadvantage: Does not work in PS-ISE.

<2> ReadKey (RawUI)

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Does not exclude modifier keys.

<3> cmd

cmd /c Pause | Out-Null
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Visibly launches new shell/window on first use; not noticeable on subsequent use but still has the overhead

<4> Read-Host

Read-Host -Prompt "Press Enter to continue"
  • Advantage: Works in PS-ISE.
  • Disadvantage: Accepts only Enter key.

<5> ReadKey composite

This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.

Function Pause ($Message = "Press any key to continue . . . ") {
    if ((Test-Path variable:psISE) -and $psISE) {
        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
    }
    else {     
        Write-Host -NoNewline $Message
        [void][System.Console]::ReadKey($true)
        Write-Host
    }
}
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE (though only with Enter or mouse click)
  • Disadvantage: Not a one-liner!

How to set the custom border color of UIView programmatically?

We can create method for it. Simply use it.

public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
    self.layer.borderWidth = width
    self.layer.cornerRadius = radius
    self.layer.shouldRasterize = false
    self.layer.rasterizationScale = 2
    self.clipsToBounds = true
    self.layer.masksToBounds = true
    let cgColor: CGColor = color.cgColor
    self.layer.borderColor = cgColor
}

Show or hide element in React

If you would like to see how to TOGGLE the display of a component checkout this fiddle.

http://jsfiddle.net/mnoster/kb3gN/16387/

var Search = React.createClass({
    getInitialState: function() {
        return { 
            shouldHide:false
        };
    },
    onClick: function() {
        console.log("onclick");
        if(!this.state.shouldHide){
            this.setState({
                shouldHide: true 
            })
        }else{
                    this.setState({
                shouldHide: false 
            })
        }
    },
render: function() {
    return (
      <div>
        <button onClick={this.onClick}>click me</button>
        <p className={this.state.shouldHide ? 'hidden' : ''} >yoyoyoyoyo</p>
      </div>
    );
}
});

ReactDOM.render( <Search /> , document.getElementById('container'));

unix sort descending order

The presence of the n option attached to the -k5 causes the global -r option to be ignored for that field. You have to specify both n and r at the same level (globally or locally).

sort -t $'\t' -k5,5rn

or

sort -rn -t $'\t' -k5,5

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

Reading a text file in MATLAB line by line

If you really want to process your file line by line, a solution might be to use fgetl:

  1. Open the data file with fopen
  2. Read the next line into a character array using fgetl
  3. Retreive the data you need using sscanf on the character array you just read
  4. Perform any relevant test
  5. Output what you want to another file
  6. Back to point 2 if you haven't reached the end of your file.

Unlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.

Hope this will help.

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.6;
  background: rgba(200, 54, 54, 0.5);  
  background-color: yellow;
  filter: alpha(opacity=50);
  zoom: 1;  
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";  
  -moz-opacity: 0.5; 
  -khtml-opacity: 0.5;  
}

jQuery disable a link

you can just hide and show the link as you like

$(link).hide();
$(link).show();

Create Table from JSON Data with angularjs and ng-repeat

You can use $http.get() method to fetch your JSON file. Then assign response data to a $scope object. In HTML to create table use ng-repeat for $scope object. ng-repeat will loop the rows in-side this loop you can bind data to columns dynamically.

I have checked your code and you have created static table

<table>
<tr>
<th>Name</th>
<th>Relationship</th>
</tr>
<tr ng-repeat="indivisual in members">
<td>{{ indivisual.Name }}</td>
<td>{{ indivisual.Relation }}</td>
</tr>
</table>

so better your can go to my code to create dynamic table as per data you column and row will be increase or decrease..

Adb install failure: INSTALL_CANCELED_BY_USER

Turn off Miui Optimizations on Developer Settings, then Restart the phone. it worked for me. Settings > Additional Settings > Developer Options > MIUI Optimization

What is the difference between exit(0) and exit(1) in C?

When the executable ends (exits) it returns a value to the shell that ran it. exit(0) usually indicates that all is well, whilst exit(1) indicates that something has gone amiss.

What is the difference between "INNER JOIN" and "OUTER JOIN"?

1.Inner Join: Also called as Join. It returns the rows present in both the Left table, and right table only if there is a match. Otherwise, it returns zero records.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
INNER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output1

2.Full Outer Join: Also called as Full Join. It returns all the rows present in both the Left table, and right table.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
FULL OUTER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output2

3.Left Outer join: Or simply called as Left Join. It returns all the rows present in the Left table and matching rows from the right table (if any).

4.Right Outer Join: Also called as Right Join. It returns matching rows from the left table (if any), and all the rows present in the Right table.

joins

Advantages of Joins

  1. Executes faster.

Pass multiple complex objects to a post/put Web API method

Basically you can send complex object without doing any extra fancy thing. Or without making changes to Web-Api. I mean why would we have to make changes to Web-Api, while the fault is in our code that's calling the Web-Api.

All you have to do use NewtonSoft's Json library as following.

string jsonObjectA = JsonConvert.SerializeObject(objectA);
string jsonObjectB = JsonConvert.SerializeObject(objectB);
string jSoNToPost = string.Format("\"content\": {0},\"config\":\"{1}\"",jsonObjectA , jsonObjectB );
//wrap it around in object container notation
jSoNToPost = string.Concat("{", jSoNToPost , "}"); 
//convert it to JSON acceptible content
HttpContent content = new StringContent(jSoNToPost , Encoding.UTF8, "application/json"); 

var response = httpClient.PutAsync("api/process/StartProcessiong", content);

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

How to read a file in reverse order?

with open("filename") as f:

    print(f.read()[::-1])

"The import org.springframework cannot be resolved."

Add the following JPA dependency.

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try this

<script>
    $().ready(function(){
        $('.coupon_question').live('click',function() 
        {
            if ($('.coupon_question').is(':checked')) {
                $(".answer").show();
            } else {
                $(".answer").hide();
            } 
        });
    });
</script>

How to make Java honor the DNS Caching Timeout?

To summarize the other answers, in <jre-path>/lib/security/java.security you can set the value of the property networkaddress.cache.ttl to adjust how DNS lookups are cached. Note that this is not a system property but a security property. I was able to set this using:

java.security.Security.setProperty("networkaddress.cache.ttl", "<value>");

This can also be set by the system property -Dsun.net.inetaddr.ttl though this will not override a security property if it is set elsewhere.

I would also like to add that if you are seeing this issue with web services in WebSphere, as I was, setting networkaddress.cache.ttl will not be enough. You need to set the system property disableWSAddressCaching to true. Unlike the time-to-live property, this can be set as a JVM argument or via System.setProperty).

IBM has a pretty detailed post on how WebSphere handles DNS caching here. The relevant piece to the above is:

To disable address caching for Web services, you need to set an additional JVM custom property disableWSAddressCaching to true. Use this property to disable address caching for Web services. If your system typically runs with lots of client threads, and you encounter lock contention on the wsAddrCache cache, you can set this custom property to true, to prevent caching of the Web services data.

Uncaught ReferenceError: React is not defined

If you are using Webpack, you can have it load React when needed without having to explicitly require it in your code.

Add to webpack.config.js:

plugins: [
   new webpack.ProvidePlugin({
      "React": "react",
   }),
],

See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

How to rename a table in SQL Server?

Table Name

sp_rename 'db_name.old_table_name', 'new_table_name'

Column

sp_rename 'db_name.old_table_name.name' 'userName', 'COLUMN'

Index

sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'

also available for statics and datatypes

SQL Server add auto increment primary key to existing table

Create a new Table With Different name and same columns, Primary Key and Foreign Key association and link this in your Insert statement of code. For E.g : For EMPLOYEE, replace with EMPLOYEES.

CREATE TABLE EMPLOYEES(

    EmpId        INT NOT NULL IDENTITY(1,1), 
    F_Name       VARCHAR(20) ,
    L_Name       VARCHAR(20) ,
    DOB          DATE ,
    DOJ          DATE ,
    PRIMARY KEY (EmpId),
    DeptId int FOREIGN KEY REFERENCES DEPARTMENT(DeptId),
    DesgId int FOREIGN KEY REFERENCES DESIGNATION(DesgId),
    AddId int FOREIGN KEY REFERENCES ADDRESS(AddId)   
) 

However, you have to either delete the existing EMPLOYEE Table or do some adjustment according to your requirement.

How do I install chkconfig on Ubuntu?

alias chkconfig=sysv-rc-conf
chkconfig --list

syntax

sysv-rc-conf command line usage:  

        sysv-rc-conf --list [service name]
        sysv-rc-conf [--level <runlevels>] <service name> <on|off>

Change bundle identifier in Xcode when submitting my first app in IOS

A very simple solution to that is to open the file:

YOURPROJECT.xcodeproj/project.pbxproj

And find for this variable:

PRODUCT_BUNDLE_IDENTIFIER

You'll see something like that:

PRODUCT_BUNDLE_IDENTIFIER = com.YOUR_APP_NAME.SOMETHING;

So, the name on the right is your Bundle Identifier. In my case it works perfectly.

conversion from string to json object android

try this:

String json = "{'phonetype':'N95','cat':'WP'}";

What is "X-Content-Type-Options=nosniff"?

For Microsoft IIS servers, you can enable this header via your web.config file:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Content-Type-Options"/>
        <add name="X-Content-Type-Options" value="nosniff"/>
      </customHeaders>
    </httpProtocol>
</system.webServer>

And you are done.

Extract a substring from a string in Ruby using a regular expression

You can use a regular expression for that pretty easily…

Allowing spaces around the word (but not keeping them):

str.match(/< ?([^>]+) ?>\Z/)[1]

Or without the spaces allowed:

str.match(/<([^>]+)>\Z/)[1]

printing a two dimensional array in python

using indices, for loops and formatting:

import numpy as np

def printMatrix(a):
   print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%6.f" %a[i,j],
      print
   print      


def printMatrixE(a):
   print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print("%6.3f" %a[i,j]),
      print
   print      


inf = float('inf')
A = np.array( [[0,1.,4.,inf,3],
     [1,0,2,inf,4],
     [4,2,0,1,5],
     [inf,inf,1,0,3],
     [3,4,5,3,0]])

printMatrix(A)    
printMatrixE(A)    

which yields the output:

Matrix[5][5]
     0      1      4    inf      3
     1      0      2    inf      4
     4      2      0      1      5
   inf    inf      1      0      3
     3      4      5      3      0

Matrix[5][5]
 0.000  1.000  4.000    inf  3.000
 1.000  0.000  2.000    inf  4.000
 4.000  2.000  0.000  1.000  5.000
   inf    inf  1.000  0.000  3.000
 3.000  4.000  5.000  3.000  0.000

Bootstrap Dropdown with Hover

The easiest solution would be in CSS. Add something like...

.dropdown:hover .dropdown-menu {
    display: block;
    margin-top: 0; // remove the gap so it doesn't close
 }

Working Fiddle

How can I ssh directly to a particular directory?

I use the environment variable CDPATH

How to remove gem from Ruby on Rails application?

For Rails 4 - remove the gem name from Gemfile and then run bundle install in your terminal. Also restart the server afterwards.

Eclipse - "Workspace in use or cannot be created, chose a different one."

Running eclipse in Administrator Mode fixed it for me. You can do this by [Right Click] -> Run as Administrator on the eclipse.exe from your install dir.

I was on a working environment with win7 machine having restrictive permission. I also did remove the .lock and .log files but that did not help. It can be a combination of all as well that made it work.

How do I set a value in CKEditor with Javascript?

Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page

How to use DISTINCT and ORDER BY in same SELECT statement?

It can be done using inner query Like this

$query = "SELECT * 
            FROM (SELECT Category  
                FROM currency_rates                 
                ORDER BY id DESC) as rows               
            GROUP BY currency";

Global javascript variable inside document.ready

You can define the variable inside the document ready function without var to make it a global variable. In javascript any variable declared without var automatically becomes a global variable

$(document).ready(function() {
    intro =  "something";
});

although you cant use the variable immediately, but it would be accessible to other functions

How can I list (ls) the 5 last modified files in a directory?

ls -t list files by creation time not last modified time. Use ls -ltc if you want to list files by last modified time from last to first(top to bottom). Thus to list the last n: ls -ltc | head ${n}

How to define an empty object in PHP

You can use new stdClass() (which is recommended):

$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);

// outputs:
// stdClass Object ( [name] => John ) 

Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:

$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);

// outputs: 
// stdClass Object ( [name] => John )  

Or you can convert the null value to an object which produces a new empty instance of the stdClass built-in class:

$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);

// outputs:
// stdClass Object ( [name] => John ) 

Media query to detect if device is touchscreen

This will work. If it doesn't let me know

@media (hover: none) and (pointer: coarse) {
    /* Touch screen device style goes here */
}

edit: hover on-demand is not supported anymore

Java: how to use UrlConnection to post request with authorization?

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.

Below is the code to do that,

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", encodedCredentials);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new 
                                     InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

Change URLConnection to HttpURLConnection, to make it POST request.

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

Suggestion (...in comments):

You might need to set these properties too,

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );

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

In my case, the error was because I had not declared the field in my $fillable array in the model. Well, it seems to be something basic, but for us who started with laravel it could work.

How do I open an .exe from another C++ .exe?

Try this:

#include <windows.h>

int main ()

{
    system ("start notepad.exe") // As an example. Change [notepad] to any executable file //

    return 0 ;
}

Keyboard shortcut to clear cell output in Jupyter notebook

Just adding in for JupyterLab users. Ctrl, (advanced settings) and pasting the below in User References under keyboard shortcuts does the trick for me.

{
"shortcuts": [
        {
            "command": "notebook:hide-cell-outputs",
            "keys": [
                "H"
            ],
            "selector": ".jp-Notebook:focus"
        },
        {
            "command": "notebook:show-cell-outputs",
            "keys": [
                "Shift H"
            ],
            "selector": ".jp-Notebook:focus"
        }
    ]
}

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

The best way to use https and avoid security issues is to use Firefox (or another tool) and download the certificate to your server. This webpage helped me a lot, and these were the steps that worked for me:

1) Open in Firefox the URL you're gonna use with CURL

2) On the address bar click on the padlock > more information (FF versions can have different menus, just find it). Click the View certificate button > Details tab.

3) Highlight the "right" certificate in Certificate hierarchy. In my case it was the second of three, called "cPanel, Inc. Certification Authority". I just discovered the right one by "trial and error" method.

4) Click the Export button. In my case the one who worked was the file type "PEM with chains" (again by trial and error method).

5) Then in your PHP script add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);    
curl_setopt($ch, CURLOPT_CAINFO, [PATH_TO_CRT_FILE]);

In addition I'd say that we must pay attention on the fact that these steps will probably need to be redone once a year or whenever the URL certificate is replaced or renewed.

How to check whether a string is a valid HTTP URL?

After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s).

Remove by _id in MongoDB console

Well, the _id is an object in your example, so you just need to pass an object

'db.test_users.remove({"_id": { "$oid" : "4d513345cc9374271b02ec6c" }})'

This should work

Edit: Added trailing paren to ensure that it compiled.

How to set Spinner default value to null?

you can put the first cell in your array to be empty({"","some","some",...}) and do nothing if the position is 0;

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position>0) {
        label.setText(MainActivity.questions[position - 1]);
    }
}
  • if you fill the array by xml file you can let the first item empty

Error in finding last used cell in Excel with VBA

Since the original question is about problems with finding the last cell, in this answer I will list the various ways you can get unexpected results; see my answer to "How can I find last row that contains data in the Excel sheet with a macro?" for my take on solving this.

I'll start by expanding on the answer by sancho.s and the comment by GlennFromIowa, adding even more detail:

[...] one has first to decide what is considered used. I see at least 6 meanings. Cell has:

  • 1) data, i.e., a formula, possibly resulting in a blank value;
  • 2) a value, i.e., a non-blank formula or constant;
  • 3) formatting;
  • 4) conditional formatting;
  • 5) a shape (including Comment) overlapping the cell;
  • 6) involvement in a Table (List Object).

Which combination do you want to test for? Some (such as Tables) may be more difficult to test for, and some may be rare (such as a shape outside of data range), but others may vary based on the situation (e.g., formulas with blank values).

Other things you might want to consider:

  • A) Can there be hidden rows (e.g. autofilter), blank cells or blank rows?
  • B) What kind of performance is acceptable?
  • C) Can the VBA macro affect the workbook or the application settings in any way?

With that in mind, let's see how the common ways of getting the "last cell" can produce unexpected results:

  • The .End(xlDown) code from the question will break most easily (e.g. with a single non-empty cell or when there are blank cells in between) for the reasons explained in the answer by Siddharth Rout here (search for "xlDown is equally unreliable.")
  • Any solution based on Counting (CountA or Cells*.Count) or .CurrentRegion will also break in presence of blank cells or rows
  • A solution involving .End(xlUp) to search backwards from the end of a column will, just as CTRL+UP, look for data (formulas producing a blank value are considered "data") in visible rows (so using it with autofilter enabled might produce incorrect results ??).

    You have to take care to avoid the standard pitfalls (for details I'll again refer to the answer by Siddharth Rout here, look for the "Find Last Row in a Column" section), such as hard-coding the last row (Range("A65536").End(xlUp)) instead of relying on sht.Rows.Count.

  • .SpecialCells(xlLastCell) is equivalent to CTRL+END, returning the bottom-most and right-most cell of the "used range", so all caveats that apply to relying on the "used range", apply to this method as well. In addition, the "used range" is only reset when saving the workbook and when accessing worksheet.UsedRange, so xlLastCell might produce stale results?? with unsaved modifications (e.g. after some rows were deleted). See the nearby answer by dotNET.
  • sht.UsedRange (described in detail in the answer by sancho.s here) considers both data and formatting (though not conditional formatting) and resets the "used range" of the worksheet, which may or may not be what you want.

    Note that a common mistake ?is to use .UsedRange.Rows.Count??, which returns the number of rows in the used range, not the last row number (they will be different if the first few rows are blank), for details see newguy's answer to How can I find last row that contains data in the Excel sheet with a macro?

  • .Find allows you to find the last row with any data (including formulas) or a non-blank value in any column. You can choose whether you're interested in formulas or values, but the catch is that it resets the defaults in the Excel's Find dialog ????, which can be highly confusing to your users. It also needs to be used carefully, see the answer by Siddharth Rout here (section "Find Last Row in a Sheet")
  • More explicit solutions that check individual Cells' in a loop are generally slower than re-using an Excel function (although can still be performant), but let you specify exactly what you want to find. See my solution based on UsedRange and VBA arrays to find the last cell with data in the given column -- it handles hidden rows, filters, blanks, does not modify the Find defaults and is quite performant.

Whatever solution you pick, be careful

  • to use Long instead of Integer to store the row numbers (to avoid getting Overflow with more than 65k rows) and
  • to always specify the worksheet you're working with (i.e. Dim ws As Worksheet ... ws.Range(...) instead of Range(...))
  • when using .Value (which is a Variant) avoid implicit casts like .Value <> "" as they will fail if the cell contains an error value.

How to check for registry value using VbScript

This should work for you:

Dim oShell
Dim iValue

Set oShell = CreateObject("WScript.Shell")

iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")

How do I install Eclipse Marketplace in Eclipse Classic?

The easy way to do it

  1. Help--> Install New Software
  2. In the box type in http://download.eclipse.org/mpc/juno

  3. General Purpose Tools--> Select Eclipse Marketplace checkbox and Finish.

Along with these steps I tried To install the whole bunch of software, but it gives an error later. So please make sure you select only one or two at a time.

IndexError: list index out of range and python

Yes,

You are trying to access an element of the list that does not exist.

MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.

Have you got an off-by-one error?

iOS 7 status bar back to iOS 6 default style in iPhone app?

This might be too late to share, but I have something to contribute which might help someone, I was trying to sub-class the UINavigationBar and wanted to make it look like ios 6 with black status bar and status bar text in white.

Here is what I found working for that

        self.navigationController?.navigationBar.clipsToBounds = true
        self.navigationController?.navigationBar.translucent = false
        self.navigationController?.navigationBar.barStyle = .Black
        self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

It made my status bar background black, status bar text white and navigation bar's color white.

iOS 9.3, XCode 7.3.1

Windows- Pyinstaller Error "failed to execute script " When App Clicked

In case anyone doesn't get results from the other answers, I fixed a similar problem by:

  1. adding --hidden-import flags as needed for any missing modules

  2. cleaning up the associated folders and spec files:

rmdir /s /q dist

rmdir /s /q build

del /s /q my_service.spec

  1. Running the commands for installation as Administrator

What is the difference between .*? and .* regular expressions?

It is the difference between greedy and non-greedy quantifiers.

Consider the input 101000000000100.

Using 1.*1, * is greedy - it will match all the way to the end, and then backtrack until it can match 1, leaving you with 1010000000001.
.*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1, eventually matching 101.

All quantifiers have a non-greedy mode: .*?, .+?, .{2,6}?, and even .??.

In your case, a similar pattern could be <([^>]*)> - matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than > in-between < and >).

See Quantifier Cheat Sheet.

Unordered List (<ul>) default indent

I'll tackle your second question first. Yes, the indentation can be reset by using a browser reset like Eric Meyers. Or a simple ul { margin: 0; padding: 0;} as indentation is, by default, enforced on the ul element.

As to the why, I suspect its to do with the current level of nesting, as unordered lists allow for nesting or maybe to do with the bullets positioning.

Edit: As Guffa mentioned, the list indentation is to ensure that the markers do not fall off the left edge.

how to open a url in python

Here is another way to do it.

import webbrowser

webbrowser.open("foobar.com")

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

This works for me:

C:\xampp\phpMyAdmin\config.inc.php

$cfg['Servers'][$i]['password'] = 'secret';

Edit: Before you got this error it is most likely that from phpmyadmin->Users you have added password for the root user. In my case that was "secret" so the above primer works for me BUT for you will work this:

$cfg['Servers'][$i]['password'] = 'Enter the password for root you have added before you got this error';