Programs & Examples On #Sql parametrized query

In PHP with PDO, how to check the final SQL parametrized query?

You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .

Python MYSQL update statement

Here is the correct way:

import MySQLdb

if __name__ == '__main__':
    connect = MySQLdb.connect(host="localhost", port=3306,
                              user="xxx", passwd="xxx", db='xxx', charset='utf8')

    cursor = connect.cursor()

    cursor.execute("""
       UPDATE tblTableName
       SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
       WHERE Server=%s
    """, (Year, Month, Day, Hour, Minute, ServerID))

    connect.commit()
    connect.close()

P.S. Don't forget connect.commit(), or it won't work

How to COUNT rows within EntityFramework without loading contents?

Query syntax:

var count = (from o in context.MyContainer
             where o.ID == '1'
             from t in o.MyTable
             select t).Count();

Method syntax:

var count = context.MyContainer
            .Where(o => o.ID == '1')
            .SelectMany(o => o.MyTable)
            .Count()

Both generate the same SQL query.

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

Facebook how to check if user has liked page and show content?

UPDATE 21/11/2012 @ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here


Hi So as promised here is my answer using only javascript :

The content of the BODY of the page :

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  FB.init({
    appId  : 'YOUR APP ID',
    status : true, 
    cookie : true, 
    xfbml  : true  
  });
</script>

<div id="container_notlike">
YOU DONT LIKE
</div>

<div id="container_like">
YOU LIKE
</div>

The CSS :

body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}

#container_notlike, #container_like {
    display:none
}

And finally the javascript :

$(document).ready(function(){

    FB.login(function(response) {
      if (response.session) {

          var user_id = response.session.uid;
          var page_id = "40796308305"; //coca cola
          var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
          var the_query = FB.Data.query(fql_query);

          the_query.wait(function(rows) {

              if (rows.length == 1 && rows[0].uid == user_id) {
                  $("#container_like").show();

                  //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

              } else {
                  $("#container_notlike").show();
                  //and here you could get the content for a non liker in ajax...
              }
          });


      } else {
        // user is not logged in
      }
    });

});

So what what does it do ?

First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid with YOUR_USER_ID (from your rails app for example)

After that it makes a FQL query on the page_fan table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.

Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/

It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...

Finally some related docs :

FQL page_fan table

FBJS FB.Data.query

Don't hesitate if you have any question ..

Cheers

UPDATE 2

As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).

For the document.ready, you could wrap your code in a function and use body onload="your_function" or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.

And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block" and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm

But jQuery is so easy :)

UPDATE

Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.

In your action controller :

decoded_request = Canvas.parse_signed_request(params[:signed_request])

And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)

decoded_request['page']['liked']

And here is the related Canvas Class (from fbgraph ruby library) :

 class Canvas

    class << self
      def parse_signed_request(secret_id,request)
        encoded_sig, payload = request.split('.', 2)
        sig = ""
        urldecode64(encoded_sig).each_byte { |b|
          sig << "%02x" % b
        }
        data = JSON.parse(urldecode64(payload))
          if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
          raise "Bad signature algorithm: %s" % data['algorithm']
        end
        expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
        if expected_sig != sig
          raise "Bad signature"
        end
        data
      end

      private

      def urldecode64(str)
        encoded_str = str.gsub('-','+').gsub('_','/')
        encoded_str += '=' while !(encoded_str.size % 4).zero?
        Base64.decode64(encoded_str)
      end
    end  

 end

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Use

=LEFT(B2, 2)*3600000 + MID(B2,4,2) * 60000 + MID(B2,7,2)*1000 + RIGHT(B2,3)

File size exceeds configured limit (2560000), code insight features not available

To clarify Alvaro's answer, you need to add the -D option to the list of command lines. I'm using PyCharm, but the concept is the same:

pycharm{64,.exe,64.exe}.vmoptions:
<code>
    -server
    -Xms128m
    ...
    -Didea.max.intellisense.filesize=999999 # <--- new line
</code>

Setting up Eclipse with JRE Path

You are most probably missing PATH entries in your windows. Follow this instruction : How do I set or change the PATH system variable?

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

A side from the very long complete accepted answer there is an important point to make about IndexOutOfRangeException compared with many other exception types, and that is:

Often there is complex program state that maybe difficult to have control over at a particular point in code e.g a DB connection goes down so data for an input cannot be retrieved etc... This kind of issue often results in an Exception of some kind that has to bubble up to a higher level because where it occurs has no way of dealing with it at that point.

IndexOutOfRangeException is generally different in that it in most cases it is pretty trivial to check for at the point where the exception is being raised. Generally this kind of exception get thrown by some code that could very easily deal with the issue at the place it is occurring - just by checking the actual length of the array. You don't want to 'fix' this by handling this exception higher up - but instead by ensuring its not thrown in the first instance - which in most cases is easy to do by checking the array length.

Another way of putting this is that other exceptions can arise due to genuine lack of control over input or program state BUT IndexOutOfRangeException more often than not is simply just pilot (programmer) error.

Fetch API with Cookie

Have just solved. Just two f. days of brutforce

For me the secret was in following:

  1. I called POST /api/auth and see that cookies were successfully received.

  2. Then calling GET /api/users/ with credentials: 'include' and got 401 unauth, because of no cookies were sent with the request.

The KEY is to set credentials: 'include' for the first /api/auth call too.

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

How to generate sample XML documents from their DTD or XSD?

Seems like nobody was able to answer the question so far :)

I use EclipseLink's MOXy to dynamically generate binding classes and then recursively go through the bound types. It is somewhat heavy, but it allows XPath value injection once the object tree is instantiated:

InputStream in = new FileInputStream(PATH_TO_XSD);
DynamicJAXBContext jaxbContext = 
            DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);
DynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);
DynamicEntity root = rootType.newDynamicEntity();
traverseProps(jaxbContext, root, rootType, 0);

TraverseProps is pretty simple recursive method:

private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{
        if (t!=null) {
            logger.info(indent(level) + "type [" + t.getName() + "] of class [" + t.getClassName() + "] has " + t.getNumberOfProperties() + " props");
            for (String pName:t.getPropertiesNames()){
                Class<?> clazz = t.getPropertyType(pName);
                logger.info(indent(level) + "prop [" + pName + "] in type: " + clazz);
                //logger.info("prop [" + pName + "] in entity: " + e.get(pName));

                if (clazz==null){
                    // need to create an instance of object
                    String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);
                    logger.info(indent(level) + "Creating new type instance for " + pName + " using following class name: " + updatedClassName );
                    DynamicType child = c.getDynamicType("generated." + updatedClassName);
                    DynamicEntity childEntity = child.newDynamicEntity();
                    e.set(pName, childEntity);
                    traverseProps(c, childEntity, child, level+1);
                } else {
                    // just set empty value
                    e.set(pName, clazz.newInstance());
                }
            }
        } else {
            logger.warn("type is null");
        }
    }

Converting everything to XML is pretty easy:

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);

List of installed gems?

This lists all the gems I have installed.

gem query --local

http://guides.rubygems.org/command-reference/#gem-list

See 2.7 Listing all installed gems

Move textfield when keyboard appears swift

Here is my version for a solution for Swift 2.2:

First register for Keyboard Show/Hide Notifications

NSNotificationCenter.defaultCenter().addObserver(self,
                                                 selector: #selector(MessageThreadVC.keyboardWillShow(_:)),
                                                 name: UIKeyboardWillShowNotification,
                                                 object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
                                                 selector: #selector(MessageThreadVC.keyboardWillHide(_:)),
                                                 name: UIKeyboardWillHideNotification,
                                                 object: nil)

Then in methods coresponding for those notifications move the main view up or down

func keyboardWillShow(sender: NSNotification) {
if let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
  self.view.frame.origin.y = -keyboardSize.height
  }
}

func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y = 0
}

The trick is in the "keyboardWillShow" part which get calls every time "QuickType Suggestion Bar" is expanded or collapsed. Then we always set the y coordinate of the main view which equals the negative value of total keyboard height (with or without the "QuickType bar" portion).

At the end do not forget to remove observers

deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}

replace \n and \r\n with <br /> in java

It works for me.

public class Program
{
    public static void main(String[] args) {
        String str = "This is a string.\nThis is a long string.";
        str = str.replaceAll("(\r\n|\n)", "<br />");
        System.out.println(str);
    }
}

Result:

This is a string.<br />This is a long string.

Your problem is somewhere else.

jQuery show/hide not working

if (grid.selectedKeyNames().length > 0) {
            $('#btnRemoveFromList').show();
        } else {
            $('#btnRemoveFromList').hide();
        }

}

() - calls the method

no parentheses - returns the property

Java's L number (long) specification

It seems like these would be good to have because (I assume) if you could specify the number you're typing in is a short then java wouldn't have to cast it

Since the parsing of literals happens at compile time, this is absolutely irrelevant in regard to performance. The only reason having short and byte suffixes would be nice is that it lead to more compact code.

What does 'super' do in Python?

I had played a bit with super(), and had recognized that we can change calling order.

For example, we have next hierarchy structure:

    A
   / \
  B   C
   \ /
    D

In this case MRO of D will be (only for Python 3):

In [26]: D.__mro__
Out[26]: (__main__.D, __main__.B, __main__.C, __main__.A, object)

Let's create a class where super() calls after method execution.

In [23]: class A(object): #  or with Python 3 can define class A:
...:     def __init__(self):
...:         print("I'm from A")
...:  
...: class B(A):
...:      def __init__(self):
...:          print("I'm from B")
...:          super().__init__()
...:   
...: class C(A):
...:      def __init__(self):
...:          print("I'm from C")
...:          super().__init__()
...:  
...: class D(B, C):
...:      def __init__(self):
...:          print("I'm from D")
...:          super().__init__()
...: d = D()
...:
I'm from D
I'm from B
I'm from C
I'm from A

    A
   / ?
  B ? C
   ? /
    D

So we can see that resolution order is same as in MRO. But when we call super() in the beginning of the method:

In [21]: class A(object):  # or class A:
...:     def __init__(self):
...:         print("I'm from A")
...:  
...: class B(A):
...:      def __init__(self):
...:          super().__init__()  # or super(B, self).__init_()
...:          print("I'm from B")
...:   
...: class C(A):
...:      def __init__(self):
...:          super().__init__()
...:          print("I'm from C")
...:  
...: class D(B, C):
...:      def __init__(self):
...:          super().__init__()
...:          print("I'm from D")
...: d = D()
...: 
I'm from A
I'm from C
I'm from B
I'm from D

We have a different order it is reversed a order of the MRO tuple.

    A
   / ?
  B ? C
   ? /
    D 

For additional reading I would recommend next answers:

  1. C3 linearization example with super (a large hierarchy)
  2. Important behavior changes between old and new style classes
  3. The Inside Story on New-Style Classes

Simple way to understand Encapsulation and Abstraction

Abstraction is generalised term. i.e. Encapsulation is subset of Abstraction.

Abstraction is a powerful methodology to manage complex systems. Abstraction is managed by well-defined objects and their hierarchical classification.

For example a car in itself is a well-defined object, which is composed of several other smaller objects like a gearing system, steering mechanism, engine, which are again have their own subsystems. But for humans car is a one single object, which can be managed by the help of its subsystems, even if their inner details are unknown. Courtesy


Encapsulation: Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.

Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.

Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.

class Bag{
    book;
    pen;
    ReadBook();
}

Encapsulation means hiding the internal details of an object, i.e. how an object does something.

Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.

Encapsulation is a technique used to protect the information in an object from the other object.

Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.

So, when you access the property you can validate the data and set it. Courtesy

Return a `struct` from a function in C

There is no issue in passing back a struct. It will be passed by value

But, what if the struct contains any member which has a address of a local variable

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

Now, here e1.name contains a memory address local to the function get(). Once get() returns, the local address for name would have been freed up. SO, in the caller if we try to access that address, it may cause segmentation fault, as we are trying a freed address. That is bad..

Where as the e1.id will be perfectly valid as its value will be copied to e2.id

So, we should always try to avoid returning local memory addresses of a function.

Anything malloced can be returned as and when wanted

How to put/get multiple JSONObjects to JSONArray?

From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:

JSONArray jsonArray=new JSONArray(jsonObject);

JSONArray has constructor to accept object.

Visual Studio 2015 Update 3 Offline Installer (ISO)

[UPDATE]
As per March 7, 2017, Visual Studio 2017 was released for general availability.

You can refer to Mehdi Dehghani answer for the direct download links or the old-fashioned ways using the website, vibs2006 answer
And you can also combine it with ray pixar answer to make it a complete full standalone offline installer.


Note:
I don't condone any illegal use of the offline installer.
Please stop piracy and follow the EULA.

The community edition is free even for commercial use, under some condition.
You can see the EULA in this link below.
https://www.visualstudio.com/support/legal/mt171547
Thank you.


Instruction for official offline installer:

  1. Open this link

    https://www.visualstudio.com/downloads/

  2. Scroll Down (DO NOT FORGET!)

  3. Click on "Visual Studio 2015" panel heading
  4. Choose the edition that you want

    These menu should be available in that panel:

    • Community 2015
    • Enterprise 2015
    • Professional 2015
    • Enterprise 2015
    • Visual Studio 2015 Update
    • Visual Studio 2015 Language Pack
    • Visual Studio Test Professional 2015 Language Pack
    • Test Professional 2015
    • Express 2015 for Desktop
    • Express 2015 for Windows 10


  1. Choose the language that you want in the drop-down menu (above the Download button)

    The language drop-down menu should be like this:

    • English for English
    • Deutsch for German
    • Español for Spanish
    • Français for French
    • Italiano for Italian
    • ??????? for Russian
    • ??? for Japanese
    • ???? for Chinese (Simplified)
    • ???? for Chinese (Traditional)
    • ??? for Korean


  1. Check on "ISO" in radio-button menu (on the left side of the Download button)

    The radio-button menu should be like this:

    • Web installer
    • ISO
  2. Click the Download button

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

.NET Console Application Exit Event

The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.

Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)

Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...


Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean

Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean

Public Enum CtrlTypes
  CTRL_C_EVENT = 0
  CTRL_BREAK_EVENT
  CTRL_CLOSE_EVENT
  CTRL_LOGOFF_EVENT = 5
  CTRL_SHUTDOWN_EVENT
End Enum

Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.
.clean up code here
.
End Function

Public Sub Main()
.
.
.
SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)
.
.
End Sub

This setup seems to work out perfectly. Here is a link to some C# code for the same thing.

Reducing video size with same format and reducing frame size

If you want to keep same screen size, you can consider using crf factor: https://trac.ffmpeg.org/wiki/Encode/H.264

Here is the command which works for me: (on mac you need to add -strict -2 to be able to use aac audio codec.

ffmpeg -i input.mp4 -c:v libx264 -crf 24 -b:v 1M -c:a aac output.mp4

Using a PagedList with a ViewModel ASP.Net MVC

For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.

Repository

    public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
    {
        List<Order> orders = new List<Order>();
        using (DatabaseContext db = new DatabaseContext())
        {
            orders = (from o in db.Orders
                      orderby o.Date descending //use orderby, otherwise Skip will throw an error
                      select o)
                      .Skip(itemsPerPage * page).Take(itemsPerPage)
                      .ToList();
            totalCount = db.Orders.Count();//return the number of pages
        }
        return orders;//the query is now already executed, it is a subset of all the orders.
    }

Controller

    public ActionResult Index(int? page)
    {
        int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
        OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
        int totalCount = 0;
        List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
        List<OrderViewModel> orderViews = new List<OrderViewModel>();
        foreach(Order order in orders)//convert your models to some view models.
        {
            orderViews.Add(orderMan.GenerateOrderViewModel(order));
        }
        //create staticPageList, defining your viewModel, current page, page size and total number of pages.
        IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
        return View(pageOrders);
    }

View

@using PagedList.Mvc;
@using PagedList; 

@model IPagedList<Babywatcher.Core.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container-fluid">
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @if (Model.Count > 0)
    {


        <table class="table">
          <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().orderId)
            </th>
            <!--rest of your stuff-->
        </table>

    }
    else
    {
        <p>No Orders yet.</p>
    }
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>

Bonus

Do above first, then perhaps use this!

Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).

Repository

In your order repository (in my case), add a static method to convert a model:

public static OrderModel ConvertToModel(Order entity)
{
    if (entity == null) return null;
    OrderModel model = new OrderModel
    {
        ContactId = entity.contactId,
        OrderId = entity.orderId,
    }
    return model;
}

Below your repository class, add this:

public static partial class Ex
{
    public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
    {
        bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
        return source.Select(x => new OrderModel
        {
            OrderId = x.orderId,
            //example use ConvertToModel of some other repository
            BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
            //example use another extension of some other repository
            Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
        });
    }
}

And then in your GetOrderPage method:

    public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
        out int totalCount)
    {
        IQueryable<Order> query = DbContext.Orders; //get queryable from db
        .....//do your filtering, sorting, paging (do not use .ToList() yet)

        return queryOrders.SelectOrderModel().AsEnumerable();
        //or, if you want to include relations
        return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
        //notice difference, first ToList(), then SelectOrderModel().
    }

Let me explain:

The static ConvertToModel method can be accessed by any other repository, as used above, I use ConvertToModel from some AddressRepository.

The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.

Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel() extension, includeRelations inside the extension will be true because the source is NOT a database query type (not an linq-to-sql IQueryable). When this is true, the extension can call other methods/extensions throughout your application for converting models.

Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList() yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations will be false so that it doesn't call other c# methods that SQL doesn't understand.

It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include() extra will load the relations.

Move seaborn plot legend to a different position?

Check out the docs here: https://matplotlib.org/users/legend_guide.html#legend-location

adding this simply worked to bring legend out of the plot:

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How to detect a route change in Angular?

In angular 6 and RxJS6:

import { filter, debounceTime } from 'rxjs/operators';

 this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      debounceTime(40000)
    ).subscribe(
      x => {
      console.log('val',x);
      this.router.navigate(['/']); /*Redirect to Home*/
}
)

jQuery how to find an element based on a data-attribute value?

Without JQuery, ES6

document.querySelectorAll(`[data-slide='${current}']`);

I know the question is about JQuery, but readers may want a pure JS method.

How to get the employees with their managers

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

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

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

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

var rowpos = $('#table tr:last').position();

$('#container').scrollTop(rowpos.top);

should do the trick!

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

How do I apply a perspective transform to a UIView?

As Ben said, you'll need to work with the UIView's layer, using a CATransform3D to perform the layer's rotation. The trick to get perspective working, as described here, is to directly access one of the matrix cells of the CATransform3D (m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:

Objective-C

UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;

Swift 5.0

if let myView = self.subviews.first {
    let layer = myView.layer
    var rotationAndPerspectiveTransform = CATransform3DIdentity
    rotationAndPerspectiveTransform.m34 = 1.0 / -500
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
    layer.transform = rotationAndPerspectiveTransform
}

which rebuilds the layer transform from scratch for each rotation.

A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.

The sublayerTransform you refer to in your response is a transform that is applied to the sublayers of your UIView's CALayer. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers contained within the one layer that I'm rotating.

How to draw a checkmark / tick using CSS?

i like this way because you don't need to create two components just one.

.checkmark:after {
    opacity: 1;
    height: 4em;
    width: 2em;
    -webkit-transform-origin: left top;
    transform-origin: left top;
    border-right: 2px solid #5cb85c;
    border-top: 2px solid #5cb85c;
    content: '';
    left: 2em;
    top: 4em;
    position: absolute;
}

Animation from Scott Galloway Pen

How to use ArrayList's get() method

ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.

public Element get(int index)

Example : In below example we are getting few elements of an arraylist by using get method.

package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
   public static void main(String[] args) {
       ArrayList<String> al = new ArrayList<String>();
       al.add("pen");
       al.add("pencil");
       al.add("ink");
       al.add("notebook");
       al.add("book");
       al.add("books");
       al.add("paper");
       al.add("white board");

       System.out.println("First element of the ArrayList: "+al.get(0));
       System.out.println("Third element of the ArrayList: "+al.get(2));
       System.out.println("Sixth element of the ArrayList: "+al.get(5));
       System.out.println("Fourth element of the ArrayList: "+al.get(3));
   }
}

Output:

First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook

Node - how to run app.js?

Assuming I have node and npm properly installed on the machine, I would

  • Download the code
  • Navigate to inside the project folder on terminal, where I would hopefully see a package.json file
  • Do an npm install for installing all the project dependencies
  • Do an npm install -g nodemon for installing all the project dependencies
  • Then npm start OR node app.js OR nodemon app.js to get the app running on local host

Hope this helps someone

use nodemon app.js ( nodemon is a utility that will monitor for any changes in your source and automatically restart your server)

Entity Framework Core: A second operation started on this context before a previous operation completed

I have a background service that performs an action for each entry in a table. The problem is, that if I iterate over and modify some data all on the same instance of the DbContext this error occurs.

One solution, as mentioned in this thread is to change the DbContext's lifetime to transient by defining it like

services.AddDbContext<DbContext>(ServiceLifetime.Transient);

but because I do changes in multiple different services and commit them at once using the SaveChanges() method this solution doesnt work in my case.

Because my code runs in a service, I was doing something like

using (var scope = Services.CreateScope())
{
   var entities = scope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = scope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)
   {
       writeService.DoSomething(entity);
   } 
}

to be able to use the service like if it was a simple request. So to solve the issue i just split the single scope into two, one for the query and the other for the write operations like so:

using (var readScope = Services.CreateScope())
using (var writeScope = Services.CreateScope())
{
   var entities = readScope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = writeScope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)
   {
       writeService.DoSomething(entity);
   } 
}

Like that, there are effevtively two different instances of the DbContext being used.

Another possible solution would be to make sure, that the read operation has terminated before starting the iteration. That is not very pratical in my case because there could be a lot of results that would all need to be loaded into memory for the operation which I tried to avoid by using a Queryable in the first place.

asp.net mvc3 return raw html to view

That looks fine, unless you want to pass it as Model string

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string model = "<HTML></HTML>";
        return View(model);
    }
}

@model string
@{
    ViewBag.Title = "Index";
}

@Html.Raw(Model)

How to add an image in Tkinter?

Just convert the jpg format image into png format. It will work 100%.

UIGestureRecognizer on UIImageView

Swift 4.2

myImageView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
tapGestureRecognizer.numberOfTapsRequired = 1
myImageView.addGestureRecognizer(tapGestureRecognizer)

and when tapped:

@objc func imageTapped(_ sender: UITapGestureRecognizer) {
   // do something when image tapped
   print("image tapped")
}

How to detect running app using ADB command

Alternatively, you could go with pgrep or Process Grep. (Busybox is needed)

You could do a adb shell pgrep com.example.app and it would display just the process Id.

As a suggestion, since Android is Linux, you can use most basic Linux commands with adb shell to navigate/control around. :D

Removing highcharts.com credits link

Add this to your css.

.highcharts-credits {
display: none !important;
}

Cannot find mysql.sock

The original questions seems to come from confusion about a) where is the file, and b) where is it being looked for (and why can't we find it there when we do a locate or grep). I think Alnitak's point was that you want to find where it was linked to - but grep will not show you a link, right? The file doesn't live there, since it's a link it is just a pointer. You still need to know where to put the link.

my sock file is definitely in /tmp and the ERROR I am getting is looking for it in /var/lib/ (not just /var) I have linked to /var and /var/lib now, and I still am getting the error "Cannot connect to local MySQL server through socket 'var/lib/mysql.sock' (2)".

Note the (2) after the error.... I found on another thread that this means the socket might be indeed attempted to be used, but something is wrong with the socket itself - so to shut down the machine - completely - so that the socket closes. Then a restart should fix it. I tried this, but it didn't work for me (now I question if I restarted too quickly? really?) Maybe it will be a solution for someone else.

Get total number of items on Json object?

Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length returns undefined rather than 5.

This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

How to put space character into a string name in XML?

xml:space="preserve"

Works like a charm.

Edit: Wrong. Actually, it only works when the content is comprised of white spaces only.

Link

Fastest way to ping a network range and return responsive hosts?

Try both of these commands and see for yourself why arp is faster:

PING:

for ip in $(seq 1 254); do ping -c 1 10.185.0.$ip > /dev/null; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done

ARP:

for ip in $(seq 1 254); do arp -n 10.185.0.$ip | grep Address; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done

Check if url contains string with JQuery

if(window.location.href.indexOf("?added-to-cart=555") >= 0)

It's window.location.href, not window.location.

JavaScript window resize event

The resize event should never be used directly as it is fired continuously as we resize.

Use a debounce function to mitigate the excess calls.

window.addEventListener('resize',debounce(handler, delay, immediate),false);

Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.

const debounce = (func, wait, immediate) => {
    var timeout;
    return () => {
        const context = this, args = arguments;
        const later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

This can be used like so...

window.addEventListener('resize', debounce(() => console.log('hello'),
200, false), false);

It will never fire more than once every 200ms.

For mobile orientation changes use:

window.addEventListener('orientationchange', () => console.log('hello'), false);

Here's a small library I put together to take care of this neatly.

Select SQL Server database size

If you want to simply check single database size, you can do it using SSMS Gui

Go to Server Explorer -> Expand it -> Right click on Database -> Choose Properties -> In popup window choose General tab ->See Size

Source: Check database size in Sql server ( Various Ways explained)

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

Java 6 Unsupported major.minor version 51.0

According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.

Laravel 5.4 redirection to custom url after login

  1. Go to Providers->RouteServiceProvider.php

  2. There change the route, given below:

    class RouteServiceProvider extends ServiceProvider
    {
     protected $namespace = 'App\Http\Controllers';
    
     /**
      * The path to the "home" route for your application.
      *
      * @var string
      */
     public const HOME = '/dashboard';
    

How to convert a Date to a formatted string in VB.net?

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
objBL.date = Convert.ToDateTime(txtDate.Value).ToString(timeFormat)

How to get SQL from Hibernate Criteria API (*not* for logging)

For anyone wishing to do this in a single line (e.g in the Display/Immediate window, a watch expression or similar in a debug session), the following will do so and "pretty print" the SQL:

new org.hibernate.jdbc.util.BasicFormatterImpl().format((new org.hibernate.loader.criteria.CriteriaJoinWalker((org.hibernate.persister.entity.OuterJoinLoadable)((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),new org.hibernate.loader.criteria.CriteriaQueryTranslator(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),((org.hibernate.impl.CriteriaImpl)crit),((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),(org.hibernate.impl.CriteriaImpl)crit,((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters())).getSQLString());

...or here's an easier to read version:

new org.hibernate.jdbc.util.BasicFormatterImpl().format(
  (new org.hibernate.loader.criteria.CriteriaJoinWalker(
     (org.hibernate.persister.entity.OuterJoinLoadable)
      ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(
        ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(
          ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),
     new org.hibernate.loader.criteria.CriteriaQueryTranslator(
          ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
          ((org.hibernate.impl.CriteriaImpl)crit),
          ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
          org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),
     ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
     (org.hibernate.impl.CriteriaImpl)crit,
     ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
     ((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters()
   )
  ).getSQLString()
);

Notes:

  1. The answer is based on the solution posted by ramdane.i.
  2. It assumes the Criteria object is named crit. If named differently, do a search and replace.
  3. It assumes the Hibernate version is later than 3.3.2.GA but earlier than 4.0 in order to use BasicFormatterImpl to "pretty print" the HQL. If using a different version, see this answer for how to modify. Or perhaps just remove the pretty printing entirely as it's just a "nice to have".
  4. It's using getEnabledFilters rather than getLoadQueryInfluencers() for backwards compatibility since the latter was introduced in a later version of Hibernate (3.5???)
  5. It doesn't output the actual parameter values used if the query is parameterized.

JSON and escaping characters

This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.

So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader instance. Any time you are creating a Reader from an InputStream, you need to specify the character encoding, or java.nio.charset.Charset instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8). If you don't specify a Charset, Java will use your platform default encoding, which on Windows is usually CP-1252.

What is the difference between association, aggregation and composition?

    Simple rules:
    A "owns" B = Composition : B has no meaning or purpose in the system 
    without A
    A "uses" B = Aggregation : B exists independently (conceptually) from A
    A "belongs/Have" B= Association; And B exists just have a relation
    Example 1:

    A Company is an aggregation of Employees.
    A Company is a composition of Accounts. When a Company ceases to do 
    business its Accounts cease to exist but its People continue to exist. 
    Employees have association relationship with each other.

    Example 2: (very simplified)
    A Text Editor owns a Buffer (composition). A Text Editor uses a File 
    (aggregation). When the Text Editor is closed,
    the Buffer is destroyed but the File itself is not destroyed.

Find length of 2D array Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Add the all tiles jars like(tiles-jsp,tiles-servlet,tiles-template,tiles-extras.tiles-core ) to your server lib folder and your application build path then it work if you using apache tailes with spring mvc application

Converting .NET DateTime to JSON

http://stevenlevithan.com/assets/misc/date.format.js

var date = eval(data.Data.Entity.Slrq.replace(/\/Date\((\d )\)\//gi, "new Date($1)"));  
alert(date.format("yyyy-MM-dd HH:mm:ss"));  
alert(dateFormat(date, "yyyy-MM-dd HH:mm:ss"));  

What is copy-on-write?

Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.

Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy object (the proxy) implements the copy-on-write technique by:

  • having an attribute bound to an immutable Value object (the subject);
  • translating copy requests to the creation of a new ValueProxy object sharing the same subject attribute as the original ValueProxy object;
  • forwarding read requests to the subject attribute;
  • translating write requests to the creation of a new immutable Value object with the new state and the rebinding of the subject attribute to this new immutable Value object.
import abc

class BaseValue(abc.ABC):
    @abc.abstractmethod
    def read(self):
        raise NotImplementedError
    @abc.abstractmethod
    def write(self, data):
        raise NotImplementedError

class Value(BaseValue):
    def __init__(self, data):
        self.data = data
    def read(self):
        return self.data
    def write(self, data):
        pass

class ValueProxy(BaseValue):
    def __init__(self, subject):
        self.subject = subject
    def read(self):
        return self.subject.read()
    def write(self, data):
        self.subject = Value(data)
    def clone(self):
        return ValueProxy(self.subject)

v1 = ValueProxy(Value('foo'))
v2 = v1.clone()  # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar')  # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject

Using Tkinter in python to edit the title bar

If you don't create a root window, Tkinter will create one for you when you try to create any other widget. Thus, in your __init__, because you haven't yet created a root window when you initialize the frame, Tkinter will create one for you. Then, you call make_widgets which creates a second root window. That is why you are seeing two windows.

A well-written Tkinter program should always explicitly create a root window before creating any other widgets.

When you modify your code to explicitly create the root window, you'll end up with one window with the expected title.

Example:

from tkinter import Tk, Button, Frame, Entry, END

class ABC(Frame):
    def __init__(self,parent=None):
        Frame.__init__(self,parent)
        self.parent = parent
        self.pack()
        self.make_widgets()

    def make_widgets(self):
        # don't assume that self.parent is a root window.
        # instead, call `winfo_toplevel to get the root window
        self.winfo_toplevel().title("Simple Prog")

        # this adds something to the frame, otherwise the default
        # size of the window will be very small
        label = Entry(self)
        label.pack(side="top", fill="x")

root = Tk()
abc = ABC(root)
root.mainloop()

Also note the use of self.make_widgets() rather than ABC.make_widgets(self). While both end up doing the same thing, the former is the proper way to call the function.

Does 'position: absolute' conflict with Flexbox?

you have forgotten width of parent

_x000D_
_x000D_
.parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

Find out which remote branch a local branch is tracking

You can try this :

git remote show origin | grep "branch_name"

branch_name needs to be replaced with your branch

Determine if char is a num or letter

C99 standard on c >= '0' && c <= '9'

c >= '0' && c <= '9' (mentioned in another answer) works because C99 N1256 standard draft 5.2.1 "Character sets" says:

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

ASCII is not guaranteed however.

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

Listing contents of a bucket with boto3

My s3 keys utility function is essentially an optimized version of @Hephaestus's answer:

import boto3


s3_paginator = boto3.client('s3').get_paginator('list_objects_v2')


def keys(bucket_name, prefix='/', delimiter='/', start_after=''):
    prefix = prefix[1:] if prefix.startswith(delimiter) else prefix
    start_after = (start_after or prefix) if prefix.endswith(delimiter) else start_after
    for page in s3_paginator.paginate(Bucket=bucket_name, Prefix=prefix, StartAfter=start_after):
        for content in page.get('Contents', ()):
            yield content['Key']

In my tests (boto3 1.9.84), it's significantly faster than the equivalent (but simpler) code:

import boto3


def keys(bucket_name, prefix='/', delimiter='/'):
    prefix = prefix[1:] if prefix.startswith(delimiter) else prefix
    bucket = boto3.resource('s3').Bucket(bucket_name)
    return (_.key for _ in bucket.objects.filter(Prefix=prefix))

As S3 guarantees UTF-8 binary sorted results, a start_after optimization has been added to the first function.

Passing an array as a function parameter in JavaScript

In ES6 standard there is a new spread operator ... which does exactly that.

call_me(...x)

It is supported by all major browsers except for IE.

The spread operator can do many other useful things, and the linked documentation does a really good job at showing that.

How can I conditionally import an ES6 module?

Look at this example for clear understanding of how dynamic import works.

Dynamic Module Imports Example

To have Basic Understanding of importing and exporting Modules.

JavaScript modules Github

Javascript Modules MDN

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

I encountered this error when I had a row.names="id" (per the tutorial) with a column named "id".

Get selected value from combo box in C# WPF

Create a ComboBox SelectionChanged Event and set ItemsSource="{Binding}" in the WPF design:

Code:

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string ob = ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();
    MessageBox.Show(ob);
}

What's the difference between interface and @interface in java?

interface: defines the contract for a class which implements it

@interface: defines the contract for an annotation

Is not an enclosing class Java

One thing I didn't realize at first when reading the accepted answer was that making an inner class static is basically the same thing as moving it to its own separate class.

Thus, when getting the error

xxx is not an enclosing class

You can solve it in either of the following ways:

  • Add the static keyword to the inner class, or
  • Move it out to its own separate class.

Can I access variables from another file?

You can export the variable from first file using export.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
export { colorCode };

Then, import the variable in second file using import.

//second.js
import { colorCode } from './first.js'

export - MDN

Oracle SQL: Update a table with data from another table

Update table set column = (select...)

never worked for me since set only expects 1 value - SQL Error: ORA-01427: single-row subquery returns more than one row.

here's the solution:

BEGIN
For i in (select id, name, desc from table1) 
LOOP
Update table2 set name = i.name, desc = i.desc where id = i.id;
END LOOP;
END;

That's how exactly you run it on SQLDeveloper worksheet. They say it's slow but that's the only solution that worked for me on this case.

How can I remove the last character of a string in python?

No need to use expensive regex, if barely needed then try- Use r'(/)(?=$)' pattern that is capture last / and replace with r'' i.e. blank character.

>>>re.sub(r'(/)(?=$)',r'','/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/')
>>>'/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg'

How to recursively find and list the latest modified files in a directory with subdirectories and times

@anubhava's answer is great, but unfortunately won't work on BSD tools – i.e. it won't work with the find that comes installed by default on macOS, because BSD find doesn't have the -printf operator.

So here's a variation that works with macOS + BSD (tested on my Catalina Mac), which combines BSD find with xargs and stat:

$ find . -type f -print0 \
      | xargs -0 -n1 -I{} stat -f '%Fm %N' "{}" \
      | sort -rn 

While I'm here, here's BSD command sequence I like to use, which puts the timestamp in ISO-8601 format

$ find . -type f -print0 \
    | xargs -0 -n1 -I{} \
       stat  -f '%Sm %N' -t '%Y-%m-%d %H:%M:%S' "{}" \
    | sort -rn

(note that both my answers, unlike @anubhava's, pass the filenames from find to xargs as a single argument rather than a \0 terminated list, which changes what gets piped out at the very end)

And here's the GNU version (i.e. @anubhava's answer, but in iso-8601 format):

$ gfind . -type f -printf "%T+ %p\0" | sort -zk1nr

Related q: find lacks the option -printf, now what?

How to use a jQuery plugin inside Vue

Option #1: Use ProvidePlugin

Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js and build/webpack.prod.conf.js so that jQuery becomes globally available to all your modules:

plugins: [

  // ...

  new webpack.ProvidePlugin({
    $: 'jquery',
    jquery: 'jquery',
    'window.jQuery': 'jquery',
    jQuery: 'jquery'
  })
]

Option #2: Use Expose Loader module for webpack

As @TremendusApps suggests in his answer, add the Expose Loader package:

npm install expose-loader --save-dev

Use in your entry point main.js like this:

import 'expose?$!expose?jQuery!jquery'

// ...

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

For me the error was:

Error: unexpected input in "?"

and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.

EDIT: OP requested an example. Here it goes.

?  ~ cat a.R
cat('hello world\n')
?  ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f  ...cat('hello wo
00000010: 726c 645c 6e27 290a                      rld\n').
?  ~ R -f a.R        

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> cat('hello world\n')
Error: unexpected input in "?"
Execution halted

Finding Key associated with max Value in a Java Map

A simple one liner using Java-8

Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();

Git status shows files as changed even though contents are the same

Have you changed the mode of the files? I did it on my machine and the local dev machine had 777 given to all the files whereas the repo had 755 which showed every file as modified. I did git diff and it showed the old mode and new mode are different. If that is the problem then you can easily ignore them by git config core.filemode false
Cheers

How to check SQL Server version

Here is what i have done to find the version Here is what i have done to find the version: just write SELECT @@version and it will give you the version.

Install numpy on python3.3 - Install pip for python3

In the solution below I used python3.4 as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget obviously but just save the file locally and run it with python).

This is great if you have multiple versions of python installed, so you can manage external libraries per python version.

So first, I'd recommend get-pip.py, it's great to install pip :

wget https://bootstrap.pypa.io/get-pip.py

Then you need to install pip for your version of python, I have python3.4 so for me this is the command :

python3.4 get-pip.py

Now pip is installed for python3.4 and in order to get libraries for python3.4 one need to call it within this version, like this :

python3.4 -m pip

So if you want to install numpy you would use :

python3.4 -m pip install numpy

Note that numpy is quite the heavy library. I thought my system was hanging and failing. But using the verbose option, you can see that the system is fine :

python3.4 -m pip install numpy -v

This may tell you that you lack python.h but you can easily get it :

On RHEL (Red hat, CentOS, Fedora) it would be something like this :

yum install python34-devel

On debian-like (Debian, Ubuntu, Kali, ...) :

apt-get install python34-dev

Then rerun this :

python3.4 -m pip install numpy -v

Passing an Array as Arguments, not an Array, in PHP

As has been mentioned, as of PHP 5.6+ you can (should!) use the ... token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:

<?php
function variadic($arg1, $arg2)
{
    // Do stuff
    echo $arg1.' '.$arg2;
}

$array = ['Hello', 'World'];

// 'Splat' the $array in the function call
variadic(...$array);

// 'Hello World'

Note: array items are mapped to arguments by their position in the array, not their keys.

As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array.

Aside

Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.

(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)

This is great for making sure an array contains items of a specific type:

<?php

// Define the function...

function variadic($var, SomeClass ...$items)
{
    // $items will be an array of objects of type `SomeClass`
}

// Then you can call...

variadic('Hello', new SomeClass, new SomeClass);

// or even splat both ways

$items = [
    new SomeClass,
    new SomeClass,
];

variadic('Hello', ...$items);

How get total sum from input box values using Javascript?

Try this:

function add() 
{
  var sum = 0;
  var inputs = document.getElementsByTagName("input");
  for(i = 0; i <= inputs.length; i++) 
  {
   if( inputs[i].name == 'qty'+i) 
   {
     sum += parseInt(input[i].value);
   }
  }
  console.log(sum)

}

Replace Both Double and Single Quotes in Javascript String

You don't escape quotes in regular expressions

this.Vals.replace(/["']/g, "")

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

How to take column-slices of dataframe in pandas

Also, Given a DataFrame

data

as in your example, if you would like to extract column a and d only (e.i. the 1st and the 4th column), iloc mothod from the pandas dataframe is what you need and could be used very effectively. All you need to know is the index of the columns you would like to extract. For example:

>>> data.iloc[:,[0,3]]

will give you

          a         d
0  0.883283  0.100975
1  0.614313  0.221731
2  0.438963  0.224361
3  0.466078  0.703347
4  0.955285  0.114033
5  0.268443  0.416996
6  0.613241  0.327548
7  0.370784  0.359159
8  0.692708  0.659410
9  0.806624  0.875476

Uncaught TypeError: Cannot read property 'top' of undefined

Your document does not contain any element with class content-nav, thus the method .offset() returns undefined which indeed has no top property.

You can see for yourself in this fiddle

alert($('.content-nav').offset());

(you will see "undefined")

To avoid crashing the whole code, you can have such code instead:

var top = ($('.content-nav').offset() || { "top": NaN }).top;
if (isNaN(top)) {
    alert("something is wrong, no top");
} else {
    alert(top);
}

Updated fiddle.

Determine the line of code that causes a segmentation fault?

GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:

gcc program.c -g

Then use gdb:

$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>

Here is a nice tutorial to get you started with GDB.

Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

How to construct a relative path in Java from two absolute paths (or URLs)?

Since Java 7 you can use the relativize method:

import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

     public static void main(String[] args) {
        Path pathAbsolute = Paths.get("/var/data/stuff/xyz.dat");
        Path pathBase = Paths.get("/var/data");
        Path pathRelative = pathBase.relativize(pathAbsolute);
        System.out.println(pathRelative);
    }

}

Output:

stuff/xyz.dat

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

Your code compiles just fine. However, your array initialization line is wrong:

int array[]={};

What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.

Instead, you can either initialize the array right in your original line:

int array[] = { 5, 5, 5, 5 };

Or you can declare the size and then populate it:

int array[] = new int[4];
// ...while loop

If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).

Set default value of javascript object attributes

Object.withDefault = (defaultValue,o={}) => {
  return new Proxy(o, {
    get: (o, k) => (k in o) ? o[k] : defaultValue 
  });
}

o = Object.withDefault(42);
o.x  //=> 42

o.x = 10
o.x  //=> 10
o.xx //=> 42

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

this is probably about you don't entered correct dependency version. you can select correct dependency from this:

file>menu>project structure>app>dependencies>+>Library Dependency>select any thing you need > OK

if cannot find your needs you should update your sdk from below way:

tools>android>sdk manager>sdk update>select any thing you need>ok

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

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

You have two options:

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

How to Detect Browser Window /Tab Close Event?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var validNavigation = false;

function wireUpEvents() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the    user to be able to leave withou confirmation
 var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab  window. Good things will come to you'
 function goodbye(e) {
if (!validNavigation) {
window.open("http://serverthemes.net/best-web-hosting-services","_blank");
return leave_message;

}
}
window.onbeforeunload=goodbye;

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
 }
 });

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
  // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
});

 // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

 }

  // Wire up the events as soon as the DOM tree is ready
   $(document).ready(function() {
   wireUpEvents();
   });
   </script>

I did answer at Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?

How do you remove an invalid remote branch reference from Git?

All you need to do is

git fetch -p

It'll remove all your local branches which are remotely deleted.

If you are on git 1.8.5+ you can set this automatically

git config fetch.prune true

or

git config --global fetch.prune true

Regular expression to find URLs within a string

Using the regex provided by @JustinLevene did not have the proper escape sequences on the back-slashes. Updated to now be correct, and added in condition to match the FTP protocol as well: Will match to all urls with or without protocols, and with out without "www."

Code: ^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?

Example: https://regex101.com/r/uQ9aL4/65

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

How to match "anything up until this sequence of characters" in a regular expression?

You didn't specify which flavor of regex you're using, but this will work in any of the most popular ones that can be considered "complete".

/.+?(?=abc)/

How it works

The .+? part is the un-greedy version of .+ (one or more of anything). When we use .+, the engine will basically match everything. Then, if there is something else in the regex it will go back in steps trying to match the following part. This is the greedy behavior, meaning as much as possible to satisfy.

When using .+?, instead of matching all at once and going back for other conditions (if any), the engine will match the next characters by step until the subsequent part of the regex is matched (again if any). This is the un-greedy, meaning match the fewest possible to satisfy.

/.+X/  ~ "abcXabcXabcX"        /.+/  ~ "abcXabcXabcX"
          ^^^^^^^^^^^^                  ^^^^^^^^^^^^

/.+?X/ ~ "abcXabcXabcX"        /.+?/ ~ "abcXabcXabcX"
          ^^^^                          ^

Following that we have (?={contents}), a zero width assertion, a look around. This grouped construction matches its contents, but does not count as characters matched (zero width). It only returns if it is a match or not (assertion).

Thus, in other terms the regex /.+?(?=abc)/ means:

Match any characters as few as possible until a "abc" is found, without counting the "abc".

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

Maven: Failed to retrieve plugin descriptor error

Mac OSX 10.7.5: I tried setting my proxy in the settings.xml file (as mentioned by posters above) in the /conf directory and also in the ~/.m2 directory, but still I got this error. I downloaded the latest version of Maven (3.1.1), and set my PATH variable to reflect the latest install, and it worked for me right off the shelf without any error.

Easy pretty printing of floats in python?

You could use pandas.

Here is an example with a list:

In: import pandas as P
In: P.set_option('display.precision',3)
In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423]
In: P.Series(data=L)
Out: 
0    3.45
1    2.12
2    6.23
3    6.34
4    9.34
dtype: float64

If you have a dict d, and you want its keys as rows:

In: d
Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312}

In: P.DataFrame(index=d.keys(), data=d.values())
Out:  
    0
1   0.45
2   2.35
3   3.42
4   4.13

And another way of giving dict to a DataFrame:

P.DataFrame.from_dict(d, orient='index')

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

PHP 7 simpleXML

For all those using Ubuntu with ppa:ondrej/php PPA this will fix the problem:

apt install php7.0-mbstring php7.0-zip php7.0-xml

(see https://launchpad.net/~ondrej/+archive/ubuntu/php)

Thanks @Alexandre Barbosa for pointing this out!

EDIT 20160423:

One-liner to fix this issue:

sudo add-apt-repository -y ppa:ondrej/php && sudo apt update && sudo apt install -y php7.0-mbstring php7.0-zip php7.0-xml

(this will add the ppa noted above and will also make sure you always have the latest php. We use Ondrej's PHP ppa for almost two years now and it's working like charm)

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Below solution is a clean work around.It does not compromises security because we are using same strict firewall.

The Steps for fixing is as below:

STEP 1 : Create a Class overriding StrictHttpFirewall as below.

package com.biz.brains.project.security.firewall;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;

public class CustomStrictHttpFirewall implements HttpFirewall {
    private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());

    private static final String ENCODED_PERCENT = "%25";

    private static final String PERCENT = "%";

    private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));

    private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));

    private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));

    private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));

    private Set<String> encodedUrlBlacklist = new HashSet<String>();

    private Set<String> decodedUrlBlacklist = new HashSet<String>();

    private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();

    public CustomStrictHttpFirewall() {
        urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);

        this.encodedUrlBlacklist.add(ENCODED_PERCENT);
        this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        this.decodedUrlBlacklist.add(PERCENT);
    }

    public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
        this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
    }

    public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
        if (allowedHttpMethods == null) {
            throw new IllegalArgumentException("allowedHttpMethods cannot be null");
        }
        if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
        } else {
            this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
        }
    }

    public void setAllowSemicolon(boolean allowSemicolon) {
        if (allowSemicolon) {
            urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        }
    }

    public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
        if (allowUrlEncodedSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        }
    }

    public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
        if (allowUrlEncodedPeriod) {
            this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
        } else {
            this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        }
    }

    public void setAllowBackSlash(boolean allowBackSlash) {
        if (allowBackSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
        }
    }

    public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
        if (allowUrlEncodedPercent) {
            this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
            this.decodedUrlBlacklist.remove(PERCENT);
        } else {
            this.encodedUrlBlacklist.add(ENCODED_PERCENT);
            this.decodedUrlBlacklist.add(PERCENT);
        }
    }

    private void urlBlacklistsAddAll(Collection<String> values) {
        this.encodedUrlBlacklist.addAll(values);
        this.decodedUrlBlacklist.addAll(values);
    }

    private void urlBlacklistsRemoveAll(Collection<String> values) {
        this.encodedUrlBlacklist.removeAll(values);
        this.decodedUrlBlacklist.removeAll(values);
    }

    @Override
    public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
        rejectForbiddenHttpMethod(request);
        rejectedBlacklistedUrls(request);

        if (!isNormalized(request)) {
            request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
        }

        String requestUri = request.getRequestURI();
        if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
        }
        return new FirewalledRequest(request) {
            @Override
            public void reset() {
            }
        };
    }

    private void rejectForbiddenHttpMethod(HttpServletRequest request) {
        if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            return;
        }
        if (!this.allowedHttpMethods.contains(request.getMethod())) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the HTTP method \"" +
                    request.getMethod() +
                    "\" was not included within the whitelist " +
                    this.allowedHttpMethods));
        }
    }

    private void rejectedBlacklistedUrls(HttpServletRequest request) {
        for (String forbidden : this.encodedUrlBlacklist) {
            if (encodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
        for (String forbidden : this.decodedUrlBlacklist) {
            if (decodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
    }

    @Override
    public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
        return new FirewalledResponse(response);
    }

    private static Set<String> createDefaultAllowedHttpMethods() {
        Set<String> result = new HashSet<>();
        result.add(HttpMethod.DELETE.name());
        result.add(HttpMethod.GET.name());
        result.add(HttpMethod.HEAD.name());
        result.add(HttpMethod.OPTIONS.name());
        result.add(HttpMethod.PATCH.name());
        result.add(HttpMethod.POST.name());
        result.add(HttpMethod.PUT.name());
        return result;
    }

    private static boolean isNormalized(HttpServletRequest request) {
        if (!isNormalized(request.getRequestURI())) {
            return false;
        }
        if (!isNormalized(request.getContextPath())) {
            return false;
        }
        if (!isNormalized(request.getServletPath())) {
            return false;
        }
        if (!isNormalized(request.getPathInfo())) {
            return false;
        }
        return true;
    }

    private static boolean encodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getContextPath(), value)) {
            return true;
        }
        return valueContains(request.getRequestURI(), value);
    }

    private static boolean decodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getServletPath(), value)) {
            return true;
        }
        if (valueContains(request.getPathInfo(), value)) {
            return true;
        }
        return false;
    }

    private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
        int length = uri.length();
        for (int i = 0; i < length; i++) {
            char c = uri.charAt(i);
            if (c < '\u0020' || c > '\u007e') {
                return false;
            }
        }

        return true;
    }

    private static boolean valueContains(String value, String contains) {
        return value != null && value.contains(contains);
    }

    private static boolean isNormalized(String path) {
        if (path == null) {
            return true;
        }

        if (path.indexOf("//") > -1) {
            return false;
        }

        for (int j = path.length(); j > 0;) {
            int i = path.lastIndexOf('/', j - 1);
            int gap = j - i;

            if (gap == 2 && path.charAt(i + 1) == '.') {
                // ".", "/./" or "/."
                return false;
            } else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
                return false;
            }

            j = i;
        }

        return true;
    }

}

STEP 2 : Create a FirewalledResponse class

package com.biz.brains.project.security.firewall;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

class FirewalledResponse extends HttpServletResponseWrapper {
    private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
    private static final String LOCATION_HEADER = "Location";
    private static final String SET_COOKIE_HEADER = "Set-Cookie";

    public FirewalledResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        // TODO: implement pluggable validation, instead of simple blacklisting.
        // SEC-1790. Prevent redirects containing CRLF
        validateCrlf(LOCATION_HEADER, location);
        super.sendRedirect(location);
    }

    @Override
    public void setHeader(String name, String value) {
        validateCrlf(name, value);
        super.setHeader(name, value);
    }

    @Override
    public void addHeader(String name, String value) {
        validateCrlf(name, value);
        super.addHeader(name, value);
    }

    @Override
    public void addCookie(Cookie cookie) {
        if (cookie != null) {
            validateCrlf(SET_COOKIE_HEADER, cookie.getName());
            validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
            validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
            validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
            validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
        }
        super.addCookie(cookie);
    }

    void validateCrlf(String name, String value) {
        if (hasCrlf(name) || hasCrlf(value)) {
            throw new IllegalArgumentException(
                    "Invalid characters (CR/LF) in header " + name);
        }
    }

    private boolean hasCrlf(String value) {
        return value != null && CR_OR_LF.matcher(value).find();
    }
}

STEP 3: Create a custom Filter to suppress the RejectedException

package com.biz.brains.project.security.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            try {
                RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
                if(Objects.nonNull(requestRejectedException)) {
                    throw requestRejectedException;
                }else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } catch (RequestRejectedException requestRejectedException) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                log
                    .error(
                            "request_rejected: remote={}, user_agent={}, request_url={}",
                            httpServletRequest.getRemoteHost(),  
                            httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
                            httpServletRequest.getRequestURL(), 
                            requestRejectedException
                    );

                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
}

STEP 4: Add the custom filter to spring filter chain in security configuration

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.addFilterBefore(new RequestRejectedExceptionFilter(),
             ChannelProcessingFilter.class);
}

Now using above fix, we can handle RequestRejectedException with Error 404 page.

How to use Ajax.ActionLink?

Ajax.ActionLink only sends an ajax request to the server. What happens ahead really depends upon type of data returned and what your client side script does with it. You may send a partial view for ajax call or json, xml etc. Ajax.ActionLink however have different callbacks and parameters that allow you to write js code on different events. You can do something before request is sent or onComplete. similarly you have an onSuccess callback. This is where you put your JS code for manipulating result returned by server. You may simply put it back in UpdateTargetID or you can do fancy stuff with this result using jQuery or some other JS library.

Completely Remove MySQL Ubuntu 14.04 LTS

Different solution for those still having issues. Hopefully I can help those trying to reinstall Mysql. Note, It's a seek and destroy mission. So be weary. Assuming your root:

apt-get purge mysql*
apt-get purge dbconfig-common #the screen used for mysql password
find / -name *mysql*          #delete any traces of mysql
#insert apt-get cleanups, autoremove,updates etc.

Originally, something leftover was interfering with my startup of mysqlserver-5.5. These commands ended up resolving the issue for myself.

IntelliJ Organize Imports

Just move your mouse over the missing view and hit keys on windows ALT + ENTER

How to handle Pop-up in Selenium WebDriver using Java

public void Test(){

     WebElement sign = fc.findElement(By.xpath(".//*[@id='login-scroll']/a"));
        sign.click();
        WebElement LoginAsGuest=fc.findElement(By.xpath(".//*[@id='guest-login-option']"));
        LoginAsGuest.click();
        WebElement email_id= fc.findElement(By.xpath(".//*[@id='guestemail']"));
        email_id.sendKeys("[email protected]");
        WebElement ContinueButton=fc.findElement(By.xpath(".//*[@id='contibutton']"));
        ContinueButton.click();

}

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

AngularJS: How do I manually set input to $valid in controller?

You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.

What you should do is to set the validity of the input element. Like so;

addItem.capabilities.$setValidity("youAreFat", false);

Now the input (and so the form) is invalid. You can also see which error causes invalidation.

addItem.capabilities.errors.youAreFat == true;

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

How do I get the Back Button to work with an AngularJS ui-router state machine?

The Back button wasn't working for me as well, but I figured out that the problem was that I had html content inside my main page, in the ui-view element.

i.e.

<div ui-view>
     <h1> Hey Kids! </h1>
     <!-- More content -->
</div>

So I moved the content into a new .html file, and marked it as a template in the .js file with the routes.

i.e.

   .state("parent.mystuff", {
        url: "/mystuff",
        controller: 'myStuffCtrl',
        templateUrl: "myStuff.html"
    })

What does "collect2: error: ld returned 1 exit status" mean?

clrscr is not standard C function. According to internet, it used to be a thing in old Borland C.
Is clrscr(); a function in C++?

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Loading PictureBox Image from resource file with path (Part 3)

Setting "Copy to Output Directory" to "Copy always" or "Copy if newer" may help for you.

Your PicPath is a relative path that is converted into an absolute path at some time while loading the image. Most probably you will see that there are no images on the specified location if you use Path.GetFullPath(PicPath) in Debug.

jQuery click / toggle between two functions

I would do something like this for the code you showed, if all you need to do is toggle a value :

var oddClick = true;
$("#time").click(function() {
    $(this).animate({
        width: oddClick ? 260 : 30
    },1500);
    oddClick = !oddClick;
});

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:

wordA((?:\s|&nbsp;)*)wordB(?!(?:\s|&nbsp;)wordc)

The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

How do I put a variable inside a string?

Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().

"hello " + str(10) + " world" = "hello 10 world"

Hope that helps!

Jquery - How to get the style display attribute "none / block"

My answer

/**
 * Display form to reply comment
 */
function displayReplyForm(commentId) {
    var replyForm = $('#reply-form-' + commentId);
    if (replyForm.css('display') == 'block') { // Current display
        replyForm.css('display', 'none');
    } else { // Hide reply form
        replyForm.css('display', 'block');
    }
}

How to check if click event is already bound - JQuery

As of June 2019, I've updated the function (and it's working for what I need)

$.fn.isBound = function (type) {
    var data = $._data($(this)[0], 'events');

    if (data[type] === undefined || data.length === 0) {
        return false;
    }
    return true;
};

How to use random in BATCH script?

@echo off
title Professional Hacker
color 02
:matrix
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%% 
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%% 
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%% 
goto matrix

Set a default parameter value for a JavaScript function

If you are using ES6+ you can set default parameters in the following manner:

_x000D_
_x000D_
function test (foo = 1, bar = 2) {_x000D_
  console.log(foo, bar);_x000D_
}_x000D_
_x000D_
test(5); // foo gets overwritten, bar remains default parameter
_x000D_
_x000D_
_x000D_

If you need ES5 syntax you can do it in the following manner:

_x000D_
_x000D_
function test(foo, bar) {_x000D_
  foo = foo || 2;_x000D_
  bar = bar || 0;_x000D_
  _x000D_
  console.log(foo, bar);_x000D_
}_x000D_
_x000D_
test(5); // foo gets overwritten, bar remains default parameter
_x000D_
_x000D_
_x000D_

In the above syntax the OR operator is used. The OR operator always returns the first value if this can be converted to true if not it returns the righthandside value. When the function is called with no corresponding argument the parameter variable (bar in our example) is set to undefined by the JS engine. undefined Is then converted to false and thus does the OR operator return the value 0.

What does -save-dev mean in npm install grunt --save-dev

For me the first answer appears a bit confusing, so to make it short and clean:

npm install <package_name> saves any specified packages into dependencies by default. Additionally, you can control where and how they get saved with some additional flags:

npm install <package_name> --no-save Prevents saving to dependencies.

npm install <package_name> ---save-dev updates the devDependencies in your package. These are only used for local testing and development.

You can read more at in the dcu

How to read response headers in angularjs?

Additionally to Eugene Retunsky's answer, quoting from $http documentation regarding the response:

The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions.

  • status{number} – HTTP status code of the response.

  • headers{function([headerName])} – Header getter function.

  • config{Object} – The configuration object that was used to generate the request.

  • statusText{string} – HTTP status text of the response.

Please note that the argument callback order for $resource (v1.6) is not the same as above:

Success callback is called with (value (Object|Array), responseHeaders (Function), status (number), statusText (string)) arguments, where the value is the populated resource instance or collection object. The error callback is called with (httpResponse) argument.

Find if variable is divisible by 2

You don't need jQuery. Just use JavaScript's Modulo operator.

How to autosize a textarea using Prototype?

I needed this function for myself, but none of the ones from here worked as I needed them.

So I used Orion's code and changed it.

I added in a minimum height, so that on the destruct it does not get too small.

function resizeIt( id, maxHeight, minHeight ) {
    var text = id && id.style ? id : document.getElementById(id);
    var str = text.value;
    var cols = text.cols;
    var linecount = 0;
    var arStr = str.split( "\n" );
    $(arStr).each(function(s) {
        linecount = linecount + 1 + Math.floor(arStr[s].length / cols); // take into account long lines
    });
    linecount++;
    linecount = Math.max(minHeight, linecount);
    linecount = Math.min(maxHeight, linecount);
    text.rows = linecount;
};

Simple file write function in C++

You need to declare the prototype of your writeFile function, before actually using it:

int writeFile( void );

int main( void )
{
   ...

Github: Can I see the number of downloads for a repo?

Update 2019:

Ustin's answer points to:


Update 2017

You still can use the GitHub API to get the download count for your releases (which is not exactly what was asked)
See "Get a single release", the download_count field.

There is no longer a traffic screen mentioning the number of repo clones.
Instead, you have to rely on third-party services like:

Git 2.14.2 release


Update August 2014

GitHub also proposes the number of clones for repo in its Traffic Graph:
See "Clone Graphs"

http://i.stack.imgur.com/uycEZ.png


Update October 2013

As mentioned below by andyberry88, and as I detailed last July, GitHub now proposes releases (see its API), which has a download_count field.

Michele Milidoni, in his (upvoted) answer, does use that field in his python script.
(very small extract)

c.setopt(c.URL, 'https://api.github.com/repos/' + full_name + '/releases')
for p in myobj:
    if "assets" in p:
        for asset in p['assets']:
            print (asset['name'] + ": " + str(asset['download_count']) +
                   " downloads")

Original answer (December 2010)

I am not sure you can see that information (if it is recorded at all), because I don't see it in the GitHub Repository API:

$ curl http://github.com/api/v2/yaml/repos/show/schacon/grit
---
repository:
  :name: grit
  :owner: schacon
  :source: mojombo/grit # The original repo at top of the pyramid
  :parent: defunkt/grit # This repo's direct parent
  :description: Grit is a Ruby library for extracting information from a
  git repository in an object oriented manner - this fork tries to
  intergrate as much pure-ruby functionality as possible
  :forks: 4
  :watchers: 67
  :private: false
  :url: http://github.com/schacon/grit
  :fork: true
  :homepage: http://grit.rubyforge.org/
  :has_wiki: true
  :has_issues: false
  :has_downloads: true

You can only see if it has downloads or not.


Adam Jagosz reports in the comments:

I got it to work with

 curl -H "Accept: application/vnd.github.v3+json"   https://api.github.com/repos/:user/:repo/releases

A couple of things that I had wrong:

  • I needed an actual Github release (not just git tag, even though Github does display those under releases, ugh).
  • And the release needs an asset file other than the zipped source that is added automatically in order to get the download count.

How do I write data to csv file in columns and rows from a list in python?

>>> import csv
>>> with open('test.csv', 'wb') as f:
...     wtr = csv.writer(f, delimiter= ' ')
...     wtr.writerows( [[1, 2], [2, 3], [4, 5]])
...
>>> with open('test.csv', 'r') as f:
...     for line in f:
...         print line,
...
1 2 <<=== Exactly what you said that you wanted.
2 3
4 5
>>>

To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon.

How to make an introduction page with Doxygen

As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE. So make sure to add your index file, e.g. README.md, to INPUT and set it as this option's value:

INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md

Display loading image while post with ajax

This is very simple and easily manage.

jQuery(document).ready(function(){
jQuery("#search").click(function(){
    jQuery("#loader").show("slow");
    jQuery("#response_result").hide("slow");
    jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
        setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
            });
});

})
function finishAjax(id,response){ 
      jQuery("#loader").hide("slow");   
      jQuery('#response_result').html(unescape(response));
      jQuery("#"+id).show("slow");      
      return true;
}

SQL: sum 3 columns when one column has a null value?

I would try this:

select sum (case when TotalHousM is null then 0 else TotalHousM end)
       + (case when TotalHousT is null then 0 else TotalHousT end)
       + (case when TotalHousW is null then 0 else TotalHousW end)
       + (case when TotalHousTH is null then 0 else TotalHousTH end)
       + (case when TotalHousF is null then 0 else TotalHousF end)
       as Total
From LeaveRequest

Command to get latest Git commit hash from a branch

Try using git log -n 1 after doing a git checkout branchname. This shows the commit hash, author, date and commit message for the latest commit.

Perform a git pull origin/branchname first, to make sure your local repo matches upstream.

If perhaps you would only like to see a list of the commits your local branch is behind on the remote branch do this:

git fetch origin
git cherry localbranch remotebranch

This will list all the hashes of the commits that you have not yet merged into your local branch.

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

Ignore python multiple return value

One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:

def f():
    return 1, 2, 3

_, _, x = f()

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

How can I open Java .class files in a human-readable way?

If you don't mind reading bytecode, javap should work fine. It's part of the standard JDK installation.

Usage: javap <options> <classes>...

where options include:
   -c                        Disassemble the code
   -classpath <pathlist>     Specify where to find user class files
   -extdirs <dirs>           Override location of installed extensions
   -help                     Print this usage message
   -J<flag>                  Pass <flag> directly to the runtime system
   -l                        Print line number and local variable tables
   -public                   Show only public classes and members
   -protected                Show protected/public classes and members
   -package                  Show package/protected/public classes
                             and members (default)
   -private                  Show all classes and members
   -s                        Print internal type signatures
   -bootclasspath <pathlist> Override location of class files loaded
                             by the bootstrap class loader
   -verbose                  Print stack size, number of locals and args for methods
                             If verifying, print reasons for failure

Can you disable tabs in Bootstrap?

In addition to James's answer:

If you need to disable the link use

$('a[data-toggle="tab"]').addClass('disabled');

If you need to prevent a disabled link from loading the tab

$('a[data-toggle="tab"]').click(function(e){

            if($this.hasClass("disabled")){

                e.preventDefault();

                e.stopPropagation();

                e.stopImmediatePropagation();

                return false;

            }
}

If you need to unable the link

$('a[data-toggle="tab"]').removeClass('disabled');

How to set time to a date object in java

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date d = cal.getTime();

Also See

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

A non well formed numeric value encountered

Because you are passing a string as the second argument to the date function, which should be an integer.

string date ( string $format [, int $timestamp = time() ] )

Try strtotime which will Parse about any English textual datetime description into a Unix timestamp (integer):

date("d", strtotime($_GET['start_date']));

How to globally replace a forward slash in a JavaScript string?

Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.

var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);

How to run bootRun with spring profile via gradle task

For anyone looking how to do this in Kotlin DSL, here's a working example for build.gradle.kts:

tasks.register("bootRunDev") {
    group = "application"
    description = "Runs this project as a Spring Boot application with the dev profile"
    doFirst {
        tasks.bootRun.configure {
            systemProperty("spring.profiles.active", "dev")
        }
    }
    finalizedBy("bootRun")
}

Converting Milliseconds to Minutes and Seconds?

You can try proceeding this way:

Pass ms value from

Long ms = watch.getTime();

to

getDisplayValue(ms)

Kotlin implementation:

fun getDisplayValue(ms: Long): String {
        val duration = Duration.ofMillis(ms)
        val minutes = duration.toMinutes()
        val seconds = duration.minusMinutes(minutes).seconds

        return "${minutes}min ${seconds}sec"
}

Java implementation:

public String getDisplayValue(Long ms) {
        Duration duration = Duration.ofMillis(ms);
        Long minutes = duration.toMinutes();
        Long seconds = duration.minusMinutes(minutes).getSeconds();

        return minutes + "min " + seconds "sec"
}

How to call Base Class's __init__ method from the child class?

If you are using Python 3, it is recommended to simply call super() without any argument:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Do not call super with class as it may lead to infinite recursion exceptions as per this answer.

Printing HashMap In Java

I did it using String map (if you're working with String Map).

for (Object obj : dados.entrySet()) {
    Map.Entry<String, String> entry = (Map.Entry) obj;
    System.out.print("Key: " + entry.getKey());
    System.out.println(", Value: " + entry.getValue());
}

Why am I getting error for apple-touch-icon-precomposed.png

If you don't care about the icon looking pretty on all sort of Apple devices, just add

get '/:apple_touch_icon' => redirect('/icon.png'), constraints: { apple_touch_icon: /apple-touch-icon(-\d+x\d+)?(-precomposed)?\.png/ }

to your config/routes.rb file and some icon.png to your public directory. Redirecting to 404.html instead of icon.png works too.

Memcached vs. Redis?

Use Redis if

  1. You require selectively deleting/expiring items in the cache. (You need this)

  2. You require the ability to query keys of a particular type. eq. 'blog1:posts:*', 'blog2:categories:xyz:posts:*'. oh yeah! this is very important. Use this to invalidate certain types of cached items selectively. You can also use this to invalidate fragment cache, page cache, only AR objects of a given type, etc.

  3. Persistence (You will need this too, unless you are okay with your cache having to warm up after every restart. Very essential for objects that seldom change)

Use memcached if

  1. Memcached gives you headached!
  2. umm... clustering? meh. if you gonna go that far, use Varnish and Redis for caching fragments and AR Objects.

From my experience I've had much better stability with Redis than Memcached

Angular ng-if="" with multiple arguments

Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

Angular2+

*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

boolean check1 = Your conditional check here...
...

Postgres Error: More than one row returned by a subquery used as an expression

The fundamental problem can often be simply solved by changing an = to IN, in cases where you've got a one-to-many relationship. For example, if you wanted to update or delete a bunch of accounts for a given customer:

WITH accounts_to_delete AS 
    ( 
        SELECT     account_id
        FROM       accounts a
        INNER JOIN customers c
                ON a.customer_id = c.id
        WHERE      c.customer_name='Some Customer'
    )

-- this fails if "Some Customer" has multiple accounts, but works if there's 1:
DELETE FROM accounts
 WHERE accounts.guid = 
( 
    SELECT account_id 
    FROM   accounts_to_delete 
);

-- this succeeds with any number of accounts:
DELETE FROM accounts
 WHERE accounts.guid IN   
( 
    SELECT account_id 
    FROM   accounts_to_delete 
);

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

Resizable table columns with jQuery

Here's a short complete html example. See demo http://jsfiddle.net/CU585/

<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>

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

This error is very common, often the very first one you get on trying to establish a connection to your database. I suggest those 6 steps to fix ORA-12154 :

  1. Check instance name has been entered correctly in tnsnames.ora.
  2. There should be no control characters at the end of the instance or database name.
  3. All paranthesis around the TNS entry should be properly terminated
  4. Domain name entry in sqlnet.ora should not be conflicting with full database name.
  5. If problem still persists, try to re-create TNS entry in tnsnames.ora.
  6. At last you may add new entries using the SQL*Net Easy configuration utility.

For more informations : http://turfybot.free.fr/oracle/11g/errors/ORA-12154.html

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

How do I tell if a regular file does not exist in Bash?

The test command ([ here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:

if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

Django - filtering on foreign key properties

This has been possible since the queryset-refactor branch landed pre-1.0. Ticket 4088 exposed the problem. This should work:

Asset.objects.filter(
    desc__contains=filter,
    project__name__contains="Foo").order_by("desc")

The Django Many-to-one documentation has this and other examples of following Foreign Keys using the Model API.

Form Validation With Bootstrap (jQuery)

enter image description here

Here is a very simple and lightweight plugin for validation with Boostrap, you can use it if you like: https://github.com/wpic/bootstrap.validator.js

How to use both onclick and target="_blank"

onclick="window.open('your_html', '_blank')"

Uploading both data and files in one form using Ajax?

For me, it didn't work without enctype: 'multipart/form-data' field in the Ajax request. I hope it helps someone who is stuck in a similar problem.

Even though the enctype was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype without explicit declaration (jQuery 3.3.1).

// Tested, this works for me (jQuery 3.3.1)

fileUploadForm.submit(function (e) {   
    e.preventDefault();
    $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            enctype: 'multipart/form-data',
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function (data) {
                console.log('Thank God it worked!');
            }
        }
    );
});

// enctype field was set in the form but Ajax request didn't set it by default.

<form action="process/file-upload" enctype="multipart/form-data" method="post" >

     <input type="file" name="input-file" accept="text/plain" required> 
     ...
</form>

As others mentioned above, please also pay special attention to the contentType and processData fields.

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

use mysql SUM() in a WHERE clause

When using aggregate functions to filter, you must use a HAVING statement.

SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

I am very late to this question, however I did encounter this problem and, after much searching, I found this information from Bryan Kennedy: http://plusbryan.com/mysql-replication-without-downtime

On Master take a backup like this:
mysqldump --skip-lock-tables --single-transaction --flush-logs --hex-blob --master-data=2 -A > ~/dump.sql

Now, examine the head of the file and jot down the values for MASTER_LOG_FILE and MASTER_LOG_POS. You will need them later: head dump.sql -n80 | grep "MASTER_LOG"

Copy the "dump.sql" file over to Slave and restore it: mysql -u mysql-user -p < ~/dump.sql

Connect to Slave mysql and run a command like this: CHANGE MASTER TO MASTER_HOST='master-server-ip', MASTER_USER='replication-user', MASTER_PASSWORD='slave-server-password', MASTER_LOG_FILE='value from above', MASTER_LOG_POS=value from above; START SLAVE;

To check the progress of Slave: SHOW SLAVE STATUS;

If all is well, Last_Error will be blank, and Slave_IO_State will report “Waiting for master to send event”. Look for Seconds_Behind_Master which indicates how far behind it is. YMMV. :)

How to remove focus from input field in jQuery?

For all textbox :

$(':text').blur()

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

What is difference between sjlj vs dwarf vs seh?

SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks

DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.

SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.

source: https://wiki.qt.io/MinGW-64-bit

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

As addition of good answers, You don't have to use [FromForm] to get form data in controller. Framework automatically convert form data to model as you wish. You can implement like following.

[HttpPost]
public async Task<IActionResult> Submit(MyModel model)
{
    //...
}

Execute action when back bar button of UINavigationController is pressed

It's not difficult as we thing. Just create a frame for UIButton with clear background color, assign action for the button and place over the navigationbar back button. And finally remove the button after use.

Here is the Swift 3 sample code done with UIImage instead of UIButton

override func viewDidLoad() {
    super.viewDidLoad()
    let imageView = UIImageView()
    imageView.backgroundColor = UIColor.clear
    imageView.frame = CGRect(x:0,y:0,width:2*(self.navigationController?.navigationBar.bounds.height)!,height:(self.navigationController?.navigationBar.bounds.height)!)
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(back(sender:)))
    imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(tapGestureRecognizer)
    imageView.tag = 1
    self.navigationController?.navigationBar.addSubview(imageView)
    }

write the code need to be executed

func back(sender: UIBarButtonItem) {

    // Perform your custom actions}
    _ = self.navigationController?.popViewController(animated: true)

    }

Remove the subView after action is performed

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    for view in (self.navigationController?.navigationBar.subviews)!{
        if view.tag == 1 {
            view.removeFromSuperview()
        }
    }

What's an easy way to read random line from a file in Unix command line?

#!/bin/bash

IFS=$'\n' wordsArray=($(<$1))

numWords=${#wordsArray[@]}
sizeOfNumWords=${#numWords}

while [ True ]
do
    for ((i=0; i<$sizeOfNumWords; i++))
    do
        let ranNumArray[$i]=$(( ( $RANDOM % 10 )  + 1 ))-1
        ranNumStr="$ranNumStr${ranNumArray[$i]}"
    done
    if [ $ranNumStr -le $numWords ]
    then
        break
    fi
    ranNumStr=""
done

noLeadZeroStr=$((10#$ranNumStr))
echo ${wordsArray[$noLeadZeroStr]}

How to affect other elements when one element is hovered

If the cube is directly inside the container:

#container:hover > #cube { background-color: yellow; }

If cube is next to (after containers closing tag) the container:

#container:hover + #cube { background-color: yellow; }

If the cube is somewhere inside the container:

#container:hover #cube { background-color: yellow; }

If the cube is a sibling of the container:

#container:hover ~ #cube { background-color: yellow; }

MemoryStream - Cannot access a closed Stream

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

However, the StreamWriter you're using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter, which is then trying to close the stream).

The best way to fix this is: don't use using and don't dispose of the StreamReader and StreamWriter. See this question.

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    var sr = new StreamReader(ms);

    sw.WriteLine("data");
    sw.WriteLine("data 2");
    ms.Position = 0;

    Console.WriteLine(sr.ReadToEnd());                        
}

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

StreamWriter sw = null;
StreamReader sr = null;

try
{
    using (var ms = new MemoryStream())
    {
        sw = new StreamWriter(ms);
        sr = new StreamReader(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;

        Console.WriteLine(sr.ReadToEnd());                        
    }
}
finally
{
    if (sw != null) sw.Dispose();
    if (sr != null) sr.Dispose();
}

Stop MySQL service windows

The Top Voted Answer is out of date. I just installed MySQL 5.7 and the service name is now MySQL57 so the new command is

net stop MySQL57

Why is setState in reactjs Async instead of Sync?

You can call a function after the state value has updated:

this.setState({foo: 'bar'}, () => { 
    // Do something here. 
});

Also, if you have lots of states to update at once, group them all within the same setState:

Instead of:

this.setState({foo: "one"}, () => {
    this.setState({bar: "two"});
});

Just do this:

this.setState({
    foo: "one",
    bar: "two"
});

What is the meaning of "this" in Java?

To be complete, this can also be used to refer to the outer object

class Outer {
    class Inner {
        void foo() {
            Outer o = Outer.this;
    }
  }
}

How to make a query with group_concat in sql server

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , STUFF((
          SELECT ',' + T.maskdetail
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH('')), 1, 1, '') as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by  A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname

Connect Java to a MySQL database

String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";

// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);

fopen deprecated warning

I'am using VisualStdio 2008. In this case I often set Preprocessor Definitions

Menu \ Project \ [ProjectName] Properties... Alt+F7

If click this menu or press Alt + F7 in project window, you can see "Property Pages" window.

Then see menu on left of window.

Configuration Properties \ C/C++ \ Preprocessor

Then add _CRT_SECURE_NO_WARNINGS to \ Preprocessor Definitions.

How to use OUTPUT parameter in Stored Procedure

SqlCommand yourCommand = new SqlCommand();
yourCommand.Connection = yourSqlConn;
yourCommand.Parameters.Add("@yourParam");
yourCommand.Parameters["@yourParam"].Direction = ParameterDirection.Output;

// execute your query successfully

int yourResult = yourCommand.Parameters["@yourParam"].Value;

PHP: How do I display the contents of a textfile on my page?

I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:

$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);

echo '<code>';
echo '<pre>';

echo $a;

echo '</pre>';
echo '</code>';

input type="submit" Vs button tag are they interchangeable?

If you are talking about <input type=button>, it won't automatically submit the form

if you are talking about the <button> tag, that's newer and doesn't automatically submit in all browsers.

Bottom line, if you want the form to submit on click in all browsers, use <input type="submit">

How can I access a hover state in reactjs?

I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

onMouseOver={() => this.onMouseOver(someId)}
onMouseOut={() => this.onMouseOut(someId)

And implement the map as follows:

onMouseOver(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = setTimeout(() => {
    scrollPreviewToComponentId(listId);
  }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
  this.hoverHandleMap[listId] = handle;
}

onMouseOut(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = this.hoverHandleMap[listId];
  clearTimeout(handle);
  delete this.hoverHandleMap[listId];
}

And the map is like so,

hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};

I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

Android: Cancel Async Task

I would like to improve the code. When you canel the aSyncTask the onCancelled() (callback method of aSyncTask) gets automatically called, and there you can hide your progressBarDialog.

You can include this code as well:

public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            this.cancel(true);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            Toast.makeText(getApplicationContext(), "asynctack cancelled.....", Toast.LENGTH_SHORT).show();
            dialog.hide(); /*hide the progressbar dialog here...*/
            super.onCancelled();
        }

    }

How do I remove the file suffix and path portion from a path string in Bash?

The basename does that, removes the path. It will also remove the suffix if given and if it matches the suffix of the file but you would need to know the suffix to give to the command. Otherwise you can use mv and figure out what the new name should be some other way.

Replace Div Content onclick

A Third Answer

Sorry, maybe I have it correct this time...

jsFiddle Demo

var savedBox1, savedBox2, state1=0, state2=0;

jQuery(document).ready(function() {
    jQuery(".rec1").click(function() {
        if (state1==0){
            savedBox1 = jQuery('#rec-box').html();
            jQuery('#rec-box').html(jQuery(this).next().html()); 
            state1 = 1;
        }else{
            jQuery('#rec-box').html(savedBox1); 
            state1 = 0;
        }
    });

    jQuery(".rec2").click(function() {
        if (state1==0){
            savedBox2 = jQuery('#rec-box2').html();
            jQuery('#rec-box2').html(jQuery(this).next().html()); 
            state2 = 1;
        }else{
            jQuery('#rec-box2').html(savedBox2); 
            state2 = 0;
        }
    });
});

How do I escape special characters in MySQL?

MySQL has the string function QUOTE, and it should solve this problem:

How to catch and print the full exception traceback without halting/exiting the program?

How to print the full traceback without halting the program?

When you don't want to halt your program on an error, you need to handle that error with a try/except:

try:
    do_something_that_might_error()
except Exception as error:
    handle_the_error(error)

To extract the full traceback, we'll use the traceback module from the standard library:

import traceback

And to create a decently complicated stacktrace to demonstrate that we get the full stacktrace:

def raise_error():
    raise RuntimeError('something bad happened!')

def do_something_that_might_error():
    raise_error()

Printing

To print the full traceback, use the traceback.print_exc method:

try:
    do_something_that_might_error()
except Exception as error:
    traceback.print_exc()

Which prints:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Better than printing, logging:

However, a best practice is to have a logger set up for your module. It will know the name of the module and be able to change levels (among other attributes, such as handlers)

import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

In which case, you'll want the logger.exception function instead:

try:
    do_something_that_might_error()
except Exception as error:
    logger.exception(error)

Which logs:

ERROR:__main__:something bad happened!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Or perhaps you just want the string, in which case, you'll want the traceback.format_exc function instead:

try:
    do_something_that_might_error()
except Exception as error:
    logger.debug(traceback.format_exc())

Which logs:

DEBUG:__main__:Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Conclusion

And for all three options, we see we get the same output as when we have an error:

>>> do_something_that_might_error()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Which to use

Performance concerns aren't important here as IO usually dominates. I'd prefer, since it does precisely what's being requested in a forward compatible way:

logger.exception(error)

Logging levels and outputs can be adjusted, making it easy to turn off without touching the code. And usually doing what's directly needed is the most efficient way to do it.

How to import Google Web Font in CSS file?

<link href="https://fonts.googleapis.com/css?family=(any font of your 
choice)" rel="stylesheet" type="text/css">

To choose the font you can visit the link : https://fonts.google.com

Write the font name of your choice from the website excluding the brackets.

For example you chose Lobster as a font of your choice then,

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" 
type="text/css">

Then you can use this normally as a font-family in your whole HTML/CSS file.

For example

<h2 style="Lobster">Please Like This Answer</h2>

Show Hide div if, if statement is true

A fresh look at this(possibly)
in your php:

else{
      $hidemydiv = "hide";
}

And then later in your html code:

<div class='<?php echo $hidemydiv ?>' > maybe show or hide this</div>

in this way your php remains quite clean

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How to identify server IP address in PHP

If you are using PHP version 5.3 or higher you can do the following:

$host= gethostname();
$ip = gethostbyname($host);

This works well when you are running a stand-alone script, not running through the web server.

set the iframe height automatically

If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.

What is the difference between an annotated and unannotated tag?

Push annotated tags, keep lightweight local

man git-tag says:

Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.

And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:

  • annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.

    Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.

  • git push --follow-tags will only push annotated tags
  • git describe without command line options only sees annotated tags

Internals differences

  • both lightweight and annotated tags are a file under .git/refs/tags that contains a SHA-1

  • for lightweight tags, the SHA-1 points directly to a commit:

    git tag light
    cat .git/refs/tags/light
    

    prints the same as the HEAD's SHA-1.

    So no wonder they cannot contain any other metadata.

  • annotated tags point to a tag object in the object database.

    git tag -as -m msg annot
    cat .git/refs/tags/annot
    

    contains the SHA of the annotated tag object:

    c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    and then we can get its content with:

    git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    sample output:

    object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
    type commit
    tag annot
    tagger Ciro Santilli <[email protected]> 1411478848 +0200
    
    msg
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.11 (GNU/Linux)
    
    <YOUR PGP SIGNATURE>
    -----END PGP SIGNAT
    

    And this is how it contains extra metadata. As we can see from the output, the metadata fields are:

    A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?

Bonuses

  • Determine if a tag is annotated:

    git cat-file -t tag
    

    Outputs

    • commit for lightweight, since there is no tag object, it points directly to the commit
    • tag for annotated, since there is a tag object in that case
  • List only lightweight tags: How can I list all lightweight tags?

Python Progress Bar

You can use tqdm:

from tqdm import tqdm

with tqdm(total=100, desc="Adding Users", bar_format="{l_bar}{bar} [ time left: {remaining} ]") as pbar:
    for i in range(100):
        time.sleep(3)
        pbar.update(1)

In this example the progress bar is running for 5 minutes and it is shown like that:

Adding Users:   3%|¦¦¦¦¦?                                     [ time left: 04:51 ]                                                                                                        

You can change it and customize it as you like.