Programs & Examples On #Linq to sql

LINQ to SQL is a component of .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects stored in Microsoft SQL Server.

How to do Select All(*) in linq to sql

u want select all data from database then u can try this:-

dbclassDataContext dc= new dbclassDataContext()
List<tableName> ObjectName= dc.tableName.ToList();

otherwise You can try this:-

var Registration = from reg in dcdc.GetTable<registration>() select reg;

and method Syntex :-

 var Registration = dc.registration.Select(reg => reg); 

Difference Between Select and SelectMany

Some SelectMany may not be necessary. Below 2 queries give the same result.

Customers.Where(c=>c.Name=="Tom").SelectMany(c=>c.Orders)

Orders.Where(o=>o.Customer.Name=="Tom")

For 1-to-Many relationship,

  1. if Start from "1", SelectMany is needed, it flattens the many.
  2. if Start from "Many", SelectMany is not needed. (still be able to filter from "1", also this is simpler than below standard join query)

from o in Orders
join c in Customers on o.CustomerID equals c.ID
where c.Name == "Tom"
select o

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

Joining on multiple columns in Linq to SQL is a little different.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { t1.ColumnA, t1.ColumnB } equals new { t2.ColumnA, t2.ColumnB }
    ...

You have to take advantage of anonymous types and compose a type for the multiple columns you wish to compare against.

This seems confusing at first but once you get acquainted with the way the SQL is composed from the expressions it will make a lot more sense, under the covers this will generate the type of join you are looking for.

EDIT Adding example for second join based on comment.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { A = t1.ColumnA, B = t1.ColumnB } equals new { A = t2.ColumnA, B = t2.ColumnB }
    join t3 in myTABLE1List
      on new { A = t2.ColumnA, B =  t2.ColumnB } equals new { A = t3.ColumnA, B = t3.ColumnB }
    ...

Linq to SQL how to do "where [column] in (list of values)"

 var filterTransNos = (from so in db.SalesOrderDetails
                    where  ItemDescription.Contains(ItemDescription)
                            select new { so.TransNo }).AsEnumerable();    


listreceipt = listreceipt.Where(p => filterTransNos.Any(p2 => p2.TransNo == p.TransNo)).ToList();

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

In my case this error was raised because table date column is not null-able

As below:

Create Table #TempTable(
 ...
 ApprovalDate datatime not null.
 ...)

To avoid this error just make it null-able

 Create Table #TempTable(
 ...
 ApprovalDate datatime null.
 ...)

How do I update a Linq to SQL dbml file?

There is a nuance to updating tables then updating the DBML... Foreign key relationships are not immediately always brought over if changes are made to existing tables. The work around is to do a build of the project and then re-add the tables again. I reported this to MS and its being fixed for VS2010.

DBML display does not show new foreign key constraints


Note that the instructions given in the main answer are not clear. To update the table

  1. Open up the dbml design surface
  2. Select all tables with Right->Click->Select All or CTRLa
  3. CTRLx (Cut)
  4. CTRLv (Paste)
  5. Save and rebuild solution.

How do you perform a left outer join using linq extension methods

For a (left outer) join of a table Bar with a table Foo on Foo.Foo_Id = Bar.Foo_Id in lambda notation:

var qry = Foo.GroupJoin(
          Bar, 
          foo => foo.Foo_Id,
          bar => bar.Foo_Id,
          (x,y) => new { Foo = x, Bars = y })
       .SelectMany(
           x => x.Bars.DefaultIfEmpty(),
           (x,y) => new { Foo=x.Foo, Bar=y});

Can I return the 'id' field after a LINQ insert?

After you commit your object into the db the object receives a value in its ID field.

So:

myObject.Field1 = "value";

// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();

// You can retrieve the id from the object
int id = myObject.ID;

LINQ syntax where string value is not null or empty

This won't fail on Linq2Objects, but it will fail for Linq2SQL, so I am assuming that you are talking about the SQL provider or something similar.

The reason has to do with the way that the SQL provider handles your lambda expression. It doesn't take it as a function Func<P,T>, but an expression Expression<Func<P,T>>. It takes that expression tree and translates it so an actual SQL statement, which it sends off to the server.

The translator knows how to handle basic operators, but it doesn't know how to handle methods on objects. It doesn't know that IsNullOrEmpty(x) translates to return x == null || x == string.empty. That has to be done explicitly for the translation to SQL to take place.

Linq to SQL .Sum() without group ... into

you can:

itemsCart.Select(c=>c.Price).Sum();

To hit the db only once do:

var itemsInCart = (from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                  ).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();

The extra round-trip saved is worth it :)

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.

Returning IEnumerable<T> vs. IQueryable<T>

A lot has been said previously, but back to the roots, in a more technical way:

  1. IEnumerable is a collection of objects in memory that you can enumerate - an in-memory sequence that makes it possible to iterate through (makes it way easy for within foreach loop, though you can go with IEnumerator only). They reside in the memory as is.
  2. IQueryable is an expression tree that will get translated into something else at some point with ability to enumerate over the final outcome. I guess this is what confuses most people.

They obviously have different connotations.

IQueryable represents an expression tree (a query, simply) that will be translated to something else by the underlying query provider as soon as release APIs are called, like LINQ aggregate functions (Sum, Count, etc.) or ToList[Array, Dictionary,...]. And IQueryable objects also implement IEnumerable, IEnumerable<T> so that if they represent a query the result of that query could be iterated. It means IQueryable don't have to be queries only. The right term is they are expression trees.

Now how those expressions are executed and what they turn to is all up to so called query providers (expression executors we can think them of).

In the Entity Framework world (which is that mystical underlying data source provider, or the query provider) IQueryable expressions are translated into native T-SQL queries. Nhibernate does similar things with them. You can write your own one following the concepts pretty well described in LINQ: Building an IQueryable Provider link, for example, and you might want to have a custom querying API for your product store provider service.

So basically, IQueryable objects are getting constructed all the way long until we explicitly release them and tell the system to rewrite them into SQL or whatever and send down the execution chain for onward processing.

As if to deferred execution it's a LINQ feature to hold up the expression tree scheme in the memory and send it into the execution only on demand, whenever certain APIs are called against the sequence (the same Count, ToList, etc.).

The proper usage of both heavily depends on the tasks you're facing for the specific case. For the well-known repository pattern I personally opt for returning IList, that is IEnumerable over Lists (indexers and the like). So it is my advice to use IQueryable only within repositories and IEnumerable anywhere else in the code. Not saying about the testability concerns that IQueryable breaks down and ruins the separation of concerns principle. If you return an expression from within repositories consumers may play with the persistence layer as they would wish.

A little addition to the mess :) (from a discussion in the comments)) None of them are objects in memory since they're not real types per se, they're markers of a type - if you want to go that deep. But it makes sense (and that's why even MSDN put it this way) to think of IEnumerables as in-memory collections whereas IQueryables as expression trees. The point is that the IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. So, in fact, you can't really call any IEnumerable member without having the object in the memory. It will get in there if you do, anyways, if it's not empty. IQueryables are just queries, not the data.

efficient way to implement paging

Trying to give you a brief answer to your doubt, if you execute the skip(n).take(m) methods on linq (with SQL 2005 / 2008 as database server) your query will be using the Select ROW_NUMBER() Over ... statement, with is somehow direct paging in the SQL engine.

Giving you an example, I have a db table called mtcity and I wrote the following query (work as well with linq to entities):

using (DataClasses1DataContext c = new DataClasses1DataContext())
{
    var query = (from MtCity2 c1 in c.MtCity2s
                select c1).Skip(3).Take(3);
    //Doing something with the query.
}

The resulting query will be:

SELECT [t1].[CodCity], 
    [t1].[CodCountry], 
    [t1].[CodRegion], 
    [t1].[Name],  
    [t1].[Code]
FROM (
    SELECT ROW_NUMBER() OVER (
        ORDER BY [t0].[CodCity], 
        [t0].[CodCountry], 
        [t0].[CodRegion], 
        [t0].[Name],
        [t0].[Code]) AS [ROW_NUMBER], 
        [t0].[CodCity], 
        [t0].[CodCountry], 
        [t0].[CodRegion], 
        [t0].[Name],
        [t0].[Code]
    FROM [dbo].[MtCity] AS [t0]
    ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]

Which is a windowed data access (pretty cool, btw cuz will be returning data since the very begining and will access the table as long as the conditions are met). This will be very similar to:

With CityEntities As 
(
    Select ROW_NUMBER() Over (Order By CodCity) As Row,
        CodCity //here is only accessed by the Index as CodCity is the primary
    From dbo.mtcity
)
Select [t0].[CodCity], 
        [t0].[CodCountry], 
        [t0].[CodRegion], 
        [t0].[Name],
        [t0].[Code]
From CityEntities c
Inner Join dbo.MtCity t0 on c.CodCity = t0.CodCity
Where c.Row Between @p0 + 1 AND @p0 + @p1
Order By c.Row Asc

With the exception that, this second query will be executed faster than the linq result because it will be using exclusively the index to create the data access window; this means, if you need some filtering, the filtering should be (or must be) in the Entity listing (where the row is created) and some indexes should be created as well to keep up the good performance.

Now, whats better?

If you have pretty much solid workflow in your logic, implementing the proper SQL way will be complicated. In that case LINQ will be the solution.

If you can lower that part of the logic directly to SQL (in a stored procedure), it will be even better because you can implement the second query I showed you (using indexes) and allow SQL to generate and store the Execution Plan of the query (improving performance).

Linq to Sql: Multiple left outer joins

Don't have access to VisualStudio (I'm on my Mac), but using the information from http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx it looks like you may be able to do something like this:

var query = from o in dc.Orders
            join v in dc.Vendors on o.VendorId equals v.Id into ov
            from x in ov.DefaultIfEmpty()
            join s in dc.Status on o.StatusId equals s.Id into os
            from y in os.DefaultIfEmpty()
            select new { o.OrderNumber, x.VendorName, y.StatusName }

How to select only the records with the highest date in LINQ

If you just want the last date for each account, you'd use this:

var q = from n in table
        group n by n.AccountId into g
        select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};

If you want the whole record:

var q = from n in table
        group n by n.AccountId into g
        select g.OrderByDescending(t=>t.Date).FirstOrDefault();

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

In your last example:

var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or doesn't matter?

Yes it does. If you try to use SingleOrDefault() and the query results in more than record you would get and exception. The only time you can safely use SingleOrDefault() is when you are expecting only 1 and only 1 result...

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

LINQ-to-SQL is a remarkable piece of technology that is very simple to use, and by and large generates very good queries to the back end. LINQ-to-EF was slated to supplant it, but historically has been extremely clunky to use and generated far inferior SQL. I don't know the current state of affairs, but Microsoft promised to migrate all the goodness of L2S into L2EF, so maybe it's all better now.

Personally, I have a passionate dislike of ORM tools (see my diatribe here for the details), and so I see no reason to favour L2EF, since L2S gives me all I ever expect to need from a data access layer. In fact, I even think that L2S features such as hand-crafted mappings and inheritance modeling add completely unnecessary complexity. But that's just me. ;-)

LINQ to SQL Left Outer Join

I'd like to add one more thing. In LINQ to SQL if your DB is properly built and your tables are related through foreign key constraints, then you do not need to do a join at all.

Using LINQPad I created the following LINQ query:

//Querying from both the CustomerInfo table and OrderInfo table
from cust in CustomerInfo
where cust.CustomerID == 123456
select new {cust, cust.OrderInfo}

Which was translated to the (slightly truncated) query below

 -- Region Parameters
 DECLARE @p0 Int = 123456
-- EndRegion
SELECT [t0].[CustomerID], [t0].[AlternateCustomerID],  [t1].[OrderID], [t1].[OnlineOrderID], (
    SELECT COUNT(*)
    FROM [OrderInfo] AS [t2]
    WHERE [t2].[CustomerID] = [t0].[CustomerID]
    ) AS [value]
FROM [CustomerInfo] AS [t0]
LEFT OUTER JOIN [OrderInfo] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE [t0].[CustomerID] = @p0
ORDER BY [t0].[CustomerID], [t1].[OrderID]

Notice the LEFT OUTER JOIN above.

LINQ to SQL - How to select specific columns and return strongly typed list

Make a call to the DB searching with myid (Id of the row) and get back specific columns:

var columns = db.Notifications
                .Where(x => x.Id == myid)
                .Select(n => new { n.NotificationTitle, 
                                   n.NotificationDescription, 
                                   n.NotificationOrder });

Update using LINQ to SQL

I found a workaround a week ago. You can use direct commands with "ExecuteCommand":

MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
                   where f.Code == Code
                   select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
    dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}

In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.

value = 0 --> 0 is the new value for the record;

code = {0} --> is the field where you will send the filter value;

Code --> is the new value for the field;

I hope this reference helps.

Entity Framework vs LINQ to SQL

I think if you need to develop something quick with no Strange things in the middle, and you need the facility to have entities representing your tables:

Linq2Sql can be a good allied, using it with LinQ unleashes a great developing timing.

Multiple WHERE clause in Linq

Also, you can use bool method(s)

Query :

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where isValid(Field<string>("UserName"))// && otherMethod() && otherMethod2()                           
            select r;   

        DataTable newDT = query.CopyToDataTable();

Method:

bool isValid(string userName)
{
    if(userName == "XXXX" || userName == "YYYY")
        return false;
    else return true;
}

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Taking data of DataBase without sorting is the same as random take

How to Select Min and Max date values in Linq Query

dim mydate = from cv in mydata.t1s
  select cv.date1 asc

datetime mindata = mydate[0];

LINQ Where with AND OR condition

from item in db.vw_Dropship_OrderItems
    where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
    (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
    select item;

Might give strange behavior if both listMerchants and listStatus are both null.

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

This is how you do a distinct count query. Note that you have to filter out the nulls.

var useranswercount = (from a in tpoll_answer
where user_nbr != null && answer_nbr != null
select user_nbr).Distinct().Count();

If you combine this with into your current grouping code, I think you'll have your solution.

LINQ - Left Join, Group By, and Count

While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.

Here's my solution:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }

Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)

Max or Default?

Think about what you're asking!

The max of {1, 2, 3, -1, -2, -3} is obviously 3. The max of {2} is obviously 2. But what is the max of the empty set { }? Obviously that is a meaningless question. The max of the empty set is simply not defined. Attempting to get an answer is a mathematical error. The max of any set must itself be an element in that set. The empty set has no elements, so claiming that some particular number is the max of that set without being in that set is a mathematical contradiction.

Just as it is correct behavior for the computer to throw an exception when the programmer asks it to divide by zero, so it is correct behavior for the computer to throw an exception when the programmer asks it to take the max of the empty set. Division by zero, taking the max of the empty set, wiggering the spacklerorke, and riding the flying unicorn to Neverland are all meaningless, impossible, undefined.

Now, what is it that you actually want to do?

Convert Linq Query Result to Dictionary

Try using the ToDictionary method like so:

var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

LINQ to SQL - Left Outer Join with multiple join conditions

Can be written using composite join key. Also if there is need to select properties from both left and right sides the LINQ can be written as

var result = context.Periods
    .Where(p => p.companyid == 100)
    .GroupJoin(
        context.Facts,
        p => new {p.id, otherid = 17},
        f => new {id = f.periodid, f.otherid},
        (p, f) => new {p, f})
    .SelectMany(
        pf => pf.f.DefaultIfEmpty(),
        (pf, f) => new MyJoinEntity
        {
            Id = pf.p.id,
            Value = f.value,
            // and so on...
        });

If Else in LINQ

you should change like this:

private string getValue(float price)
{
    if(price >0)
        return "debit";
    return "credit";
}

//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};

Return anonymous type results?

In C# 7 you can now use tuples!... which eliminates the need to create a class just to return the result.

Here is a sample code:

public List<(string Name, string BreedName)> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
             join b in db.Breeds on d.BreedId equals b.BreedId
             select new
             {
                Name = d.Name,
                BreedName = b.BreedName
             }.ToList();

    return result.Select(r => (r.Name, r.BreedName)).ToList();
}

You might need to install System.ValueTuple nuget package though.

LINQ-to-SQL vs stored procedures?

I am generally a proponent of putting everything in stored procedures, for all of the reasons DBAs have been harping on for years. In the case of Linq, it is true that there will be no performance difference with simple CRUD queries.

But keep a few things in mind when making this decision: using any ORM couples you tightly to your data model. A DBA has no freedom to make changes to the data model without forcing you to change your compiled code. With stored procedures, you can hide these sorts of changes to an extent, since the parameter list and results set(s) returned from a procedure represent its contract, and the innards can be changed around, just so long as that contract is still met.

And also, if Linq is used for more complex queries, tuning the database becomes a much more difficult task. When a stored procedure is running slow, the DBA can totally focus on the code in isolation, and has lots of options, just so that contract is still satisfied when he/she is done.

I have seen many, many cases where serious problems in an application were addressed by changes to the schema and code in stored procedures without any change to deployed, compiled code.

Perhaps a hybird approach would be nice with Linq? Linq can, of course, be used to call stored procedures.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

I had the same error. The cause was that I had created a table with wrong schema(it ought to be [dbo]). I did the following steps:

  1. I dropped all tables which does not have a prefix "dbo."

  2. I created and run this query:

CREATE TABLE dbo.Cars(IDCar int PRIMARY KEY NOT NULL,Name varchar(25) NOT NULL,    
CarDescription text NULL)
GO

What is the syntax for an inner join in LINQ to SQL?

Use LINQ joins to perform Inner Join.

var employeeInfo = from emp in db.Employees
                   join dept in db.Departments
                   on emp.Eid equals dept.Eid 
                   select new
                   {
                    emp.Ename,
                    dept.Dname,
                    emp.Elocation
                   };

How to store a list in a column of a database table

Many SQL databases allow a table to contain a subtable as a component. The usual method is to allow the domain of one of the columns to be a table. This is in addition to using some convention like CSV to encode the substructure in ways unknown to the DBMS.

When Ed Codd was developing the relational model in 1969-1970, he specifically defined a normal form that would disallow this kind of nesting of tables. Normal form was later called First Normal Form. He then went on to show that for every database, there is a database in first normal form that expresses the same information.

Why bother with this? Well, databases in first normal form permit keyed access to all data. If you provide a table name, a key value into that table, and a column name, the database will contain at most one cell containing one item of data.

If you allow a cell to contain a list or a table or any other collection, now you can't provide keyed access to the sub items, without completely reworking the idea of a key.

Keyed access to all data is fundamental to the relational model. Without this concept, the model isn't relational. As to why the relational model is a good idea, and what might be the limitations of that good idea, you have to look at the 50 years worth of accumulated experience with the relational model.

Understanding SQL Server LOCKS on SELECT queries

A SELECT in SQL Server will place a shared lock on a table row - and a second SELECT would also require a shared lock, and those are compatible with one another.

So no - one SELECT cannot block another SELECT.

What the WITH (NOLOCK) query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.

Without that query hint, a SELECT might be blocked reading a table by an ongoing INSERT (or UPDATE) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).

Problem of the WITH (NOLOCK) hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.

There's another query hint that might be useful - WITH (READPAST). This instructs the SELECT command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

If you're using Entity Framework < v6.0, then use EntityFunctions.TruncateTime If you're using Entity Framework >= v6.0, then use DbFunctions.TruncateTime

Use either (based on your EF version) around any DateTime class property you want to use inside your Linq query

Example

var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate) 
                                       >= DbFunctions.TruncateTime(DateTime.UtcNow));

How to do a LIKE query with linq?

You could use SqlMethods.Like(matchExpression,pattern)

var results = from c in db.costumers
              where SqlMethods.Like(c.FullName, "%"+FirstName+"%,"+LastName)
              select c;

The use of this method outside of LINQ to SQL will always throw a NotSupportedException exception.

how to update the multiple rows at a time using linq to sql?

This is what I did:

EF:

using (var context = new SomeDBContext())
{
    foreach (var item in model.ShopItems)  // ShopItems is a posted list with values 
    {    
        var feature = context.Shop
                             .Where(h => h.ShopID == 123 && h.Type == item.Type).ToList();

        feature.ForEach(a => a.SortOrder = item.SortOrder);
    }

    context.SaveChanges();
}

Hope helps someone.

How do I get the MAX row with a GROUP BY in LINQ query?

This can be done using GroupBy and SelectMany in LINQ lamda expression

var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));

How to do a subquery in LINQ?

Here's a subquery for you!

List<int> IdsToFind = new List<int>() {2, 3, 4};

db.Users
.Where(u => SqlMethods.Like(u.LastName, "%fra%"))
.Where(u =>
    db.CompanyRolesToUsers
    .Where(crtu => IdsToFind.Contains(crtu.CompanyRoleId))
    .Select(crtu =>  crtu.UserId)
    .Contains(u.Id)
)

Regarding this portion of the question:

predicateAnd = predicateAnd.And(c => c.LastName.Contains(
                                TextBoxLastName.Text.Trim()));

I strongly recommend extracting the string from the textbox before authoring the query.

string searchString = TextBoxLastName.Text.Trim();
predicateAnd = predicateAnd.And(c => c.LastName.Contains( searchString));

You want to maintain good control over what gets sent to the database. In the original code, one possible reading is that an untrimmed string gets sent into the database for trimming - which is not good work for the database to be doing.

How can I iterate through a string and also know the index (current position)?

Since std::distance is only constant time for random-access iterators, I would probably prefer explicit iterator arithmetic. Also, since we're writing C++ code here, I do believe a more C++ idiomatic solution is preferable over a C-style approach.

string str{"Test string"};
auto begin = str.begin();

for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
    cout << it - begin << *it;
}

How do I pass multiple ints into a vector at once?

These days (c++17) it's easy:

auto const pusher([](auto& v) noexcept
  {
    return [&](auto&& ...e)
      {
        (
          (
            v.push_back(std::forward<decltype(e)>(e))
          ),
          ...
        );
      };
  }
);

pusher(TestVector)(2, 5, 8, 11, 14);

How to fix corrupted git repository?

TL;DR

Git doesn't really store history the way you think it does. It calculates history at run-time based on an ancestor chain. If your ancestry is missing blobs, trees, or commits then you may not be able to fully recover your history.

Restore Missing Objects from Backups

The first thing you can try is to restore the missing items from backup. For example, see if you have a backup of the commit stored as .git/objects/98/4c11abfc9c2839b386f29c574d9e03383fa589. If so you can restore it.

You may also want to look into git-verify-pack and git-unpack-objects in the event that the commit has already been packed up and you want to return it to a loose object for the purposes of repository surgery.

Surgical Resection

If you can't replace the missing items from a backup, you may be able to excise the missing history. For example, you might examine your history or reflog to find an ancestor of commit 984c11abfc9c2839b386f29c574d9e03383fa589. If you find one intact, then:

  1. Copy your Git working directory to a temporary directory somewhere.
  2. Do a hard reset to the uncorrupted commit.
  3. Copy your current files back into the Git work tree, but make sure you don't copy the .git folder back!
  4. Commit the current work tree, and do your best to treat it as a squashed commit of all the missing history.

If it works, you will of course lose the intervening history. At this point, if you have a working history log, then it's a good idea to prune your history and reflogs of all unreachable commits and objects.

Full Restores and Re-Initialization

If your repository is still broken, then hopefully you have an uncorrupted backup or clone you can restore from. If not, but your current working directory contains valid files, then you can always re-initialize Git. For example:

rm -rf .git
git init
git add .
git commit -m 'Re-initialize repository without old history.'

It's drastic, but it may be your only option if your repository history is truly unrecoverable. YMMV.

Vuejs and Vue.set(), update array

As stated before - VueJS simply can't track those operations(array elements assignment). All operations that are tracked by VueJS with array are here. But I'll copy them once again:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

During development, you face a problem - how to live with that :).

push(), pop(), shift(), unshift(), sort() and reverse() are pretty plain and help you in some cases but the main focus lies within the splice(), which allows you effectively modify the array that would be tracked by VueJs. So I can share some of the approaches, that are used the most working with arrays.

You need to replace Item in Array:

// note - findIndex might be replaced with some(), filter(), forEach() 
// or any other function/approach if you need 
// additional browser support, or you might use a polyfill
const index = this.values.findIndex(item => {
          return (replacementItem.id === item.id)
        })
this.values.splice(index, 1, replacementItem)

Note: if you just need to modify an item field - you can do it just by:

this.values[index].itemField = newItemFieldValue

And this would be tracked by VueJS as the item(Object) fields would be tracked.

You need to empty the array:

this.values.splice(0, this.values.length)

Actually you can do much more with this function splice() - w3schools link You can add multiple records, delete multiple records, etc.

Vue.set() and Vue.delete()

Vue.set() and Vue.delete() might be used for adding field to your UI version of data. For example, you need some additional calculated data or flags within your objects. You can do this for your objects, or list of objects(in the loop):

 Vue.set(plan, 'editEnabled', true) //(or this.$set)

And send edited data back to the back-end in the same format doing this before the Axios call:

 Vue.delete(plan, 'editEnabled') //(or this.$delete)

How to embed images in html email

I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.

Regarding displaying embedded (inline) images, here's what's on their documentation:

Inline Attachments

There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with <img src="cid:my-photo" alt="my-photo" />.

In detail, here is the function to add an inline attachment:

$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

To give you a more complete example of how it would work:

<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on     errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->Port       = 25;                    // set the SMTP port
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->Subject = 'PHPMailer Test';

  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';

  $mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
  $mail->Send();
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

Edit:

Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.

One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.

For example:

You can replace the line that send the email:

$mail->Send();

With this:

$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want

Hope that helps. Let me know if you run into trouble using it.

Searching if value exists in a list of objects using Linq

Try this, I hope it helps you.

 if (lstCustumers.Any(cus => cus.Firstname == "John"))
 {
     //TODO CODE
 }

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

The listed return type of the method is Task<string>. You're trying to return a string. They are not the same, nor is there an implicit conversion from string to Task<string>, hence the error.

You're likely confusing this with an async method in which the return value is automatically wrapped in a Task by the compiler. Currently that method is not an async method. You almost certainly meant to do this:

private async Task<string> methodAsync() 
{
    await Task.Delay(10000);
    return "Hello";
}

There are two key changes. First, the method is marked as async, which means the return type is wrapped in a Task, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await model always avoid blocking waits when you can. Task.Delay is a task that will be completed after the specified number of milliseconds. By await-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).

If you prefer a 4.0 way of doing it, without using await , you can do this:

private Task<string> methodAsync() 
{
    return Task.Delay(10000)
        .ContinueWith(t => "Hello");
}

The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await we aren't leveraging here.

If your Thread.Sleep(10000) is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run:

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            SomeLongRunningMethod();
            return "Hello";
        });
}

Or more likely:

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            return SomeLongRunningMethodThatReturnsAString();
        });
}

Continue For loop

A few years late, but here is another alternative.

For x = LBound(arr) To UBound(arr)
    sname = arr(x)  
    If InStr(sname, "Configuration item") Then  
        'Do nothing here, which automatically go to the next iteration
    Else
        'Code to perform the required action
    End If
Next x

How to stop process from .BAT file?

Here is how to kill one or more process from a .bat file.

Step 1. Open a preferred text editor and create a new file.

step 2. To kill one process use the 'taskkill' command, with the '/im' parameter that specifies the image name of the process to be terminated. Example:

taskkill /im examplename.exe

To 'force' kill a process use the '/f' parameter which specifies that processes be forcefully terminated. Example:

taskkill /f /im somecorporateprocess.exe

To kill more than one process you rinse and repeat the first part of step 2. Example:

taskkill /im examplename.exe
taskkill /im examplename1.exe
taskkill /im examplename2.exe

or

taskkill /f /im examplename.exe
taskkill /f /im examplename1.exe
taskkill /f /im examplename2.exe

step 3. Save your file to desired location with the .bat extension.

step 4. click newly created bat file to run it.

MySQL wait_timeout Variable - GLOBAL vs SESSION

As noted by Riedsio, the session variables do not change after connecting unless you specifically set them; setting the global variable only changes the session value of your next connection.

For example, if you have 100 connections and you lower the global wait_timeout then it will not affect the existing connections, only new ones after the variable was changed.

Specifically for the wait_timeout variable though, there is a twist. If you are using the mysql client in the interactive mode, or the connector with CLIENT_INTERACTIVE set via mysql_real_connect() then you will see the interactive_timeout set for @@session.wait_timeout

Here you can see this demonstrated:

> ./bin/mysql -Bsse 'select @@session.wait_timeout, @@session.interactive_timeout, @@global.wait_timeout, @@global.interactive_timeout' 
70      60      70      60

> ./bin/mysql -Bsse 'select @@wait_timeout'                                                                                                 
70

> ./bin/mysql                                                                                                                               
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.12-5 MySQL Community Server (GPL)

Copyright (c) 2009-2016 Percona LLC and/or its affiliates
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select @@wait_timeout;
+----------------+
| @@wait_timeout |
+----------------+
|             60 |
+----------------+
1 row in set (0.00 sec)

So, if you are testing this using the client it is the interactive_timeout that you will see when connecting and not the value of wait_timeout

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Rename a file using Java

Files.move(file.toPath(), fileNew.toPath()); 

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.

Remove part of string in Java

Kotlin Solution

If you are removing a specific string from the end, use removeSuffix (Documentation)

var text = "one(two"
text = text.removeSuffix("(two") // "one"

If the suffix does not exist in the string, it just returns the original

var text = "one(three"
text = text.removeSuffix("(two") // "one(three"

If you want to remove after a character, use

// Each results in "one"

text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")

You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar

The Full List is here: (Documentation)

Outline radius?

Similar to Lea Hayes above, but here's how I did it:

_x000D_
_x000D_
div {_x000D_
  background: #999;_x000D_
  height: 100px;_x000D_
  width: 200px;_x000D_
  border: #999 solid 1px;_x000D_
  border-radius: 10px;_x000D_
  margin: 15px;_x000D_
  box-shadow: 0px 0px 0px 1px #fff inset;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

No nesting of DIVs or jQuery necessary, Altho for brevity I have left out the -moz and -webkit variants of some of the CSS. You can see the result above

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

What does java.lang.Thread.interrupt() do?

Thread interruption is based on flag interrupt status. For every thread default value of interrupt status is set to false. Whenever interrupt() method is called on thread, interrupt status is set to true.

  1. If interrupt status = true (interrupt() already called on thread), that particular thread cannot go to sleep. If sleep is called on that thread interrupted exception is thrown. After throwing exception again flag is set to false.
  2. If thread is already sleeping and interrupt() is called, thread will come out of sleeping state and throw interrupted Exception.

VBA Go to last empty row

If you are certain that you only need column A, then you can use an End function in VBA to get that result.

If all the cells A1:A100 are filled, then to select the next empty cell use:

Range("A1").End(xlDown).Offset(1, 0).Select

Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.

If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:

Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select

Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.

Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select

The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

Does svn have a `revert-all` command?

To revert modified files:

sudo svn revert
svn status|grep "^ *M" | sed -e 's/^ *M *//'

Maven compile with multiple src directories

This can be done in two steps:

  • For each source directory you should create own module.
  • In all modules you should specify the same build directory: ${build.directory}

If you work with started Jetty (jetty:run), then recompilation of any class in any module (with Maven, IDEA or Eclipse) will lead to Jetty's restart. The same behavior you'll get for modified resources.

Two dimensional array list

I know that's an old question with good answers, but I believe I can add my 2 cents.

The simplest and most flexible way which works for me is just using an almost "Plain and Old Java Object" class2D to create each "row" of your array.

The below example has some explanations and is executable (you can copy and paste it, but remember to check the package name):

package my2darraylist;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;

public class My2DArrayList
{
    public static void main(String[] args)
    {
        // This is your "2D" ArrayList
        // 
        List<Box> boxes = new ArrayList<>();

        // Add your stuff
        //
        Box stuff = new Box();
        stuff.setAString( "This is my stuff");
        stuff.addString("My Stuff 01");
        stuff.addInteger( 1 );
        boxes.add( stuff );

        // Add other stuff
        //
        Box otherStuff = new Box();
        otherStuff.setAString( "This is my other stuff");
        otherStuff.addString("My Other Stuff 01");
        otherStuff.addInteger( 1 );
        otherStuff.addString("My Other Stuff 02");
        otherStuff.addInteger( 2 );
        boxes.add( otherStuff );

        // List the whole thing
        for ( Box box : boxes)
        {
            System.out.println( box.getAString() );
            System.out.println( box.getMyStrings().size() );
            System.out.println( box.getMyIntegers().size() );
        }
    }

}

class Box
{
    // Each attribute is a "Column" in you array
    //    
    private String aString;
    private List<String> myStrings = new ArrayList<>() ;
    private List<Integer> myIntegers = new ArrayList<>();
    // Use your imagination...
    //
    private JPanel jpanel;

    public void addString( String s )
    {
        myStrings.add( s );
    }

    public void addInteger( int i )
    {
        myIntegers.add( i );
    }

    // Getters & Setters

    public String getAString()
    {
        return aString;
    }

    public void setAString(String aString)
    {
        this.aString = aString;
    }

    public List<String> getMyStrings()
    {
        return myStrings;
    }

    public void setMyStrings(List<String> myStrings)
    {
        this.myStrings = myStrings;
    }

    public List<Integer> getMyIntegers()
    {
        return myIntegers;
    }

    public void setMyIntegers(List<Integer> myIntegers)
    {
        this.myIntegers = myIntegers;
    }

    public JPanel getJpanel()
    {
        return jpanel;
    }

    public void setJpanel(JPanel jpanel)
    {
        this.jpanel = jpanel;
    }
}

UPDATE - To answer the question from @Mohammed Akhtar Zuberi, I've created the simplified version of the program, to make it easier to show the results.

import java.util.ArrayList;

public class My2DArrayListSimplified
{

    public static void main(String[] args)
    {
        ArrayList<Row> rows = new ArrayList<>();
        Row row;
        // Insert the columns for each row
        //             First Name, Last Name, Age
        row = new Row("John",      "Doe",     30);
        rows.add(row);
        row = new Row("Jane",      "Doe",     29);
        rows.add(row);
        row = new Row("Mary",      "Doe",      1);
        rows.add(row);

        // Show the Array
        //
        System.out.println("First\t Last\tAge");
        System.out.println("----------------------");
        for (Row printRow : rows)
        {
            System.out.println(
                    printRow.getFirstName() + "\t " +
                    printRow.getLastName() + "\t" +
                    printRow.getAge());

        }
    }

}

class Row
{

    // REMEMBER: each attribute is a column
    //
    private final String firstName;
    private final String lastName;
    private final int age;

    public Row(String firstName, String lastName, int age)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public int getAge()
    {
        return age;
    }

}

The code above produces the following result (I ran it on NetBeans):

run:
First    Last   Age
----------------------
John     Doe    30
Jane     Doe    29
Mary     Doe    1
BUILD SUCCESSFUL (total time: 0 seconds)

How to change Rails 3 server default port in develoment?

We're using Puma as a web server, and dotenv to set environment variables in development. This means I can set an environment variable for PORT, and reference it in the Puma config.

# .env
PORT=10524


# config/puma.rb
port ENV['PORT']

However, you'll have to start your app with foreman start instead of rails s, otherwise the puma config doesn't get read properly.

I like this approach because the configuration works the same way in development and production, you just change the value of the port if necessary.

How can I convert tabs to spaces in every file of a directory?

How can I convert tabs to spaces in every file of a directory (possibly recursively)?

This is usually not what you want.

Do you want to do this for png images? PDF files? The .git directory? Your Makefile (which requires tabs)? A 5GB SQL dump?

You could, in theory, pass a whole lot of exlude options to find or whatever else you're using; but this is fragile, and will break as soon as you add other binary files.

What you want, is at least:

  1. Skip files over a certain size.
  2. Detect if a file is binary by checking for the presence of a NULL byte.
  3. Only replace tabs at the start of a file (expand does this, sed doesn't).

As far as I know, there is no "standard" Unix utility that can do this, and it's not very easy to do with a shell one-liner, so a script is needed.

A while ago I created a little script called sanitize_files which does exactly that. It also fixes some other common stuff like replacing \r\n with \n, adding a trailing \n, etc.

You can find a simplified script without the extra features and command-line arguments below, but I recommend you use the above script as it's more likely to receive bugfixes and other updated than this post.

I would also like to point out, in response to some of the other answers here, that using shell globbing is not a robust way of doing this, because sooner or later you'll end up with more files than will fit in ARG_MAX (on modern Linux systems it's 128k, which may seem a lot, but sooner or later it's not enough).


#!/usr/bin/env python
#
# http://code.arp242.net/sanitize_files
#

import os, re, sys


def is_binary(data):
    return data.find(b'\000') >= 0


def should_ignore(path):
    keep = [
        # VCS systems
        '.git/', '.hg/' '.svn/' 'CVS/',

        # These files have significant whitespace/tabs, and cannot be edited
        # safely
        # TODO: there are probably more of these files..
        'Makefile', 'BSDmakefile', 'GNUmakefile', 'Gemfile.lock'
    ]

    for k in keep:
        if '/%s' % k in path:
            return True
    return False


def run(files):
    indent_find = b'\t'
    indent_replace = b'    ' * indent_width

    for f in files:
        if should_ignore(f):
            print('Ignoring %s' % f)
            continue

        try:
            size = os.stat(f).st_size
        # Unresolvable symlink, just ignore those
        except FileNotFoundError as exc:
            print('%s is unresolvable, skipping (%s)' % (f, exc))
            continue

        if size == 0: continue
        if size > 1024 ** 2:
            print("Skipping `%s' because it's over 1MiB" % f)
            continue

        try:
            data = open(f, 'rb').read()
        except (OSError, PermissionError) as exc:
            print("Error: Unable to read `%s': %s" % (f, exc))
            continue

        if is_binary(data):
            print("Skipping `%s' because it looks binary" % f)
            continue

        data = data.split(b'\n')

        fixed_indent = False
        for i, line in enumerate(data):
            # Fix indentation
            repl_count = 0
            while line.startswith(indent_find):
                fixed_indent = True
                repl_count += 1
                line = line.replace(indent_find, b'', 1)

            if repl_count > 0:
                line = indent_replace * repl_count + line

        data = list(filter(lambda x: x is not None, data))

        try:
            open(f, 'wb').write(b'\n'.join(data))
        except (OSError, PermissionError) as exc:
            print("Error: Unable to write to `%s': %s" % (f, exc))


if __name__ == '__main__':
    allfiles = []
    for root, dirs, files in os.walk(os.getcwd()):
        for f in files:
            p = '%s/%s' % (root, f)
            if do_add:
                allfiles.append(p)

    run(allfiles)

Powershell: How can I stop errors from being displayed in a script?

You're way off track here.

You already have a nice, big error message. Why on Earth would you want to write code that checks $? explicitly after every single command? This is enormously cumbersome and error prone. The correct solution is stop checking $?.

Instead, use PowerShell's built in mechanism to blow up for you. You enable it by setting the error preference to the highest level:

$ErrorActionPreference = 'Stop'

I put this at the top of every single script I ever write, and now I don't have to check $?. This makes my code vastly simpler and more reliable.

If you run into situations where you really need to disable this behavior, you can either catch the error or pass a setting to a particular function using the common -ErrorAction. In your case, you probably want your process to stop on the first error, catch the error, and then log it.

Do note that this doesn't handle the case when external executables fail (exit code nonzero, conventionally), so you do still need to check $LASTEXITCODE if you invoke any. Despite this limitation, the setting still saves a lot of code and effort.

Additional reliability

You might also want to consider using strict mode:

Set-StrictMode -Version Latest

This prevents PowerShell from silently proceeding when you use a non-existent variable and in other weird situations. (See the -Version parameter for details about what it restricts.)

Combining these two settings makes PowerShell much more of fail-fast language, which makes programming in it vastly easier.

JDBC connection failed, error: TCP/IP connection to host failed

The error is self explanatory:

  • Check if your SQL server is actually up and running
  • Check SQL server hostname, username and password is correct
  • Check there's no firewall rule blocking TCP connection to port 1433
  • Check the host is actually reachable

A good check I often use is to use telnet, eg on a windows command prompt run:

telnet 127.0.0.1 1433

If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem

Simulating ENTER keypress in bash script

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

Rails: How to reference images in CSS within Rails 4

WHAT I HAVE FOUND AFTER HOURS OF MUCKING WITH THIS:

WORKS :

background-image: url(image_path('transparent_2x2.png')); 

// how to add attributes like repeat, center, fixed?

The above outputs something like: "/assets/transparent_2x2-ec47061dbe4fb88d51ae1e7f41a146db.png"

Notice the leading "/", and it's within quotes. Also note the scss extension and image_path helper in yourstylesheet.css.scss. The image is in the app/assets/images directory.

Doesn't work:

background: url(image_path('transparent_2x2.png') repeat center center fixed;

doesn't work, invalid property:

background:url(/assets/pretty_photo/default/sprite.png) 2px 1px repeat center fixed;

My last resort was going to be to put these in my public s3 bucket and load from there, but finally got something going.

Best practices with STDIN in Ruby?

I am not quite sure what you need, but I would use something like this:

#!/usr/bin/env ruby

until ARGV.empty? do
  puts "From arguments: #{ARGV.shift}"
end

while a = gets
  puts "From stdin: #{a}"
end

Note that because ARGV array is empty before first gets, Ruby won't try to interpret argument as text file from which to read (behaviour inherited from Perl).

If stdin is empty or there is no arguments, nothing is printed.

Few test cases:

$ cat input.txt | ./myprog.rb
From stdin: line 1
From stdin: line 2

$ ./myprog.rb arg1 arg2 arg3
From arguments: arg1
From arguments: arg2
From arguments: arg3
hi!
From stdin: hi!

Programmatically scroll to a specific position in an Android ListView

Put your code in handler as follows,

public void timerDelayRunForScroll(long time) {
        Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() {           
            public void run() {   
                try {
                    lstView.smoothScrollToPosition(YOUR_POSITION);
                } catch (Exception e) {}
            }
        }, time); 
    }

and then call this method like,

timerDelayRunForScroll(100);

CHEERS!!!

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

Here is my Approach based on DarKalimHero's Suggestion by selecting only on Explorer.exe processes

Function Get-RdpSessions 
{
    param(
        [string]$computername 
    )

    $processinfo = Get-WmiObject -Query "select * from win32_process where name='explorer.exe'" -ComputerName $computername

    $processinfo | ForEach-Object { $_.GetOwner().User } | Sort-Object -Unique | ForEach-Object { New-Object psobject -Property @{Computer=$computername;LoggedOn=$_} } | Select-Object Computer,LoggedOn
}

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Just used the Nathan's solution and it works fine. I needed to convert ISO-8859-1 to Unicode:

string isocontent = Encoding.GetEncoding("ISO-8859-1").GetString(fileContent, 0, fileContent.Length);
byte[] isobytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(isocontent);
byte[] ubytes = Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.Unicode, isobytes);
return Encoding.Unicode.GetString(ubytes, 0, ubytes.Length);

How to get selected value from Dropdown list in JavaScript

It is working fine with me.

I have the following HTML:

<div>
    <select id="select1">
        <option value="1">test1</option>
        <option value="2" selected="selected">test2</option>
        <option value="3">test3</option>
    </select>
    <br/>
    <button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>

And the following JavaScript:

function GetSelectedItem(el)
{
    var e = document.getElementById(el);
    var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
    alert(strSel);
}

See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.

Inverse dictionary lookup in Python

No, you can not do this efficiently without looking in all the keys and checking all their values. So you will need O(n) time to do this. If you need to do a lot of such lookups you will need to do this efficiently by constructing a reversed dictionary (can be done also in O(n)) and then making a search inside of this reversed dictionary (each search will take on average O(1)).

Here is an example of how to construct a reversed dictionary (which will be able to do one to many mapping) from a normal dictionary:

for i in h_normal:
    for j in h_normal[i]:
        if j not in h_reversed:
            h_reversed[j] = set([i])
        else:
            h_reversed[j].add(i)

For example if your

h_normal = {
  1: set([3]), 
  2: set([5, 7]), 
  3: set([]), 
  4: set([7]), 
  5: set([1, 4]), 
  6: set([1, 7]), 
  7: set([1]), 
  8: set([2, 5, 6])
}

your h_reversed will be

{
  1: set([5, 6, 7]),
  2: set([8]), 
  3: set([1]), 
  4: set([5]), 
  5: set([8, 2]), 
  6: set([8]), 
  7: set([2, 4, 6])
}

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

WebScarab is a framework for analysing applications that communicate using the HTTP and HTTPS protocols. It is written in Java, and is thus portable to many platforms. WebScarab has several modes of operation, implemented by a number of plugins. In its most common usage, WebScarab operates as an intercepting proxy, allowing the operator to review and modify requests created by the browser before they are sent to the server, and to review and modify responses returned from the server before they are received by the browser. WebScarab is able to intercept both HTTP and HTTPS communication. The operator can also review the conversations (requests and responses) that have passed through WebScarab.

http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project

Failed to execute 'createObjectURL' on 'URL':

My code was broken because I was using a deprecated technique. It used to be this:

video.src = window.URL.createObjectURL(localMediaStream);
video.play();

Then I replaced that with this:

video.srcObject = localMediaStream;
video.play();

That worked beautifully.

EDIT: Recently localMediaStream has been deprecated and replaced with MediaStream. The latest code looks like this:

video.srcObject = new MediaStream();

References:

  1. Deprecated technique: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
  2. Modern deprecated technique: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
  3. Modern technique: https://developer.mozilla.org/en-US/docs/Web/API/MediaStream

find vs find_by vs where

There is a difference between find and find_by in that find will return an error if not found, whereas find_by will return null.

Sometimes it is easier to read if you have a method like find_by email: "haha", as opposed to .where(email: some_params).first.

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

Suppress/ print without b' prefix for bytes in Python 3

If we take a look at the source for bytes.__repr__, it looks as if the b'' is baked into the method.

The most obvious workaround is to manually slice off the b'' from the resulting repr():

>>> x = b'\x01\x02\x03\x04'

>>> print(repr(x))
b'\x01\x02\x03\x04'

>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

date format yyyy-MM-ddTHH:mm:ssZ

Look here at "u" and "s" patterns. First is without 'T' separator, and the second one is without timezone suffix.

self.tableView.reloadData() not working in Swift

All the calls to UI should be asynchronous, anything you change on the UI like updating table or changing text label should be done from main thread. using DispatchQueue.main will add your operation to the queue on the main thread.

Swift 4

DispatchQueue.main.async{
    self.tableView.reloadData()
}

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

Is it necessary to write HEAD, BODY and HTML tags?

It's valid to omit them in HTML4:

7.3 The HTML element
start tag: optional, End tag: optional

7.4.1 The HEAD element
start tag: optional, End tag: optional

http://www.w3.org/TR/html401/struct/global.html

In HTML5, there are no "required" or "optional" elements exactly, as HTML5 syntax is more loosely defined. For example, title:

The title element is a required child in most situations, but when a higher-level protocol provides title information, e.g. in the Subject line of an e-mail when HTML is used as an e-mail authoring format, the title element can be omitted.

http://www.w3.org/TR/html5/semantics.html#the-title-element-0

It's not valid to omit them in true XHTML5, though that is almost never used (versus XHTML-acting-like-HTML5).

However, from a practical standpoint you often want browsers to run in "standards mode," for predictability in rendering HTML and CSS. Providing a DOCTYPE and a more structured HTML tree will guarantee more predictable cross-browser results.

How do I check if a cookie exists?

/// ************************************************ cookie_exists

/// global entry point, export to global namespace

/// <synopsis>
///   cookie_exists ( name );
///
/// <summary>
///   determines if a cookie with name exists
///
/// <param name="name">
///   string containing the name of the cookie to test for 
//    existence
///
/// <returns>
///   true, if the cookie exists; otherwise, false
///
/// <example>
///   if ( cookie_exists ( name ) );
///     {
///     // do something with the existing cookie
///     }
///   else
///     {
///     // cookies does not exist, do something else 
///     }

function cookie_exists ( name )
  {
  var exists = false;

  if ( document.cookie )
    {
    if ( document.cookie.length > 0 )
      {
                                    // trim name
      if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
        {
        var cookies = document.cookie.split ( ";" );
        var name_with_equal = name + "=";

        for ( var i = 0; ( i < cookies.length ); i++ )
          {
                                    // trim cookie
          var cookie = cookies [ i ].replace ( /^\s*/, "" );

          if ( cookie.indexOf ( name_with_equal ) === 0 )
            {
            exists = true;
            break;
            }
          }
        }
      }
    }

  return ( exists );

  } // cookie_exists

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

Add click event on div tag using javascript

the document class selector:

document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)

also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

document.querySelector(".drill_cursor").addEventListener('click',function(){},false)

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

Double value to round up in Java

This is not possible in the requested way because there are numbers with two decimal places which can not be expressed exactly using IEEE floating point numbers (for example 1/10 = 0.1 can not be expressed as a Double or Float). The formatting should always happen as the last step before presenting the result to the user.

I guess you are asking because you want to deal with monetary values. There is no way to do this reliably with floating-point numbers, you shoud consider switching to fixed-point arithmetics. This probably means doing all calculations in "cents" instead of "dollars".

How do I drop table variables in SQL-Server? Should I even do this?

Table variables are automatically local and automatically dropped -- you don't have to worry about it.

How to convert an enum type variable to a string?

I needed this to work in both directions AND I frequently embed my enums inside a containing class, and so I started with the solution by James McNellis way, way at the top of these answers, but I made this solution. Note also I prefer enum class rather than just enum, which complicates the answer somewhat.

#define X_DEFINE_ENUMERATION(r, datatype, elem) case datatype::elem : return BOOST_PP_STRINGIZE(elem);

// The data portion of the FOR_EACH should be (variable type)(value)
#define X_DEFINE_ENUMERATION2(r, dataseq, elem) \
    if (BOOST_PP_SEQ_ELEM(1, dataseq) == BOOST_PP_STRINGIZE(elem) ) return BOOST_PP_SEQ_ELEM(0, dataseq)::elem;

#define DEFINE_ENUMERATION_MASTER(modifier, name, toFunctionName, enumerators)    \
    enum class name {                                                         \
        Undefined,                                                            \
        BOOST_PP_SEQ_ENUM(enumerators)                                        \
    };                                                                        \
                                                                              \
    modifier const char* ToString(const name & v)                               \
    {                                                                         \
        switch (v)                                                            \
        {                                                                     \
            BOOST_PP_SEQ_FOR_EACH(                                            \
                X_DEFINE_ENUMERATION,                                         \
                name,                                                         \
                enumerators                                                   \
            )                                                                 \
            default: return "[Unknown " BOOST_PP_STRINGIZE(name) "]";         \
        }                                                                     \
    }                                                                         \
                                                                              \
    modifier const name toFunctionName(const std::string & value)               \
    {                                                                         \
        BOOST_PP_SEQ_FOR_EACH(                                                \
            X_DEFINE_ENUMERATION2,                                            \
            (name)(value),                                                    \
            enumerators                                                       \
        )                                                                     \
        return name::Undefined;                                               \
    }

#define DEFINE_ENUMERATION(name, toFunctionName, enumerators)                 \
    DEFINE_ENUMERATION_MASTER(inline, name, toFunctionName, enumerators)

#define DEFINE_ENUMERATION_INSIDE_CLASS(name, toFunctionName, enumerators)                 \
    DEFINE_ENUMERATION_MASTER(static, name, toFunctionName, enumerators)

To use it inside a class, you could do something like this:

class ComponentStatus {
public:
    /** This is a simple bad, iffy, and good status. See other places for greater details. */
    DEFINE_ENUMERATION_INSIDE_CLASS(Status, toStatus, (RED)(YELLOW)(GREEN)
}

And I wrote a CppUnit test, which demonstrates how to use it:

void
ComponentStatusTest::testSimple() {
    ComponentStatus::Status value = ComponentStatus::Status::RED;

    const char * valueStr = ComponentStatus::ToString(value);

    ComponentStatus::Status convertedValue = ComponentStatus::toStatus(string(valueStr));

    CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect conversion to a string.", (const char *)"RED", valueStr);
    CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect conversion back from a string.", convertedValue, value);
}

DEFINE_ENUMERATION(Status, toStatus, (RED)(YELLOW)(GREEN))

void
ComponentStatusTest::testOutside() {
    Status value = Status::RED;

    const char * valueStr = ToString(value);

    Status convertedValue = toStatus(string(valueStr));

    CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect conversion to a string.", (const char *)"RED", valueStr);
    CPPUNIT_ASSERT_EQUAL_MESSAGE("Incorrect conversion back from a string.", convertedValue, value);
}

You have to pick which macro to use, either DEFINE_ENUMERATION or DEFINE_ENUMERATION_INSIDE_CLASS. You'll see I used the latter when defining ComponentStatus::Status but I used the former when just defining Status. The difference is simple. Inside a class, I prefix the to/from methods as "static" and if not in a class, I use "inline". Trivial differences, but necessary.

Unfortunately, I don't think there's a clean way to avoid having to do this:

const char * valueStr = ComponentStatus::ToString(value);

although you could manually create an inline method after your class definition that simply chains to the class method, something like:

inline const char * toString(const ComponentStatus::Status value) { return ComponentStatus::ToString(value); }

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

How to import an Oracle database from dmp file and log file?

If you are using impdp command example from @sathyajith-bhat response:

impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;

you will need to use mandatory parameter directory and create and grant it as:

CREATE OR REPLACE DIRECTORY DMP_DIR AS 'c:\Users\USER\Downloads';
GRANT READ, WRITE ON DIRECTORY DMP_DIR TO {USER};

or use one of defined:

select * from DBA_DIRECTORIES;

My ORACLE Express 11g R2 has default named DATA_PUMP_DIR (located at {inst_dir}\app\oracle/admin/xe/dpdump/) you sill need to grant it for your user.

Can't start Eclipse - Java was started but returned exit code=13

I had the same issue after I upgraded my JDK from 1.7 to 1.8. I'm using Eclipse 4.4 (Luna). The error is gone after I degrade JDK to 1.7.

How do I tell matplotlib that I am done with a plot?

If you're using Matplotlib interactively, for example in a web application, (e.g. ipython) you maybe looking for

plt.show()

instead of plt.close() or plt.clf().

Location of WSDL.exe

You'll get it as part of a Visual Studio install (if you included the SDK), or in a standalone SDK install. It'll live somewhere like C:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin

If you don't already have it, you can download the .NET SDKs from
http://msdn.microsoft.com/en-us/netframework/aa569263.aspx

'gulp' is not recognized as an internal or external command

The best solution, you can manage the multiple node versions using nvm installer. then, install the required node's version using below command

nvm install version

Use below command as a working node with mentioned version alone

nvm use version

now, you can use any version node without uninstalling previous installed node.

Python sys.argv lists and indexes

In a nutshell, sys.argv is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0], and the second element (first argument, if there is one) is sys.argv[1], etc.

The test len(sys.argv) >= 2 simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.

What is Android's file system?

Similar to Linux:

  • /boot

  • /system

  • /recovery

  • /data

  • /cache

  • /misc

How to remove a build from itunes connect?

As I understand the new iTunesConnect philosophy :

  • you can upload some multiple "eligible" builds to iTunesConnect int the "pre release" tab
  • let some other testers test a specific build, via TestFlight (and declared as iTunesConnect users)
  • when you come to a stable version, select the correct build version, from the "Versions" tab to submit to the AppStore, the usual way.

To me, you can have like 150 build for a pre release, it doesn't matter.

Debugging with Android Studio stuck at "Waiting For Debugger" forever

I had the same problem. Restart my android phone device worked for me.

check if command was successful in a batch file

You can use

if errorlevel 1 echo Unsuccessful

in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.

Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.

New line character in VB.Net?

it's :

vbnewline

for example

Msgbox ("Fst line" & vbnewline & "second line")

How do I get the value of text input field using JavaScript?

If your input is in a form and you want to get value after submit you can do like

<form onsubmit="submitLoginForm(event)">
    <input type="text" name="name">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

<script type="text/javascript">

    function submitLoginForm(event){
        event.preventDefault();

        console.log(event.target['name'].value);
        console.log(event.target['password'].value);
    }
</script>

Benefit of this way: Example your page have 2 form for input sender and receiver information.

If you don't use form for get value then
- You can set 2 different id(or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
- If you set same value for 2 input, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver. Later if you change the order of 2 form in html, you need to check this code again

If you use form, then you can use name, address, ...

How can you speed up Eclipse?

Try this too, it will improve the performance:

cleaning up indexes - {workspace path}.metadata.plugins\org.eclipse.jdt.core cleaning up history - {workspace path}.metadata.plugins\org.eclipse.core.resources.history

Cleaning the above folders will not impact the project files.

Convert JSON to DataTable

It can also be achieved using below code.

DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

Batch file to copy files from one folder to another folder

To bypass the 'specify a file name or directory name on the target (F = file, D = directory)?' prompt with xcopy, you can do the following...

echo f | xcopy /f /y srcfile destfile

or for those of us just copying large substructures/folders:

use /i which specifies destination must be a directory if copying more than one file

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

Rounding to two decimal places in Python 2.7?

Rounding up to the next 0.05, I would do this way:

def roundup(x):
    return round(int(math.ceil(x / 0.05)) * 0.05,2)

How can I determine installed SQL Server instances and their versions?

I know this thread is a bit old, but I came across this thread before I found the answer I was looking for and thought I'd share. If you are using SQLExpress (or localdb) there is a simpler way to find your instance names. At a command line type:

> sqllocaldb i

This will list the instance names you have installed locally. So your full server name should include (localdb)\ in front of the instance name to connect. Also, sqllocaldb allows you to create new instances or delete them as well as configure them. See: SqlLocalDB Utility.

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

Check file size before upload

JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.

Displaying better error message than "No JSON object could be decoded"

You could try the rson library found here: http://code.google.com/p/rson/ . I it also up on PYPI: https://pypi.python.org/pypi/rson/0.9 so you can use easy_install or pip to get it.

for the example given by tom:

>>> rson.loads('[1,2,]')
...
rson.base.tokenizer.RSONDecodeError: Unexpected trailing comma: line 1, column 6, text ']'

RSON is a designed to be a superset of JSON, so it can parse JSON files. It also has an alternate syntax which is much nicer for humans to look at and edit. I use it quite a bit for input files.

As for the capitalizing of boolean values: it appears that rson reads incorrectly capitalized booleans as strings.

>>> rson.loads('[true,False]')
[True, u'False']

Swift - Remove " character from string

Swift 3 and Swift 4:

text2 = text2.textureName.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)

Latest documents updated to Swift 3.0.1 have:

  • Null Character (\0)
  • Backslash (\\)
  • Horizontal Tab (\t)
  • Line Feed (\n)
  • Carriage Return (\r)
  • Double Quote (\")
  • Single Quote (\')
  • Unicode scalar (\u{n}), where n is between one and eight hexadecimal digits

If you need more details you can take a look to the official docs here

Node.js: How to read a stream into a buffer?

I suggest loganfsmyths method, using an array to hold the data.

var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
  var buf = Buffer.concat(bufs);
}

IN my current working example, i am working with GRIDfs and npm's Jimp.

   var bucket = new GridFSBucket(getDBReference(), { bucketName: 'images' } );
    var dwnldStream = bucket.openDownloadStream(info[0]._id);// original size
  dwnldStream.on('data', function(chunk) {
       data.push(chunk);
    });
  dwnldStream.on('end', function() {
    var buff =Buffer.concat(data);
    console.log("buffer: ", buff);
       jimp.read(buff)
.then(image => {
         console.log("read the image!");
         IMAGE_SIZES.forEach( (size)=>{
         resize(image,size);
         });
});

I did some other research

with a string method but that did not work, per haps because i was reading from an image file, but the array method did work.

const DISCLAIMER = "DONT DO THIS";
var data = "";
stdout.on('data', function(d){ 
           bufs+=d; 
         });
stdout.on('end', function(){
          var buf = Buffer.from(bufs);
          //// do work with the buffer here

          });

When i did the string method i got this error from npm jimp

buffer:  <Buffer 00 00 00 00 00>
{ Error: Could not find MIME for Buffer <null>

basically i think the type coersion from binary to string didnt work so well.

"Default Activity Not Found" on Android Studio upgrade

ugly but worked for me:

Had this error message, my problem was in a module, I just deleted the application tag compleatly from my module's manifest and it worked.

(delete ic_launcher from the module library as well)

was:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mymodule"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="23" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
       >
        <activity
            android:name="com.example.mymodule.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

now:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mymodule"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="23" />


</manifest>

Locking a file in Python

Locking is platform and device specific, but generally, you have a few options:

  1. Use flock(), or equivalent (if your os supports it). This is advisory locking, unless you check for the lock, its ignored.
  2. Use a lock-copy-move-unlock methodology, where you copy the file, write the new data, then move it (move, not copy - move is an atomic operation in Linux -- check your OS), and you check for the existence of the lock file.
  3. Use a directory as a "lock". This is necessary if you're writing to NFS, since NFS doesn't support flock().
  4. There's also the possibility of using shared memory between the processes, but I've never tried that; it's very OS-specific.

For all these methods, you'll have to use a spin-lock (retry-after-failure) technique for acquiring and testing the lock. This does leave a small window for mis-synchronization, but its generally small enough to not be an major issue.

If you're looking for a solution that is cross platform, then you're better off logging to another system via some other mechanism (the next best thing is the NFS technique above).

Note that sqlite is subject to the same constraints over NFS that normal files are, so you can't write to an sqlite database on a network share and get synchronization for free.

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

If WorkSheet("wsName") Exists

also a slightly different version. i just did a appllication.sheets.count to know how many worksheets i have additionallyl. well and put a little rename in aswell

Sub insertworksheet()
    Dim worksh As Integer
    Dim worksheetexists As Boolean
    worksh = Application.Sheets.Count
    worksheetexists = False
    For x = 1 To worksh
        If Worksheets(x).Name = "ENTERWROKSHEETNAME" Then
            worksheetexists = True
            'Debug.Print worksheetexists
            Exit For
        End If
    Next x
    If worksheetexists = False Then
        Debug.Print "transformed exists"
        Worksheets.Add after:=Worksheets(Worksheets.Count)
        ActiveSheet.Name = "ENTERNAMEUWANTTHENEWONE"
    End If
End Sub

I want to declare an empty array in java and then I want do update it but the code is not working

You need to give the array a size:

public static void main(String args[])
{
    int array[] = new int[4];
    int number = 5, i = 0,j = 0;
    while (i<4){
        array[i]=number;
        i=i+1;
    }
    while (j<4){
        System.out.println(array[j]);
        j++;
    }
}

Send a file via HTTP POST with C#

For me client.UploadFile still wrapped the content in a multipart request so I had to do it like this:

using (WebClient client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/octet-stream");
    using (Stream fileStream = File.OpenRead(filePath))
    using (Stream requestStream = client.OpenWrite(new Uri(fileUploadUrl), "POST"))
    {
        fileStream.CopyTo(requestStream);
    }
}

Can linux cat command be used for writing text to file?

Here's another way -

cat > outfile.txt
>Enter text
>to save press ctrl-d

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

Angular get object from array by Id

// Used In TypeScript For Angular 4+        
const viewArray = [
          {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
          {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
          {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
          {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

Cannot start MongoDB as a service

Following works with MongoDB 3.6.0

Make sure you have these folders:

  • C:\mongodb\data
  • C:\mongodb\data\db

Then all you need are these commands:

  • mongod --directoryperdb -dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongo.log --logappend --service --install
  • net start MongoDB
  • mongo

How to set portrait and landscape media queries in css?

It can also be as simple as this.

@media (orientation: landscape) {

}

The target principal name is incorrect. Cannot generate SSPI context

I have tried all the solutions here and none of them have worked yet. A workaround that is working is to Click Connect, enter the server name, select Options, Connection Properties tab. Set the "Network protocol" to "Named Pipes". This allows users to remote connect using their network credentials. I'll post an update when I get a fix.

Why check both isset() and !empty()

The accepted answer is not correct.

isset() is NOT equivalent to !empty().

You will create some rather unpleasant and hard to debug bugs if you go down this route. e.g. try running this code:

<?php

$s = '';

print "isset: '" . isset($s) . "'. ";
print "!empty: '" . !empty($s) . "'";

?>

https://3v4l.org/J4nBb

How do I download NLTK data?

Do not name your file nltk.py I used the same code and name it nltk, and got the same error as you have, I changed the file name and it went well.

How to measure elapsed time

Even better!

long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds

Read the documentation about nanoTime()!

How to extract this specific substring in SQL Server?

If you need to split something into 3 pieces, such as an email address and you don't know the length of the middle part, try this (I just ran this on sqlserver 2012 so I know it works):

SELECT top 2000 
    emailaddr_ as email,
    SUBSTRING(emailaddr_, 1,CHARINDEX('@',emailaddr_) -1) as username,
    SUBSTRING(emailaddr_, CHARINDEX('@',emailaddr_)+1, (LEN(emailaddr_) - charindex('@',emailaddr_) - charindex('.',reverse(emailaddr_)) ))  domain 
FROM 
    emailTable
WHERE 
    charindex('@',emailaddr_)>0 
    AND 
    charindex('.',emailaddr_)>0;
GO

Hope this helps.

How can I clear the content of a file?

The easiest way is:

File.WriteAllText(path, string.Empty)

However, I recommend you use FileStream because the first solution can throw UnauthorizedAccessException

using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
     lock(fs)
     {
          fs.SetLength(0);
     }
}

Writing outputs to log file and console

I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:

2017-06-21 11:16:41+05:30 Fetching information about files in the directory...

Add following lines at the top of your script:

LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done >&2)

Hope this helps somebody!

what is the difference between OLE DB and ODBC data sources?

According to ADO: ActiveX Data Objects, a book by Jason T. Roff, published by O'Reilly Media in 2001 (excellent diagram here), he says precisely what MOZILLA said.

(directly from page 7 of that book)

  • ODBC provides access only to relational databases
  • OLE DB provides the following features
    • Access to data regardless of its format or location
    • Full access to ODBC data sources and ODBC drivers

So it would seem that OLE DB interacts with SQL-based datasources THRU the ODBC driver layer.

alt text

I'm not 100% sure this image is correct. The two connections I'm not certain about are ADO.NET thru ADO C-api, and OLE DB thru ODBC to SQL-based data source (because in this diagram the author doesn't put OLE DB's access thru ODBC, which I believe is a mistake).

How to delete columns in a CSV file?

Using a dict to grab headings then looping through gets you what you need cleanly.

import csv
ct = 0
cols_i_want = {'cost' : -1, 'date' : -1}
with open("file1.csv","rb") as source:
    rdr = csv.reader( source )
    with open("result","wb") as result:
        wtr = csv.writer( result )
        for row in rdr:
            if ct == 0:
              cc = 0
              for col in row:
                for ciw in cols_i_want: 
                  if col == ciw:
                    cols_i_want[ciw] = cc
                cc += 1
            wtr.writerow( (row[cols_i_want['cost']], row[cols_i_want['date']]) )
            ct += 1

How to check if a MySQL query using the legacy API was successful?

if using MySQLi bind_param try to put this line above the query

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

How do I create a MessageBox in C#?

Also you can use a MessageBox with OKCancel options, but it requires many codes. The if block is for OK, the else block is for Cancel. Here is the code:

if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
    MessageBox.Show("You pressed OK!");
}
else
{
    MessageBox.Show("You pressed Cancel!");
}

You can also use a MessageBox with YesNo options:

if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    MessageBox.Show("You are pressed Yes!");
}
else
{
    MessageBox.Show("You are pressed No!");
}

php pdo: get the columns name of a table

$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

must be

$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

What precisely does 'Run as administrator' do?

When you log on Windows creates an access token. This identifies you, the groups you are a member of and your privileges. And note that whether a user is an administrator or not is determined by whether the user is a member of the Administrators group.

Without UAC, when you run a program it gets a copy of the access token, and this controls what the program can access.

With UAC, when you run a program it gets a restricted access token. This is the original access token with "Administrators" removed from the list of groups (and some other changes). Even though your user is a member of the Administrators group, the program can't use Administrator privileges.

When you select "Run as Administrator" and your user is an administrator the program is launched with the original unrestricted access token. If your user is not an administrator you are prompted for an administrator account, and the program is run under that account.

Pass Hidden parameters using response.sendRedirect()

Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    ...
    request.getSession().setAttribute("name", name);
    response.sendRedirect("/todo.do");

In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.

If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:

<h1>Welcome ${name}</h1>

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

Does --disable-web-security Work In Chrome Anymore?

Just create this batch file and run it on windows. It basically would kill all chrome instances and then would start chrome with disabling security. Save the following script in batch file say ***.bat and double click on it.

TASKKILL /F /IM chrome.exe
start chrome.exe --args --disable-web-security –-allow-file-access-from-files

What is the best way to dump entire objects to a log in C#?

You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):

MyObject
    Property1 = value
    Property2 = value2
    OtherObject
       OtherProperty = value ...

ExpressJS - throw er Unhandled error event

Reason for this error

Some other process is already running on the port you have specified

Simple and Quick solution

On Linux OS, For example you have specified 3000 as the port

  • Open the terminal and run lsof -i :3000. If any process is already running on port 3000 then you will see this printing on the console

_x000D_
_x000D_
COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME_x000D_
node    16615 aegon   13u  IPv6 183768      0t0  TCP *:3000 (LISTEN)
_x000D_
_x000D_
_x000D_

  • Copy the PID (process ID) from the output

  • Run sudo kill -9 16615 (you have to put PID after -9)

  • Start the server again

Fill username and password using selenium in python

driver = webdriver.Firefox(...)  # Or Chrome(), or Ie(), or Opera()

username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")

username.send_keys("YourUsername")
password.send_keys("Pa55worD")

driver.find_element_by_name("submit").click()

Notes to your code:

How to use index in select statement?

The optimiser will judge if the use of your index will make your query run faster, and if it is, it will use the index.

Depending on your RDBMS you can force the use of an index, although it is not recommended unless you know what you are doing.

In general you should index columns that you use in table join's and where statements

Where is HttpContent.ReadAsAsync?

It looks like it is an extension method (in System.Net.Http.Formatting):

HttpContentExtensions Class

Update:

PM> install-package Microsoft.AspNet.WebApi.Client

According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client package available on NuGet here.

When do you use POST and when do you use GET?

In PHP, POST data limit is usually set by your php.ini. GET is limited by server/browser settings I believe - usually around 255 bytes.

Add/remove class with jquery based on vertical scroll?

For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.

jQuery(document.body).scroll(function() {
        var scroll = jQuery(document.body).scrollTop();

        if (scroll >= 300) {
            //alert();
            header.addClass("sticky");
        } else {
            header.removeClass('sticky');
        }
    });

This code worked for me. Hope it will help you.

How do I use the conditional operator (? :) in Ruby?

@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:

(true) ? 1 : 0

Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \ line-continuation symbol at the end of a line and Ruby will be happy:

(true)   \
  ? 1    \
  : 0

This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.

It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:

(true) ?
  1 :
  0

I think that leads to really hard to read code as the conditional test and/or results get longer.

I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.


Why have you put brackets around true?

Consider the OP's example:

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

Wrapping the conditional test helps make it more readable because it visually separates the test:

<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>

Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:

<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
                                   : question.question 
%>

Or, more written more idiomatically:

<% question = if (question.size > 20)
                question.question.slice(0, 20) + "..."
              else 
                question.question 
              end
%>

It'd be easy to argument that readability suffers badly from question.question too.

How to get current date time in milliseconds in android

The problem is that System. currentTimeMillis(); returns the number of milliseconds from 1970-01-01T00:00:00Z, but new Date() gives the current local time. Adding the ZONE_OFFSET and DST_OFFSET from the Calendar class gives you the time in UTC.

Calendar rightNow = Calendar.getInstance();

// offset to add since we're not UTC

long offset = rightNow.get(Calendar.ZONE_OFFSET) +
    rightNow.get(Calendar.DST_OFFSET);

long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
    (24 * 60 * 60 * 1000);

System.out.println(sinceMidnight + " milliseconds since midnight");

How to split one string into multiple variables in bash shell?

Using bash regex capabilities:

re="^([^-]+)-(.*)$"
[[ "ABCDE-123456" =~ $re ]] && var1="${BASH_REMATCH[1]}" && var2="${BASH_REMATCH[2]}"
echo $var1
echo $var2

OUTPUT

ABCDE
123456

Convert nullable bool? to bool

You can use the null-coalescing operator: x ?? something, where something is a boolean value that you want to use if x is null.

Example:

bool? myBool = null;
bool newBool = myBool ?? false;

newBool will be false.

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

I think you might need to use the full path:

export EDITOR=/usr/bin/vim

Storing Images in PostgreSQL

Try this. I've use the Large Object Binary (LOB) format for storing generated PDF documents, some of which were 10+ MB in size, in a database and it worked wonderfully.

Loop through all elements in XML using NodeList

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();
            }
        }
    }

Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.

For each node under stuff (name, phone, email, area, city)

 el.getElementsByTagName("name").item(0).getTextContent(); 

el.getElementsByTagName("name") will extract the "name" nodes under stuff, .item(0) will get you the first node and .getTextContent() will get the text content inside.

Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters
}

Then using jackson:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));



private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

Why is super.super.method(); not allowed in Java?

It violates encapsulation. You shouldn't be able to bypass the parent class's behaviour. It makes sense to sometimes be able to bypass your own class's behaviour (particularly from within the same method) but not your parent's. For example, suppose we have a base "collection of items", a subclass representing "a collection of red items" and a subclass of that representing "a collection of big red items". It makes sense to have:

public class Items
{
    public void add(Item item) { ... }
}

public class RedItems extends Items
{
    @Override
    public void add(Item item)
    {
        if (!item.isRed())
        {
            throw new NotRedItemException();
        }
        super.add(item);
    }
}

public class BigRedItems extends RedItems
{
    @Override
    public void add(Item item)
    {
        if (!item.isBig())
        {
            throw new NotBigItemException();
        }
        super.add(item);
    }
}

That's fine - RedItems can always be confident that the items it contains are all red. Now suppose we were able to call super.super.add():

public class NaughtyItems extends RedItems
{
    @Override
    public void add(Item item)
    {
        // I don't care if it's red or not. Take that, RedItems!
        super.super.add(item);
    }
}

Now we could add whatever we like, and the invariant in RedItems is broken.

Does that make sense?

Vim: How to insert in visual block mode?

if you want to add new text before or after the selected colum:

  • press ctrl+v
  • select columns
  • press shift+i
  • write your text
  • press esc
  • press "jj"

Create a <ul> and fill it based on a passed array

What are disadvantages of the following solution? Seems to be faster and shorter.

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

How to add a border just on the top side of a UIView

Inspired by @Addison I've rewritten the extension without the use of any third party framework, as he used SnapKit and CocoaLumberjack.

As in @Addisons approach I'm also removing previously added borders, so this implementation should play nice with reusable views as table cells and collection cells.

fileprivate class BorderView: UIView {} // dummy class to help us differentiate among border views and other views
                                        // to enabling us to remove existing borders and place new ones

extension UIView {

    func setBorders(toEdges edges: [UIRectEdge], withColor color: UIColor, inset: CGFloat = 0, thickness: CGFloat) {
        // Remove existing edges
        for view in subviews {
            if view is BorderView {
                view.removeFromSuperview()
            }
        }
        // Add new edges
        if edges.contains(.all) {
            addSidedBorder(toEdge: [.left,.right, .top, .bottom], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.left) {
            addSidedBorder(toEdge: [.left], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.right) {
            addSidedBorder(toEdge: [.right], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.top) {
            addSidedBorder(toEdge: [.top], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.bottom) {
            addSidedBorder(toEdge: [.bottom], withColor: color, inset: inset, thickness: thickness)
        }
    }

    private func addSidedBorder(toEdge edges: [RectangularEdges], withColor color: UIColor, inset: CGFloat = 0, thickness: CGFloat) {
        for edge in edges {
            let border = BorderView(frame: .zero)
            border.backgroundColor = color
            addSubview(border)
            border.translatesAutoresizingMaskIntoConstraints = false
            switch edge {
            case .left:
                NSLayoutConstraint.activate([
                border.leftAnchor.constraint(equalTo: self.leftAnchor, constant: inset),
                    border.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
                    border.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset),
                    NSLayoutConstraint(item: border, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: thickness) ])
            case .right:
                NSLayoutConstraint.activate([
                    border.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -inset),
                    border.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
                    border.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset),
                    NSLayoutConstraint(item: border, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: thickness) ])
            case .top:
                NSLayoutConstraint.activate([
                    border.leftAnchor.constraint(equalTo: self.leftAnchor, constant: inset),
                    border.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -inset),
                    border.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
                    NSLayoutConstraint(item: border, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: thickness) ])
            case .bottom:
                NSLayoutConstraint.activate([
                    border.leftAnchor.constraint(equalTo: self.leftAnchor, constant: inset),
                    border.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -inset),
                    border.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset),
                    NSLayoutConstraint(item: border, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: thickness) ])
            }
        }
    }

    private enum RectangularEdges {
        case left
        case right
        case top
        case bottom
    }
}

How to set a transparent background of JPanel?

 public void paintComponent (Graphics g)
    { 
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.0f)); // draw transparent background
     super.paintComponent(g);
    ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f)); // turn on opacity
    g.setColor(Color.RED);
    g.fillRect(20, 20, 500, 300);
     } 

I have tried to do it this way, but it is very flickery

SQL Server: Query fast, but slow from procedure

I found the problem, here's the script of the slow and fast versions of the stored procedure:

dbo.ViewOpener__RenamedForCruachan__Slow.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
    @SessionGUID uniqueidentifier
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

dbo.ViewOpener__RenamedForCruachan__Fast.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
    @SessionGUID uniqueidentifier 
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:

Slow: SET ANSI_NULLS OFF

Fast: SET ANSI_NULLS ON


This answer also could be made to make sense, since the view does have a join clause that says:

(table.column IS NOT NULL)

So there is some NULLs involved.


The explanation is further proved by returning to Query Analizer, and running

SET ANSI_NULLS OFF

.

DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'

.

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank

And the query is slow.


So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.

Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:

Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....

How to check if all inputs are not empty with jQuery

$('#form_submit_btn').click(function(){
    $('input').each(function() {
        if(!$(this).val()){
            alert('Some fields are empty');
           return false;
        }
    });
});

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

How to obtain the last path segment of a URI

is that what you are looking for:

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);

alternatively

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);

Double array initialization in Java

You can initialize an array by writing actual values it holds in curly braces on the right hand side like:

String[] strArr = { "one", "two", "three"};
int[] numArr = { 1, 2, 3};

In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:

String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} };

Your example shows exactly that

double m[][] = {
    {0*0,1*0,2*0,3*0},
    {0*1,1*1,2*1,3*1},
    {0*2,1*2,2*2,3*2},
    {0*3,1*3,2*3,3*3}
};

But also the multiplication of number will also be performed and its the same as:

double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} };

JavaScript get clipboard data on paste event (Cross browser)

Solution #1 (Plain Text only and requires Firefox 22+)

Works for IE6+, FF 22+, Chrome, Safari, Edge (Only tested in IE9+, but should work for lower versions)

If you need support for pasting HTML or Firefox <= 22, see Solution #2.

HTML

<div id='editableDiv' contenteditable='true'>Paste</div>

JavaScript

function handlePaste (e) {
    var clipboardData, pastedData;

    // Stop data actually being pasted into div
    e.stopPropagation();
    e.preventDefault();

    // Get pasted data via clipboard API
    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData('Text');
    
    // Do whatever with pasteddata
    alert(pastedData);
}

document.getElementById('editableDiv').addEventListener('paste', handlePaste);

JSFiddle: https://jsfiddle.net/swL8ftLs/12/

Note that this solution uses the parameter 'Text' for the getData function, which is non-standard. However, it works in all browsers at the time of writing.


Solution #2 (HTML and works for Firefox <= 22)

Tested in IE6+, FF 3.5+, Chrome, Safari, Edge

HTML

<div id='div' contenteditable='true'>Paste</div>

JavaScript

var editableDiv = document.getElementById('editableDiv');

function handlepaste (e) {
    var types, pastedData, savedContent;
    
    // Browsers that support the 'text/html' type in the Clipboard API (Chrome, Firefox 22+)
    if (e && e.clipboardData && e.clipboardData.types && e.clipboardData.getData) {
            
        // Check for 'text/html' in types list. See abligh's answer below for deatils on
        // why the DOMStringList bit is needed. We cannot fall back to 'text/plain' as
        // Safari/Edge don't advertise HTML data even if it is available
        types = e.clipboardData.types;
        if (((types instanceof DOMStringList) && types.contains("text/html")) || (types.indexOf && types.indexOf('text/html') !== -1)) {
        
            // Extract data and pass it to callback
            pastedData = e.clipboardData.getData('text/html');
            processPaste(editableDiv, pastedData);

            // Stop the data from actually being pasted
            e.stopPropagation();
            e.preventDefault();
            return false;
        }
    }
    
    // Everything else: Move existing element contents to a DocumentFragment for safekeeping
    savedContent = document.createDocumentFragment();
    while(editableDiv.childNodes.length > 0) {
        savedContent.appendChild(editableDiv.childNodes[0]);
    }
    
    // Then wait for browser to paste content into it and cleanup
    waitForPastedData(editableDiv, savedContent);
    return true;
}

function waitForPastedData (elem, savedContent) {

    // If data has been processes by browser, process it
    if (elem.childNodes && elem.childNodes.length > 0) {
    
        // Retrieve pasted content via innerHTML
        // (Alternatively loop through elem.childNodes or elem.getElementsByTagName here)
        var pastedData = elem.innerHTML;
        
        // Restore saved content
        elem.innerHTML = "";
        elem.appendChild(savedContent);
        
        // Call callback
        processPaste(elem, pastedData);
    }
    
    // Else wait 20ms and try again
    else {
        setTimeout(function () {
            waitForPastedData(elem, savedContent)
        }, 20);
    }
}

function processPaste (elem, pastedData) {
    // Do whatever with gathered data;
    alert(pastedData);
    elem.focus();
}

// Modern browsers. Note: 3rd argument is required for Firefox <= 6
if (editableDiv.addEventListener) {
    editableDiv.addEventListener('paste', handlepaste, false);
}
// IE <= 8
else {
    editableDiv.attachEvent('onpaste', handlepaste);
}

JSFiddle: https://jsfiddle.net/nicoburns/wrqmuabo/23/

Explanation

The onpaste event of the div has the handlePaste function attached to it and passed a single argument: the event object for the paste event. Of particular interest to us is the clipboardData property of this event which enables clipboard access in non-ie browsers. In IE the equivalent is window.clipboardData, although this has a slightly different API.

See resources section below.


The handlepaste function:

This function has two branches.

The first checks for the existence of event.clipboardData and checks whether it's types property contains 'text/html' (types may be either a DOMStringList which is checked using the contains method, or a string which is checked using the indexOf method). If all of these conditions are fulfilled, then we proceed as in solution #1, except with 'text/html' instead of 'text/plain'. This currently works in Chrome and Firefox 22+.

If this method is not supported (all other browsers), then we

  1. Save the element's contents to a DocumentFragment
  2. Empty the element
  3. Call the waitForPastedData function

The waitforpastedata function:

This function first polls for the pasted data (once per 20ms), which is necessary because it doesn't appear straight away. When the data has appeared it:

  1. Saves the innerHTML of the editable div (which is now the pasted data) to a variable
  2. Restores the content saved in the DocumentFragment
  3. Calls the 'processPaste' function with the retrieved data

The processpaste function:

Does arbitrary things with the pasted data. In this case we just alert the data, you can do whatever you like. You will probably want to run the pasted data through some kind of data sanitising process.


Saving and restoring the cursor position

In a real sitution you would probably want to save the selection before, and restore it afterwards (Set cursor position on contentEditable <div>). You could then insert the pasted data at the position the cursor was in when the user initiated the paste action.

Resources:

Thanks to Tim Down to suggesting the use of a DocumentFragment, and abligh for catching an error in Firefox due to the use of DOMStringList instead of a string for clipboardData.types

How can I divide two integers to get a double?

var result = decimal.ToDouble(decimal.Divide(5, 2));

How do I get the "id" after INSERT into MySQL database with Python?

Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...

id = cursor.lastrowid

...should work too, and it's per-connection based obviously.

How to display a date as iso 8601 format with PHP

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

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

The easiest way is to make a "fake show" by using jquery.

element.delay(1000).fadeIn(0); // This will work

How do I open a second window from the first window in WPF?

You can use this code:

private void OnClickNavigate(object sender, RoutedEventArgs e)
{
    NavigatedWindow navigatesWindow = new NavigatedWindow();
    navigatesWindow.ShowDialog();
}

Python iterating through object attributes

You can use the standard Python idiom, vars():

for attr, value in vars(k).items():
    print(attr, '=', value)

What is jQuery Unobtrusive Validation?

jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).

Correct way to handle conditional styling in React

 <div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>

Checkout the above code. That will do the trick.

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

Have a div cling to top of screen if scrolled down past it

The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.

Derived from the code viixii.com uses I ended up using this:

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top)
        $('#sticky-element').addClass('sticky');
    else
        $('#sticky-element').removeClass('sticky');
}

$(function() {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.

Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.

Just place an empty div with a class acting like an anchor just above the element you want to have fixed.

Like so:

<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>

All credit for the code goes to viixii.com

Background color in input and text fields

You want to restrict to input fields that are of type text so use the selector input[type=text] rather than input (which will apply to all input fields (e.g. those of type submit as well)).

Beautiful Soup and extracting a div and its contents by ID

have you tried soup.findAll("div", {"id": "articlebody"})?

sounds crazy, but if you're scraping stuff from the wild, you can't rule out multiple divs...

How do I use valgrind to find memory leaks?

You can create an alias in .bashrc file as follows

alias vg='valgrind --leak-check=full -v --track-origins=yes --log-file=vg_logfile.out'

So whenever you want to check memory leaks, just do simply

vg ./<name of your executable> <command line parameters to your executable>

This will generate a Valgrind log file in the current directory.

custom facebook share button

This solution is using javascript to open a new window when a user clicks on your custom share button.

HTML:

<a href="#" onclick="share_fb('http://urlhere.com/test/55d7258b61707022e3050000');return false;" rel="nofollow" share_url="http://urlhere.com/test/55d7258b61707022e3050000" target="_blank">

  //using fontawesome
  <i class="uk-icon-facebook uk-float-left"></i>
    Share
</a>

and in your javascript file. note window.open params are (url, dialogue title, width, height)

function share_fb(url) {
  window.open('https://www.facebook.com/sharer/sharer.php?u='+url,'facebook-share-dialog',"width=626, height=436")
}

How to calculate Date difference in Hive

I would try this first

select * from employee where month(current_date)-3 = month(joining_date)

Make Axios send cookies in its requests automatically

You can use withCredentials property to pass cookies in the request.

axios.get(`api_url`, { withCredentials: true })

By setting { withCredentials: true } you may encounter cross origin issue. To solve that you need to use

expressApp.use(cors({ credentials: true, origin: "http://localhost:8080" }));

Here you can read about withCredentials

Capture event onclose browser

Men, use this:

if(myWindow.closed){
    callback();
    return;
}

Remove spacing between table cells and rows

Add border-collapse: collapse into the style attribute value of the inner table element. You could alternatively add the attribute cellspacing=0 there, but then you would have a double border between the cells.

I.e.:

<table class="main-story-image" style="float: left; width: 180px; margin: 0 25px 25px 25px; border-collapse: collapse">

Get parent directory of running script

I hope this will help

function get_directory(){
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol . "://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
}
define("ROOT_PATH", get_directory()."/" );
echo ROOT_PATH;

.htaccess not working apache

I cleared this use. By using this site click Here , follow the steps, the same steps follows upto the ubuntu version 18.04

How can I wrap or break long text/word in a fixed width span?

By default a span is an inline element... so that's not the default behavior.

You can make the span behave that way by adding display: block; to your CSS.

span {
    display: block;
    width: 100px;
}

Palindrome check in Javascript

Recursive Method:

var low;
var high;
var A = "abcdcba";  

function palindrome(A , low, high){
  A = A.split('');

 if((low > high) || (low == high)){
   return true;
 }

 if(A[low] === A[high]){
   A = A.join('');
   low = low + 1; 
   high = high - 1; 
   return palindrome(A , low, high);
 }
 else{
   return "not a palindrome";
 }
}

palindrome(A, 0, A.length-1);

Row count on the Filtered data

I have found a way to do this that it requires 2 steps, but it works

' to copy out a filtered selection into a different sheet


number_of_dinosaurs = WorksheetFunction.Count(Worksheets("Dinosaurs").Range("A2", "A3000"))

With Worksheets("Dinosaurs")
    .AutoFilterMode = False
    With .Range("$A$4:$E$" & number_of_dinosaurs)
        .AutoFilter Field:=2, Criteria1:="*teeth*" ' change your criteria to whatever you like
        .SpecialCells(xlCellTypeVisible).Copy Destination:=Worksheets("Bad_Dinosaurs").Range("A1")
    End With
End With


' then do a normal count on the secondary sheet  

number_of_dinosaurs_that_eat_humans = WorksheetFunction.Count(Worksheets("Bad_Dinosaurs").Range("A2", "A30000"))

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

How to install a node.js module without using npm?

Step-by-step:

  • let's say you are working on a project use-gulp which uses(requires) node_modules like gulp and gulp-util.
  • Now you want to make some modifications to gulp-util lib and test it locally with your use-gulp project...
  • Fork gulp-util project on github\bitbucket etc.
  • Switch to your project: cd use-gulp/node_modules
  • Clone gulp-util as gulp-util-dev : git clone https://.../gulp-util.git gulp-util-dev
  • Run npm install to ensure dependencies of gulp-util-dev are available.
  • Now you have a mirror of gulp-util as gulp-util-dev. In your use-gulp project, you can now replace: require('gulp-util')...; call with : require('gulp-util-dev') to test your changes you made to gulp-util-dev

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

Traverse a list in reverse order in Python

An expressive way to achieve reverse(enumerate(collection)) in python 3:

zip(reversed(range(len(collection))), reversed(collection))

in python 2:

izip(reversed(xrange(len(collection))), reversed(collection))

I'm not sure why we don't have a shorthand for this, eg.:

def reversed_enumerate(collection):
    return zip(reversed(range(len(collection))), reversed(collection))

or why we don't have reversed_range()

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

The problem is that you mapped your servlet to /register.html and it expects POST method, because you implemented only doPost() method. So when you open register.html page, it will not open html page with the form but servlet that handles the form data.

Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).

To fix:

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

How can I get my webapp's base URL in ASP.NET MVC?

You could have a static method that looks at HttpContext.Current and decides which URL to use (development or live server) depending on the host ID. HttpContext might even offer some easier way to do it, but this is the first option I found and it works fine.

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

Find the differences between 2 Excel worksheets?

SO in fact that you are using excel means that you can use the SpreadSheet Compare from Microsoft. It is available from Office 2013. Yes i know this question is older then 6 years. But who knows maybe someone need this information today.

How to pass a datetime parameter?

I feel your pain ... yet another date time format... just what you needed!

Using Web Api 2 you can use route attributes to specify parameters.

so with attributes on your class and your method you can code up a REST URL using this utc format you are having trouble with (apparently its ISO8601, presumably arrived at using startDate.toISOString())

[Route(@"daterange/{startDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}/{endDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange(DateTime startDate, DateTime endDate)

.... BUT, although this works with one date (startDate), for some reason it doesnt work when the endDate is in this format ... debugged for hours, only clue is exception says it doesnt like colon ":" (even though web.config is set with :

<system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" requestPathInvalidCharacters="" />
</system.web>

So, lets make another date format (taken from the polyfill for the ISO date format) and add it to the Javascript date (for brevity, only convert up to minutes):

if (!Date.prototype.toUTCDateTimeDigits) {
    (function () {

        function pad(number) {
            if (number < 10) {
                return '0' + number;
            }
            return number;
        }

        Date.prototype.toUTCDateTimeDigits = function () {
            return this.getUTCFullYear() +
              pad(this.getUTCMonth() + 1) +
              pad(this.getUTCDate()) +
              'T' +
              pad(this.getUTCHours()) +
              pad(this.getUTCMinutes()) +
              'Z';
        };

    }());
}

Then when you send the dates to the Web API 2 method, you can convert them from string to date:

[RoutePrefix("api/myrecordtype")]
public class MyRecordTypeController : ApiController
{


    [Route(@"daterange/{startDateString}/{endDateString}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange([FromUri]string startDateString, [FromUri]string endDateString)
    {
        var startDate = BuildDateTimeFromYAFormat(startDateString);
        var endDate = BuildDateTimeFromYAFormat(endDateString);
    ...
    }

    /// <summary>
    /// Convert a UTC Date String of format yyyyMMddThhmmZ into a Local Date
    /// </summary>
    /// <param name="dateString"></param>
    /// <returns></returns>
    private DateTime BuildDateTimeFromYAFormat(string dateString)
    {
        Regex r = new Regex(@"^\d{4}\d{2}\d{2}T\d{2}\d{2}Z$");
        if (!r.IsMatch(dateString))
        {
            throw new FormatException(
                string.Format("{0} is not the correct format. Should be yyyyMMddThhmmZ", dateString)); 
        }

        DateTime dt = DateTime.ParseExact(dateString, "yyyyMMddThhmmZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

        return dt;
    }

so the url would be

http://domain/api/myrecordtype/daterange/20140302T0003Z/20140302T1603Z

Hanselman gives some related info here:

http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

How to handle onchange event on input type=file in jQuery?

 $('#fileupload').bind('change', function (e) { //dynamic property binding
alert('hello');// message you want to display
});

You can use this one also

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Vlookup is good if the reference values (column A, sheet 1) are in ascending order. Another option is Index and Match, which can be used no matter the order (As long as the values in column a, sheet 1 are unique)

This is what you would put in column B on sheet 2

=INDEX(Sheet1!A$1:B$6,MATCH(A1,Sheet1!A$1:A$6),2)

Setting Sheet1!A$1:B$6 and Sheet1!A$1:A$6 as named ranges makes it a little more user friendly.

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

Persistent invalid graphics state error when using ggplot2

I ran into this same error and solved it by running:

dev.off()

and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.

Iterate through a HashMap

If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).

Is a LINQ statement faster than a 'foreach' loop?

It should probably be noted that the for loop is faster than the foreach. So for the original post, if you are worried about performance on a critical component like a renderer, use a for loop.

Reference: In .NET, which loop runs faster, 'for' or 'foreach'?

Allow user to select camera or gallery for image

Adding my solution - it will return a callback whether it is from the camera or from the galley alongside the intent:

public class ImagePickerManager extends BaseAdapter {

private List<ResolveInfo> mApplications;
private TreeSet<Integer> mImageCaptureIntents;
private TreeSet<Integer> mImagePickerIntents;
private Context mContext;
private final ImagePickerManagerListener listener;

private static enum intentType {
    choosePhoto,
    takePhoto,
    unknown;

    public int getIntValue() {
        switch (this) {
            case choosePhoto:
                return 0;
            case takePhoto:
                return 1;
            case unknown:
                return 2;
        }
        return 0;
    }
}

public interface ImagePickerManagerListener {
    void onChooseImage(Intent intent);
    void onCaptureImage(Intent intent);
}

public ImagePickerManager(Context context,ImagePickerManagerListener listenr) {
    this.mContext = context;
    this.listener = listenr;

    mImageCaptureIntents = new TreeSet<>();
    mImagePickerIntents = new TreeSet<>();

    //Picking photo intent
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    mApplications = mContext.getPackageManager().queryIntentActivities(intent, 0);

    int index = 0;
    for (int i = 0; i < mApplications.size(); i++) {
        mImagePickerIntents.add(index);
        index++;
    }

    //Capture photo intent
    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    List<ResolveInfo> resolveInfoList = mContext.getPackageManager().queryIntentActivities(intent, 0);
    mApplications.addAll(resolveInfoList);
    for (int i = 0; i < mApplications.size(); i++) {
        mImageCaptureIntents.add(index);
        index++;
    }
}

public static void openChooseAndCaptureImageDialog(final Context context, final ImagePickerManagerListener listener) {

    Log.d("openChooseAndCaptureImageDialog", "enter");

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    final ImagePickerManager imagePickerManager = new ImagePickerManager(context,listener);
    builder.setTitle(context.getString(R.string.image_picker_dialog_box_title));
    builder.setAdapter(imagePickerManager, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialoginterface, int i) {
            ResolveInfo resolveInfo = (ResolveInfo) imagePickerManager.getItem(i);
            Intent pickerIntent = imagePickerManager.getIntentForPackage(context,resolveInfo,i);
            switch (imagePickerManager.getIntentType(i)){
                case choosePhoto:
                    listener.onChooseImage(pickerIntent);
                    break;
                case takePhoto:
                    listener.onCaptureImage(pickerIntent);
                    break;
                case unknown:
                    break;
            }
        }
    });

    builder.setCancelable(true);
    builder.setInverseBackgroundForced(true);
    AlertDialog dialog = builder.create();
    dialog.show();
}


private intentType getIntentType(int index) {

    if (mImageCaptureIntents.contains(index)) {
       return intentType.takePhoto;
    } else if(mImagePickerIntents.contains(index)) {
        return intentType.choosePhoto;
    }
    return intentType.unknown;
}

private Intent getIntentForPackage(Context context, ResolveInfo info,int index) {
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(info.activityInfo.packageName);

    ComponentName chosenName = new ComponentName(
            info.activityInfo.packageName,
            info.activityInfo.name);

    intent.setComponent(chosenName);
    intent.setFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
    if (mImageCaptureIntents.contains(index)) {
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    } else if(mImagePickerIntents.contains(index)) {
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
    }
    return intent;
}

@Override
public int getCount() {
    return mApplications.size();
}

@Override
public Object getItem(int position) {
    return mApplications.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ResolveInfo item = mApplications.get(position);
    if (convertView == null) {
        TextView applicationTextView = new TextView(mContext);
        LayoutParams param = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        applicationTextView.setLayoutParams(param);
        final int horizontalPadding = (int) FVRGeneralUtils.convertDpToPx(mContext, 15);
        final int verticalPadding = (int) FVRGeneralUtils.convertDpToPx(mContext, 5);
        applicationTextView.setPadding(horizontalPadding,verticalPadding, horizontalPadding, verticalPadding);
        applicationTextView.setGravity(android.view.Gravity.CENTER_VERTICAL);
        Resources.Theme th = mContext.getTheme();
        TypedValue tv = new TypedValue();

        if (th.resolveAttribute(android.R.attr.textAppearanceMedium, tv, true)) {
            applicationTextView.setTextAppearance(mContext, tv.resourceId);
        }

        applicationTextView.setMinHeight((int) FVRGeneralUtils.convertDpToPx(mContext, 25));
        applicationTextView.setCompoundDrawablePadding((int) FVRGeneralUtils.convertDpToPx(mContext, 7));
        convertView = applicationTextView;
    }

    TextView textView = (TextView) convertView;
    textView.setText(item.loadLabel(mContext.getPackageManager()));
    textView.setCompoundDrawablesWithIntrinsicBounds(item.loadIcon(mContext.getPackageManager()), null, null, null);
    return textView;
} }

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with

for (const field of Object.keys(this.formErrors)) {

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

You can covert numpy.ndarray to object using astype(object)

This will work:

>>> a = [np.zeros((224,224,3)).astype(object), np.zeros((224,224,3)).astype(object), np.zeros((224,224,13)).astype(object)]

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How can I add an element after another element?

try

.insertAfter()

here

$(content).insertAfter('#bla');

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance :

TL;DR

Use isInstance or instanceof which have similar performance. isAssignableFrom is slightly slower.

Sorted by performance:

  1. isInstance
  2. instanceof (+ 0.5%)
  3. isAssignableFrom (+ 2.7%)

Based on a benchmark of 2000 iterations on JAVA 8 Windows x64, with 20 warmup iterations.

In theory

Using a soft like bytecode viewer we can translate each operator into bytecode.

In the context of:

package foo;

public class Benchmark
{
  public static final Object a = new A();
  public static final Object b = new B();

  ...

}

JAVA:

b instanceof A;

Bytecode:

getstatic foo/Benchmark.b:java.lang.Object
instanceof foo/A

JAVA:

A.class.isInstance(b);

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Class isInstance((Ljava/lang/Object;)Z);

JAVA:

A.class.isAssignableFrom(b.getClass());

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Object getClass(()Ljava/lang/Class;);
invokevirtual java/lang/Class isAssignableFrom((Ljava/lang/Class;)Z);

Measuring how many bytecode instructions are used by each operator, we could expect instanceof and isInstance to be faster than isAssignableFrom. However, the actual performance is NOT determined by the bytecode but by the machine code (which is platform dependent). Let's do a micro benchmark for each of the operators.

The benchmark

Credit: As advised by @aleksandr-dubinsky, and thanks to @yura for providing the base code, here is a JMH benchmark (see this tuning guide):

class A {}
class B extends A {}

public class Benchmark {

    public static final Object a = new A();
    public static final Object b = new B();

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testInstanceOf()
    {
        return b instanceof A;
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsInstance()
    {
        return A.class.isInstance(b);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsAssignableFrom()
    {
        return A.class.isAssignableFrom(b.getClass());
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(TestPerf2.class.getSimpleName())
                .warmupIterations(20)
                .measurementIterations(2000)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}

Gave the following results (score is a number of operations in a time unit, so the higher the score the better):

Benchmark                       Mode   Cnt    Score   Error   Units
Benchmark.testIsInstance        thrpt  2000  373,061 ± 0,115  ops/us
Benchmark.testInstanceOf        thrpt  2000  371,047 ± 0,131  ops/us
Benchmark.testIsAssignableFrom  thrpt  2000  363,648 ± 0,289  ops/us

Warning

  • the benchmark is JVM and platform dependent. Since there are no significant differences between each operation, it might be possible to get a different result (and maybe different order!) on a different JAVA version and/or platforms like Solaris, Mac or Linux.
  • the benchmark compares the performance of "is B an instance of A" when "B extends A" directly. If the class hierarchy is deeper and more complex (like B extends X which extends Y which extends Z which extends A), results might be different.
  • it is usually advised to write the code first picking one of the operators (the most convenient) and then profile your code to check if there are a performance bottleneck. Maybe this operator is negligible in the context of your code, or maybe...
  • in relation to the previous point, instanceof in the context of your code might get optimized more easily than an isInstance for example...

To give you an example, take the following loop:

class A{}
class B extends A{}

A b = new B();

boolean execute(){
  return A.class.isAssignableFrom(b.getClass());
  // return A.class.isInstance(b);
  // return b instanceof A;
}

// Warmup the code
for (int i = 0; i < 100; ++i)
  execute();

// Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
   execute();
}
final long elapsed = System.nanoTime() - start;

Thanks to the JIT, the code is optimized at some point and we get:

  • instanceof: 6ms
  • isInstance: 12ms
  • isAssignableFrom : 15ms

Note

Originally this post was doing its own benchmark using a for loop in raw JAVA, which gave unreliable results as some optimization like Just In Time can eliminate the loop. So it was mostly measuring how long did the JIT compiler take to optimize the loop: see Performance test independent of the number of iterations for more details

Related questions

What is Dependency Injection?

Dependency Injection means a way (actually any-way) for one part of code (e.g a class) to have access to dependencies (other parts of code, e.g other classes, it depends upon) in a modular way without them being hardcoded (so they can change or be overriden freely, or even be loaded at another time, as needed)

(and ps , yes it has become an overly-hyped 25$ name for a rather simple, concept), my .25 cents

How to Initialize char array from a string

Another option is to use sprintf.

For example,

char buffer[50];
sprintf( buffer, "My String" );

Good luck.

How can a Javascript object refer to values in itself?

One alternative would be to use a getter/setter methods.

For instance, if you only care about reading the calculated value:

var book  = {}

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true },
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + " works!";
        }
    }
});

console.log(book.key2); //prints "it works!"

The above code, though, won't let you define another value for key2.

So, the things become a bit more complicated if you would like to also redefine the value of key2. It will always be a calculated value. Most likely that's what you want.

However, if you would like to be able to redefine the value of key2, then you will need a place to cache its value independently of the calculation.

Somewhat like this:

var book  = { _key2: " works!" }

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true},
    _key2: { enumerable: false},
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + this._key2;
        },
        set: function(newValue){
            this._key2 = newValue;
        }
    }
});

console.log(book.key2); //it works!

book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!

for(var key in book){
    //prints both key1 and key2, but not _key2
    console.log(key + ":" + book[key]); 
}

Another interesting alternative is to use a self-initializing object:

var obj = ({
  x: "it",
  init: function(){
    this.y = this.x + " works!";
    return this;
  }
}).init();

console.log(obj.y); //it works!

How do I send a file in Android from a mobile device to server using http?

the most effective method is to use android-async-http

You can use this code to upload a file:

// gather your request parameters
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
    params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

// send request
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
        // handle success response
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
        // handle failure response
    }
});

Note that you can put this code directly into your main Activity, no need to create a background Task explicitly. AsyncHttp will take care of that for you!

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

.NET code to send ZPL to Zebra printers

I've managed a project that does this with sockets for years. Zebra's typically use port 6101. I'll look through the code and post what I can.

public void SendData(string zpl)
{
    NetworkStream ns = null;
    Socket socket = null;

    try
    {
        if (printerIP == null)
        {
            /* IP is a string property for the printer's IP address. */
            /* 6101 is the common port of all our Zebra printers. */
            printerIP = new IPEndPoint(IPAddress.Parse(IP), 6101);  
        }

        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp);
        socket.Connect(printerIP);

        ns = new NetworkStream(socket);

        byte[] toSend = Encoding.ASCII.GetBytes(zpl);
        ns.Write(toSend, 0, toSend.Length);
    }
    finally
    {
        if (ns != null)
            ns.Close();

        if (socket != null && socket.Connected)
            socket.Close();
    }
}

Auto submit form on page load

This is the way it worked for me, because with other methods the form was sent empty:

<form name="yourform" id="yourform" method="POST" action="yourpage.html">
    <input type=hidden name="data" value="yourdata">
    <input type="submit" id="send" name="send" value="Send">
</form>
<script>            
    document.addEventListener("DOMContentLoaded", function(event) {
            document.createElement('form').submit.call(document.getElementById('yourform'));
            });         
</script>

Chrome DevTools Devices does not detect device when plugged in

On a Galaxy S7 and Windows 10 laptop, all I had to do whilst connected to the computer was change the USB connection mode to "Audio Source" (Phone Settings > Developer Options > USB Configuration).

This then immediately came up with the on-device prompt to allow the RSA key fingerprint. Then the dev tools on computer recognised my device.

Why this works I do not know, however it is by far the simplest of solutions, and without the need for installing unnecessary software.

I have also had some luck changing it to "MTP (Media Transfer Protocol)" mode too, but only on occasion.

Edit:

The MTP option no longer works for me.

In addition to Audio Source, setting the connection mode to MIDI also works. It is alot easier to change the connection mode by accessing it straight from the device's notification bar - Tap the "Transferring media files via USB" or the equivalent notification.

Using MIDI is probably the easiest of the two since it doesn't require going into several setting screens to access it.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

@Xander's solution works, but does not persist after a reboot.

I found that I had to change listen.mode to 0660 in /etc/php5/fpm/pool.d/www.conf.

Sample from www.conf:

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0660
;listen.owner = www-data
;listen.group = www-data
;listen.mode = 0660

Edit: Per @Chris Burgess, I've changed this to the more secure method.

I removed the comment for listen.mode, .group and .owner:

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

/var/run Only holds information about the running system since last boot, e.g., currently logged-in users and running daemons. (http://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard#Directory_structure).

Side note:

My php5-fpm -v Reports: PHP 5.4.28-1+deb.sury.org~precise+1. The issue did happen after a recent update as well.

Event when window.location.href changes

Well there is 2 ways to change the location.href. Either you can write location.href = "y.html", which reloads the page or can use the history API which does not reload the page. I experimented with the first a lot recently.

If you open a child window and capture the load of the child page from the parent window, then different browsers behave very differently. The only thing that is common, that they remove the old document and add a new one, so for example adding readystatechange or load event handlers to the old document does not have any effect. Most of the browsers remove the event handlers from the window object too, the only exception is Firefox. In Chrome with Karma runner and in Firefox you can capture the new document in the loading readyState if you use unload + next tick. So you can add for example a load event handler or a readystatechange event handler or just log that the browser is loading a page with a new URI. In Chrome with manual testing (probably GreaseMonkey too) and in Opera, PhantomJS, IE10, IE11 you cannot capture the new document in the loading state. In those browsers the unload + next tick calls the callback a few hundred msecs later than the load event of the page fires. The delay is typically 100 to 300 msecs, but opera simetime makes a 750 msec delay for next tick, which is scary. So if you want a consistent result in all browsers, then you do what you want to after the load event, but there is no guarantee the location won't be overridden before that.

var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");


var callBacks = [];
var uglyHax = function (){
    var done = function (){
        uglyHax();
        callBacks.forEach(function (cb){
            cb();
        });
    };
    win.addEventListener("unload", function unloadListener(){
        win.removeEventListener("unload", unloadListener); // Firefox remembers, other browsers don't
        setTimeout(function (){
            // IE10, IE11, Opera, PhantomJS, Chrome has a complete new document at this point
            // Chrome on Karma, Firefox has a loading new document at this point
            win.document.readyState; // IE10 and IE11 sometimes fails if I don't access it twice, idk. how or why
            if (win.document.readyState === "complete")
                done();
            else
                win.addEventListener("load", function (){
                    setTimeout(done, 0);
                });
        }, 0);
    });
};
uglyHax();


callBacks.push(function (){
    console.log("cb", win.location.href, win.document.readyState);
    if (win.location.href !== "http://localhost:4444/y.html")
        win.location.href = "http://localhost:4444/y.html";
    else
        console.log("done");
});
win.location.href = "http://localhost:4444/x.html";

If you run your script only in Firefox, then you can use a simplified version and capture the document in a loading state, so for example a script on the loaded page cannot navigate away before you log the URI change:

var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");


var callBacks = [];
win.addEventListener("unload", function unloadListener(){
    setTimeout(function (){
        callBacks.forEach(function (cb){
            cb();
        });
    }, 0);
});


callBacks.push(function (){
    console.log("cb", win.location.href, win.document.readyState);
    // be aware that the page is in loading readyState, 
    // so if you rewrite the location here, the actual page will be never loaded, just the new one
    if (win.location.href !== "http://localhost:4444/y.html")
        win.location.href = "http://localhost:4444/y.html";
    else
        console.log("done");
});
win.location.href = "http://localhost:4444/x.html";

If we are talking about single page applications which change the hash part of the URI, or use the history API, then you can use the hashchange and the popstate events of the window respectively. Those can capture even if you move in history back and forward until you stay on the same page. The document does not changes by those and the page is not really reloaded.

How do I find the mime-type of a file with php?

The mime of any file on your server can be gotten with this

<?php
function get_mime($file_path){
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  $type  = $finfo->file(file_path);
}

$mime = get_mime('path/to/file.ext');

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

Why doesn't java.util.Set have get(int index)?

Please note only 2 basic data structure can be accessed via index.

  • Array data structure can be accessed via index with O(1) time complexity to achieve get(int index) operation.
  • LinkedList data structure can also be accessed via index, but with O(n) time complexity to achieve get(int index) operation.

In Java, ArrayList is implemented using Array data structure.

While Set data structure usually can be implemented via HashTable/HashMap or BalancedTree data structure, for fast detecting whether an element exists and add non-existing element, usually a well implemented Set can achieve O(1) time complexity contains operation. In Java, HashSet is the most common used implementation of Set, it is implemented by calling HashMap API, and HashMap is implemented using separate chaining with linked lists (a combination of Array and LinkedList).

Since Set can be implemented via different data structure, there is no get(int index) method for it.

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

(HTML) Download a PDF file instead of opening them in browser when clicked

You can't do this with HTML. It's a server-based solution. You have to stream the file so that the browser than triggers the save dialog.

I'd advise not doing this. How a user interacts with a PDF should be left up to the user.

UPDATE (2014):

So...this answer still gets plenty of downvotes. I assume part of that is that this was answered 4 years ago and as Sarim points out, there is now the HTML 5 download attribute that can handle this.

I agree, and think Sarim's answer is good (it probably should be the chosen answer if the OP ever returns). However, this answer is still the reliable way to handle it (as Yigit Yener's answer points out and--oddly--people agree with). While the download attribute has gained support, it's still spotty:

http://caniuse.com/#feat=download

How to type a new line character in SQL Server Management Studio

Ronnie,

The data grid appears to be swallowing any attempts to paste a newline character, including the use of ALT+010. Microsoft does not list any shortcut keys that would help. The usual suspects

<ctrl>enter, 
<alt> enter, 
<ctrl><alt> enter, 
<shift> enter, etc

don't work, as you pointed out.

For the record, if you are doing web development, the linefeeds will not show up in the browser anyway (they are interpreted as extra whitespace, and are ignored). I had to replace line feed with

<br> 

everywhere I wanted a line break to show up in the browser (text areas will accept line feeds as usable input).

Even if you could insert a line break, I don't think the data grid view in SSMS is capable of displaying it.

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

How to force keyboard with numbers in mobile website in Android

IMPORTANT NOTE

I am posting this as an answer, not a comment, as it is rather important info and it will attract more attention in this format.

As other fellows pointed, you can force a device to show you a numeric keyboard with type="number" / type="tel", but I must emphasize that you have to be extremely cautious with this.

If someone expects a number beginning with zeros, such as 000222, then she is likely to have trouble, as some browsers (desktop Chrome, for instance) will send to the server 222, which is not what she wants.

About type="tel" I can't say anything similar but personally I do not use it, as its behavior on different telephones can vary. I have confined myself to the simple pattern="[0-9]*" which do not work in Android

Map HTML to JSON

Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON method to recursively build the result

Below, html2json is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity

_x000D_
_x000D_
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    textContent:_x000D_
      e.textContent,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.children, Elem)_x000D_
  })_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

In the previous example, the textContent gets a little butchered. To remedy this, we introduce another data constructor, TextElem. We'll have to map over the childNodes (instead of children) and choose to return the correct data type based on e.nodeType – this gets us a littler closer to what we might need

_x000D_
_x000D_
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
  toJSON: () => ({_x000D_
    type:_x000D_
      'TextElem',_x000D_
    textContent:_x000D_
      e.textContent_x000D_
  })_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    type:_x000D_
      'Elem',_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.childNodes, fromNode)_x000D_
  })_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
  switch (e.nodeType) {_x000D_
    case 3:  return TextElem(e)_x000D_
    default: return Elem(e)_x000D_
  }_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity

In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^

Related: Recursive methods using JavaScript: building your own version of JSON.stringify

Is it possible to decrypt MD5 hashes?

No, it is not possible to reverse a hash function such as MD5: given the output hash value it is impossible to find the input message unless enough information about the input message is known.

Decryption is not a function that is defined for a hash function; encryption and decryption are functions of a cipher such as AES in CBC mode; hash functions do not encrypt nor decrypt. Hash functions are used to digest an input message. As the name implies there is no reverse algorithm possible by design.


MD5 has been designed as a cryptographically secure, one-way hash function. It is now easy to generate collisions for MD5 - even if a large part of the input message is pre-determined. So MD5 is officially broken and MD5 should not be considered a cryptographically secure hash anymore. It is however still impossible to find an input message that leads to a hash value: find X when only H(X) is known (and X doesn't have a pre-computed structure with at least one 128 byte block of precomputed data). There are no known pre-image attacks against MD5.

It is generally also possible to guess passwords using brute force or (augmented) dictionary attacks, to compare databases or to try and find password hashes in so called rainbow tables. If a match is found then it is computationally certain that the input has been found. Hash functions are also secure against collision attacks: finding X' so that H(X') = H(X) given H(X). So if an X is found it is computationally certain that it was indeed the input message. Otherwise you would have performed a collision attack after all. Rainbow tables can be used to speed up the attacks and there are specialized internet resources out there that will help you find a password given a specific hash.

It is of course possible to re-use the hash value H(X) to verify passwords that were generated on other systems. The only thing that the receiving system has to do is to store the result of a deterministic function F that takes H(X) as input. When X is given to the system then H(X) and therefore F can be recalculated and the results can be compared. In other words, it is not required to decrypt the hash value to just verify that a password is correct, and you can still store the hash as a different value.


Instead of MD5 it is important to use a password hash or PBKDF (password based key derivation function) instead. Such a function specifies how to use a salt together with a hash. That way identical hashes won't be generated for identical passwords (from other users or within other databases). Password hashes for that reason also do not allow rainbow tables to be used as long as the salt is large enough and properly randomized.

Password hashes also contain a work factor (sometimes configured using an iteration count) that can significantly slow down attacks that try to find the password given the salt and hash value. This is important as the database with salts and hash values could be stolen. Finally, the password hash may also be memory-hard so that a significant amount of memory is required to calculate the hash. This makes it impossible to use special hardware (GPU's, ASIC's, FPGA's etc.) to allow an attacker to speed up the search. Other inputs or configuration options such as a pepper or the amount of parallelization may also be available to a password hash.

It will however still allow anybody to verify a password given H(X) even if H(X) is a password hash. Password hashes are still deterministic, so if anybody has knows all the input and the hash algorithm itself then X can be used to calculate H(X) and - again - the results can be compared.

Commonly used password hashes are bcrypt, scrypt and PBKDF2. There is also Argon2 in various forms which is the winner of the reasonably recent password hashing competition. Here on CrackStation is a good blog post on doing password security right.


It is possible to make it impossible for adversaries to perform the hash calculation verify that a password is correct. For this a pepper can be used as input to the password hash. Alternatively, the hash value can of course be encrypted using a cipher such as AES and a mode of operation such as CBC or GCM. This however requires the storage of a secret / key independently and with higher access requirements than the password hash.

Oracle SQL query for Date format

you can use this command by getting your data. this will extract your data...

select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';

Eclipse: stop code from running (java)

Open the Console view, locate the console for your running app and hit the Big Red Button.

Alternatively if you open the Debug perspective you will see all running apps in (by default) the top left. You can select the one that's causing you grief and once again hit the Big Red Button.enter image description here

how to draw a rectangle in HTML or CSS?

css:

.example {
    display: table;
    width: 200px;
    height: 200px;
    background: #4679BD;
}

html:

<div class="retangulo">
   
</div>