Programs & Examples On #Nunit addins

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Function to convert column number to letter?

Here is a late answer, just for simplistic approach using Int() and If in case of 1-3 character columns:

Function outColLetterFromNumber(i As Integer) As String

    If i < 27 Then       'one-letter
        col = Chr(64 + i)
    ElseIf i < 677 Then  'two-letter
        col = Chr(64 + Int(i / 26)) & Chr(64 + i - (Int(i / 26) * 26))
    Else                 'three-letter
        col = Chr(64 + Int(i / 676)) & Chr(64 + Int(i - Int(i / 676) * 676) / 26)) & Chr(64 + i - (Int(i - Int(i / 676) * 676) / 26) * 26))
    End If

    outColLetterFromNumber = col

End Function

Counting no of rows returned by a select query

Try wrapping your entire select in brackets, then running a count(*) on that

select count(*)
from
(
   select m.id
   from Monitor as m 
    inner join Monitor_Request as mr 
       on mr.Company_ID=m.Company_id   group by m.Company_id
    having COUNT(m.Monitor_id)>=5
) myNewTable

Accessing Google Account Id /username via Android

Retrieve profile information for a signed-in user Use the GoogleSignInResult.getSignInAccount method to request profile information for the currently signed in user. You can call the getSignInAccount method after the sign-in intent succeeds.

GoogleSignInResult result = 
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();

How do I make the return type of a method generic?

You have to convert the type of your return value of the method to the Generic type which you pass to the method during calling.

    public static T values<T>()
    {
        Random random = new Random();
        int number = random.Next(1, 4);
        return (T)Convert.ChangeType(number, typeof(T));
    }

You need pass a type that is type casteable for the value you return through that method.

If you would want to return a value which is not type casteable to the generic type you pass, you might have to alter the code or make sure you pass a type that is casteable for the return value of method. So, this approach is not reccomended.

List<object>.RemoveAll - How to create an appropriate Predicate

A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

{
    List<Vehicle> vehicles;
    // Using a lambda
    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    // Using an equivalent anonymous method
    vehicles.RemoveAll(delegate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    });
    // Using an equivalent actual method
    vehicles.RemoveAll(VehiclePredicate);
}

private static bool VehiclePredicate(Vehicle vehicle)
{
    return vehicle.EnquiryID == 123;
}

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

ERROR Android emulator gets killed

In android studio version 4.0 (WINDOWS), I could find the solution by just checking android studio welcome screen and clicking on the "Events" dropdown AFTER trying to launch the emulator (hence after getting the error): enter image description here

the events section clearly shows that ANDROID_SDK_ROOT was not set in my system.

In a nutshell, whenever you see such error when starting the emulator, just check the "events" section in the welcome to android studio screen to find the real problem.

Beware that if ANDROID_HOME is not set properly, it will still tell you that ANDROID_SDK_ROOT is broken.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

This error occurs when the syntax of connection string is not valid.

You can use the connection string as

'jdbc:derby:MyDbTest;create=true'

or

you can use the following command in the command prompt, the command below creates a new database called MyDbTest succesfully:

connect 'jdbc:derby:MyDbTest;create=true';

Why is PHP session_destroy() not working?

If you need to clear the values of $_SESSION, set the array equal to an empty array:

$_SESSION = array();

Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.

Try the following:

session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable

How are people unit testing with Entity Framework 6, should you bother?

In order to unit test code that relies on your database you need to setup a database or mock for each and every test.

  1. Having a database (real or mocked) with a single state for all your tests will bite you quickly; you cannot test all records are valid and some aren't from the same data.
  2. Setting up an in-memory database in a OneTimeSetup will have issues where the old database is not cleared down before the next test starts up. This will show as tests working when you run them individually, but failing when you run them all.
  3. A Unit test should ideally only set what affects the test

I am working in an application that has a lot of tables with a lot of connections and some massive Linq blocks. These need testing. A simple grouping missed, or a join that results in more than 1 row will affect results.

To deal with this I have setup a heavy Unit Test Helper that is a lot of work to setup, but enables us to reliably mock the database in any state, and running 48 tests against 55 interconnected tables, with the entire database setup 48 times takes 4.7 seconds.

Here's how:

  1. In the Db context class ensure each table class is set to virtual

    public virtual DbSet<Branch> Branches { get; set; }
    public virtual DbSet<Warehouse> Warehouses { get; set; }
    
  2. In a UnitTestHelper class create a method to setup your database. Each table class is an optional parameter. If not supplied, it will be created through a Make method

    internal static Db Bootstrap(bool onlyMockPassedTables = false, List<Branch> branches = null, List<Products> products = null, List<Warehouses> warehouses = null)
    {
        if (onlyMockPassedTables == false) {
            branches ??= new List<Branch> { MakeBranch() };
            warehouses ??= new List<Warehouse>{ MakeWarehouse() };
        }
    
  3. For each table class, each object in it is mapped to the other lists

        branches?.ForEach(b => {
            b.Warehouse = warehouses.FirstOrDefault(w => w.ID == b.WarehouseID);
        });
    
        warehouses?.ForEach(w => {
            w.Branches = branches.Where(b => b.WarehouseID == w.ID);
        });
    
  4. And add it to the DbContext

         var context = new Db(new DbContextOptionsBuilder<Db>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
         context.Branches.AddRange(branches);
         context.Warehouses.AddRange(warehouses);
         context.SaveChanges();
         return context;
     }
    
  5. Define a list of IDs to make is easier to reuse them and make sure joins are valid

     internal const int BranchID = 1;
     internal const int WarehouseID = 2;
    
  6. Create a Make for each table to setup the most basic, but connected version it can be

     internal static Branch MakeBranch(int id = BranchID, string code = "The branch", int warehouseId = WarehouseID) => new Branch { ID = id, Code = code, WarehouseID = warehouseId };
     internal static Warehouse MakeWarehouse(int id = WarehouseID, string code = "B", string name = "My Big Warehouse") => new Warehouse { ID = id, Code = code, Name = name };
    

It's a lot of work, but it only needs doing once, and then your tests can be very focused because the rest of the database will be setup for it.

[Test]
[TestCase(new string [] {"ABC", "DEF"}, "ABC", ExpectedResult = 1)]
[TestCase(new string [] {"ABC", "BCD"}, "BC", ExpectedResult = 2)]
[TestCase(new string [] {"ABC"}, "EF", ExpectedResult = 0)]
[TestCase(new string[] { "ABC", "DEF" }, "abc", ExpectedResult = 1)]
public int Given_SearchingForBranchByName_Then_ReturnCount(string[] codesInDatabase, string searchString)
{
    // Arrange
    var branches = codesInDatabase.Select(x => UnitTestHelpers.MakeBranch(code: $"qqqq{x}qqq")).ToList();
    var db = UnitTestHelpers.Bootstrap(branches: branches);
    var service = new BranchService(db);

    // Act
    var result = service.SearchByName(searchString);

    // Assert
    return result.Count();
}

What are the alternatives now that the Google web search API has been deprecated?

Here is an option at the bottom of the Custom Search Control Panel: "Sites to search", you can choose "Search the entire web but emphasize included sites"

Custom Search Control Panel - Sites to search

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

The ~ selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Consider the following example:

_x000D_
_x000D_
.a ~ .b {_x000D_
  background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="b">1st</li>_x000D_
  <li class="a">2nd</li>_x000D_
  <li>3rd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="b">5th</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

.a ~ .b matches the 4th and 5th list item because they:

  • Are .b elements
  • Are siblings of .a
  • Appear after .a in HTML source order.

Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.

Changing Tint / Background color of UITabBar

Another solution (which is a hack) is to set the alpha on the tabBarController to 0.01 so that it is virtually invisible yet still clickable. Then set a an ImageView control on the bottom of the MainWindow nib with your custom tabbar image underneath the alpha'ed tabBarCOntroller. Then swap the images, change colors or hightlight when the tabbarcontroller switches views.

However, you lose the '...more' and customize functionality.

Convert sqlalchemy row object to python dict

if your models table column is not equie mysql column.

such as :

class People:
    id: int = Column(name='id', type_=Integer, primary_key=True)
    createdTime: datetime = Column(name='create_time', type_=TIMESTAMP,
                               nullable=False,
                               server_default=text("CURRENT_TIMESTAMP"),
                               default=func.now())
    modifiedTime: datetime = Column(name='modify_time', type_=TIMESTAMP,
                                server_default=text("CURRENT_TIMESTAMP"),
                                default=func.now())

Need to use:

 from sqlalchemy.orm import class_mapper 
 def asDict(self):
        return {x.key: getattr(self, x.key, None) for x in
            class_mapper(Application).iterate_properties}

if you use this way you can get modify_time and create_time both are None

{'id': 1, 'create_time': None, 'modify_time': None}


    def to_dict(self):
        return {c.name: getattr(self, c.name, None)
         for c in self.__table__.columns}

Because Class Attributes name not equal with column store in mysql

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

In your case, what you can do is:

z = dict(list(x.items()) + list(y.items()))

This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict's value:

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{'a': 1, 'c': 11, 'b': 10}

If you use Python 2, you can even remove the list() calls. To create z:

>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}

If you use Python version 3.9.0a4 or greater, then you can directly use:

x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = x | y
print(z)
{'a': 1, 'c': 11, 'b': 10}

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

OK so I think i know the issue you're having.

Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.

How to fix it (possibly) You need to add some extra information to your composer.json file.

"autoload": {
    "classmap": [
        "PATH TO YOUR MIGRATIONS FOLDER"
    ],
}

You need to add the path to your migrations folder to the classmap array. Then run the following three commands...

php artisan clear-compiled 
composer dump-autoload
php artisan optimize

This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.

Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).

Hope you can manage to get this sorted, as its very annoying indeed :(

How to get "GET" request parameters in JavaScript?

Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.

With an example:

// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else

var _GET = (function() {
    var _get = {};
    var re = /[?&]([^=&]+)(=?)([^&]*)/g;
    while (m = re.exec(location.search))
        _get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
    return _get;
})();

console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123

How to check if element exists using a lambda expression?

The above answers require you to malloc a new stream object.

public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {

    for (final T z : c) {
        if (p.test(z)) {
            return true;
        }
    }
    return false;
}

public boolean containsTabById(TabPane tabPane, String id) {
    return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
   ...
}

Efficiently sorting a numpy array in descending order?

Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.

x=np.sort(array)
y=np.fliplr(x)

np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!

Hope it helps you out!

I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

How to get the background color of an HTML element?

It depends which style from the div you need. Is this a background style which was defined in CSS or background style which was added through javascript(inline) to the current node?

In case of CSS style, you should use computed style. Like you do in getStyle().

With inline style you should use node.style reference: x.style.backgroundColor;

Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color, but backgroundColor;

Swift apply .uppercaseString to only the first letter of a string

For swift 5, you can simple do like that:

yourString.firstUppercased

Sample: "abc" -> "Abc"

how to draw smooth curve through N points using javascript HTML5 canvas?

As Daniel Howard points out, Rob Spencer describes what you want at http://scaledinnovation.com/analytics/splines/aboutSplines.html.

Here's an interactive demo: http://jsbin.com/ApitIxo/2/

Here it is as a snippet in case jsbin is down.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
    <html>_x000D_
      <head>_x000D_
        <meta charset=utf-8 />_x000D_
        <title>Demo smooth connection</title>_x000D_
      </head>_x000D_
      <body>_x000D_
        <div id="display">_x000D_
          Click to build a smooth path. _x000D_
          (See Rob Spencer's <a href="http://scaledinnovation.com/analytics/splines/aboutSplines.html">article</a>)_x000D_
          <br><label><input type="checkbox" id="showPoints" checked> Show points</label>_x000D_
          <br><label><input type="checkbox" id="showControlLines" checked> Show control lines</label>_x000D_
          <br>_x000D_
          <label>_x000D_
            <input type="range" id="tension" min="-1" max="2" step=".1" value=".5" > Tension <span id="tensionvalue">(0.5)</span>_x000D_
          </label>_x000D_
        <div id="mouse"></div>_x000D_
        </div>_x000D_
        <canvas id="canvas"></canvas>_x000D_
        <style>_x000D_
          html { position: relative; height: 100%; width: 100%; }_x000D_
          body { position: absolute; left: 0; right: 0; top: 0; bottom: 0; } _x000D_
          canvas { outline: 1px solid red; }_x000D_
          #display { position: fixed; margin: 8px; background: white; z-index: 1; }_x000D_
        </style>_x000D_
        <script>_x000D_
          function update() {_x000D_
            $("tensionvalue").innerHTML="("+$("tension").value+")";_x000D_
            drawSplines();_x000D_
          }_x000D_
          $("showPoints").onchange = $("showControlLines").onchange = $("tension").onchange = update;_x000D_
      _x000D_
          // utility function_x000D_
          function $(id){ return document.getElementById(id); }_x000D_
          var canvas=$("canvas"), ctx=canvas.getContext("2d");_x000D_
_x000D_
          function setCanvasSize() {_x000D_
            canvas.width = parseInt(window.getComputedStyle(document.body).width);_x000D_
            canvas.height = parseInt(window.getComputedStyle(document.body).height);_x000D_
          }_x000D_
          window.onload = window.onresize = setCanvasSize();_x000D_
      _x000D_
          function mousePositionOnCanvas(e) {_x000D_
            var el=e.target, c=el;_x000D_
            var scaleX = c.width/c.offsetWidth || 1;_x000D_
            var scaleY = c.height/c.offsetHeight || 1;_x000D_
          _x000D_
            if (!isNaN(e.offsetX)) _x000D_
              return { x:e.offsetX*scaleX, y:e.offsetY*scaleY };_x000D_
          _x000D_
            var x=e.pageX, y=e.pageY;_x000D_
            do {_x000D_
              x -= el.offsetLeft;_x000D_
              y -= el.offsetTop;_x000D_
              el = el.offsetParent;_x000D_
            } while (el);_x000D_
            return { x: x*scaleX, y: y*scaleY };_x000D_
          }_x000D_
      _x000D_
          canvas.onclick = function(e){_x000D_
            var p = mousePositionOnCanvas(e);_x000D_
            addSplinePoint(p.x, p.y);_x000D_
          };_x000D_
      _x000D_
          function drawPoint(x,y,color){_x000D_
            ctx.save();_x000D_
            ctx.fillStyle=color;_x000D_
            ctx.beginPath();_x000D_
            ctx.arc(x,y,3,0,2*Math.PI);_x000D_
            ctx.fill()_x000D_
            ctx.restore();_x000D_
          }_x000D_
          canvas.onmousemove = function(e) {_x000D_
            var p = mousePositionOnCanvas(e);_x000D_
            $("mouse").innerHTML = p.x+","+p.y;_x000D_
          };_x000D_
      _x000D_
          var pts=[]; // a list of x and ys_x000D_
_x000D_
          // given an array of x,y's, return distance between any two,_x000D_
          // note that i and j are indexes to the points, not directly into the array._x000D_
          function dista(arr, i, j) {_x000D_
            return Math.sqrt(Math.pow(arr[2*i]-arr[2*j], 2) + Math.pow(arr[2*i+1]-arr[2*j+1], 2));_x000D_
          }_x000D_
_x000D_
          // return vector from i to j where i and j are indexes pointing into an array of points._x000D_
          function va(arr, i, j){_x000D_
            return [arr[2*j]-arr[2*i], arr[2*j+1]-arr[2*i+1]]_x000D_
          }_x000D_
      _x000D_
          function ctlpts(x1,y1,x2,y2,x3,y3) {_x000D_
            var t = $("tension").value;_x000D_
            var v = va(arguments, 0, 2);_x000D_
            var d01 = dista(arguments, 0, 1);_x000D_
            var d12 = dista(arguments, 1, 2);_x000D_
            var d012 = d01 + d12;_x000D_
            return [x2 - v[0] * t * d01 / d012, y2 - v[1] * t * d01 / d012,_x000D_
                    x2 + v[0] * t * d12 / d012, y2 + v[1] * t * d12 / d012 ];_x000D_
          }_x000D_
_x000D_
          function addSplinePoint(x, y){_x000D_
            pts.push(x); pts.push(y);_x000D_
            drawSplines();_x000D_
          }_x000D_
          function drawSplines() {_x000D_
            clear();_x000D_
            cps = []; // There will be two control points for each "middle" point, 1 ... len-2e_x000D_
            for (var i = 0; i < pts.length - 2; i += 1) {_x000D_
              cps = cps.concat(ctlpts(pts[2*i], pts[2*i+1], _x000D_
                                      pts[2*i+2], pts[2*i+3], _x000D_
                                      pts[2*i+4], pts[2*i+5]));_x000D_
            }_x000D_
            if ($("showControlLines").checked) drawControlPoints(cps);_x000D_
            if ($("showPoints").checked) drawPoints(pts);_x000D_
    _x000D_
            drawCurvedPath(cps, pts);_x000D_
 _x000D_
          }_x000D_
          function drawControlPoints(cps) {_x000D_
            for (var i = 0; i < cps.length; i += 4) {_x000D_
              showPt(cps[i], cps[i+1], "pink");_x000D_
              showPt(cps[i+2], cps[i+3], "pink");_x000D_
              drawLine(cps[i], cps[i+1], cps[i+2], cps[i+3], "pink");_x000D_
            } _x000D_
          }_x000D_
      _x000D_
          function drawPoints(pts) {_x000D_
            for (var i = 0; i < pts.length; i += 2) {_x000D_
              showPt(pts[i], pts[i+1], "black");_x000D_
            } _x000D_
          }_x000D_
      _x000D_
          function drawCurvedPath(cps, pts){_x000D_
            var len = pts.length / 2; // number of points_x000D_
            if (len < 2) return;_x000D_
            if (len == 2) {_x000D_
              ctx.beginPath();_x000D_
              ctx.moveTo(pts[0], pts[1]);_x000D_
              ctx.lineTo(pts[2], pts[3]);_x000D_
              ctx.stroke();_x000D_
            }_x000D_
            else {_x000D_
              ctx.beginPath();_x000D_
              ctx.moveTo(pts[0], pts[1]);_x000D_
              // from point 0 to point 1 is a quadratic_x000D_
              ctx.quadraticCurveTo(cps[0], cps[1], pts[2], pts[3]);_x000D_
              // for all middle points, connect with bezier_x000D_
              for (var i = 2; i < len-1; i += 1) {_x000D_
                // console.log("to", pts[2*i], pts[2*i+1]);_x000D_
                ctx.bezierCurveTo(_x000D_
                  cps[(2*(i-1)-1)*2], cps[(2*(i-1)-1)*2+1],_x000D_
                  cps[(2*(i-1))*2], cps[(2*(i-1))*2+1],_x000D_
                  pts[i*2], pts[i*2+1]);_x000D_
              }_x000D_
              ctx.quadraticCurveTo(_x000D_
                cps[(2*(i-1)-1)*2], cps[(2*(i-1)-1)*2+1],_x000D_
                pts[i*2], pts[i*2+1]);_x000D_
              ctx.stroke();_x000D_
            }_x000D_
          }_x000D_
          function clear() {_x000D_
            ctx.save();_x000D_
            // use alpha to fade out_x000D_
            ctx.fillStyle = "rgba(255,255,255,.7)"; // clear screen_x000D_
            ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
            ctx.restore();_x000D_
          }_x000D_
      _x000D_
          function showPt(x,y,fillStyle) {_x000D_
            ctx.save();_x000D_
            ctx.beginPath();_x000D_
            if (fillStyle) {_x000D_
              ctx.fillStyle = fillStyle;_x000D_
            }_x000D_
            ctx.arc(x, y, 5, 0, 2*Math.PI);_x000D_
            ctx.fill();_x000D_
            ctx.restore();_x000D_
          }_x000D_
_x000D_
          function drawLine(x1, y1, x2, y2, strokeStyle){_x000D_
            ctx.beginPath();_x000D_
            ctx.moveTo(x1, y1);_x000D_
            ctx.lineTo(x2, y2);_x000D_
            if (strokeStyle) {_x000D_
              ctx.save();_x000D_
              ctx.strokeStyle = strokeStyle;_x000D_
              ctx.stroke();_x000D_
              ctx.restore();_x000D_
            }_x000D_
            else {_x000D_
              ctx.save();_x000D_
              ctx.strokeStyle = "pink";_x000D_
              ctx.stroke();_x000D_
              ctx.restore();_x000D_
            }_x000D_
          }_x000D_
_x000D_
        </script>_x000D_
_x000D_
_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Rails 4 - passing variable to partial

If you are using JavaScript to render then use escape_JavaScript("<%=render partial: partial_name, locals=>{@newval=>@oldval}%>");

echo that outputs to stderr

Another option that I recently stumbled on is this:

    {
        echo "First error line"
        echo "Second error line"
        echo "Third error line"
    } >&2

This uses only Bash built-ins while making multi-line error output less error prone (since you don't have to remember to add &>2 to every line).

How to remove new line characters from data rows in mysql?

Removes trailing returns when importing from Excel. When you execute this, you may receive an error that there is no WHERE; ignore and execute.

UPDATE table_name SET col_name = TRIM(TRAILING '\r' FROM col_name)

Size of character ('a') in C/C++

In C, the type of a character constant like 'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.

How to make background of table cell transparent

You are giving colour to the background and then expecting it to be transparent? Remove background-color: #D8F0DA,

If you want #D8F0DA to be the colour of text, use color: #D8F0DA

javascript onclick increment number

jQuery Library must be in the head section then.

<button onclick="var less = parseInt($('#qty').val()) - 1; $('#qty').val(less);"></button>
<input type="text" id="qty" value="2">
<button onclick="var add = parseInt($('#qty').val()) + 1; $('#qty').val(add);">+</button>

css absolute position won't work with margin-left:auto margin-right: auto

All answers were just a suggested solutions or workarounds. But still don't get answer to the question: why margin:auto works with position:relative but does not with position:absolute.

Following explanation was helpful for me:

"Margins make little sense on absolutely positioned elements since such elements are removed from the normal flow, thus they cannot push away any other elements on the page. Using margins like this can only affect the placement of the element to which the margin is applied, not any other element." http://www.justskins.com/forums/css-margins-and-absolute-82168.html

How can I use jQuery to make an input readonly?

Maybe use atribute disabled:

<input disabled="disabled" id="fieldName" name="fieldName" type="text" class="text_box" />

Or just use label tag: ;)

<label>

semaphore implementation

Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.

Some of the corrections you must make are:

1) You must make a variable of semaphore type

sem_t semvar;

2) The functions sem_wait(), sem_post() require the semaphore variable but you are passing the semaphore id, which makes no sense.

sem_wait(&semvar);
   //your critical section code
sem_post(&semvar);

3) You are passing the semaphore to sem_wait() and sem_post() without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.

ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
     perror("Semaphore failed to initialize");

Study the semaphore API's from the man page and go through this example.

nginx 502 bad gateway

You can make nginx ignore client aborts using:

location / {
  proxy_ignore_client_abort on;
}

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.

  1. Generate CA and the certificates (you can use openssl: Generating CA and self-signed certificates.
  2. Install root certificate (*.cer file) on the device - you can open it by Safari and it should redirect you to Settings
  3. When the certificated is installed, go to Certificate Trust Settings (Settings > General > About > Certificate Trust Settings) as in MattP answer.

If it is not possible then you need to change server trust evaluation.

More info in this document: Technical Q&A QA1948 HTTPS and Test Servers

find files by extension, *.html under a folder in nodejs

Based on Lucio's code, I made a module. It will return an away with all the files with specific extensions under the one. Just post it here in case anybody needs it.

var path = require('path'), 
    fs   = require('fs');


/**
 * Find all files recursively in specific folder with specific extension, e.g:
 * findFilesInDir('./project/src', '.html') ==> ['./project/src/a.html','./project/src/build/index.html']
 * @param  {String} startPath    Path relative to this file or other file which requires this files
 * @param  {String} filter       Extension name, e.g: '.html'
 * @return {Array}               Result files with path string in an array
 */
function findFilesInDir(startPath,filter){

    var results = [];

    if (!fs.existsSync(startPath)){
        console.log("no dir ",startPath);
        return;
    }

    var files=fs.readdirSync(startPath);
    for(var i=0;i<files.length;i++){
        var filename=path.join(startPath,files[i]);
        var stat = fs.lstatSync(filename);
        if (stat.isDirectory()){
            results = results.concat(findFilesInDir(filename,filter)); //recurse
        }
        else if (filename.indexOf(filter)>=0) {
            console.log('-- found: ',filename);
            results.push(filename);
        }
    }
    return results;
}

module.exports = findFilesInDir;

Activity has leaked window that was originally added

This happened to me when i am using ProgressDialog in AsyncTask. Actually i am using hide() method in onPostExecute. Based on the answer of @Alex Volovoy i need to use dismiss() with ProgressDialog to remove it in onPostExecute and its done.

progressDialog.hide(); // Don't use it, it gives error

progressDialog.dismiss(); // Use it

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

grep using a character vector with multiple patterns

This should work:

grep(pattern = 'A1|A9|A6', x = myfile$Letter)

Or even more simply:

library(data.table)
myfile$Letter %like% 'A1|A9|A6'

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

CSS how to make an element fade in and then fade out?

A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:

<style> 
p {
animation-name: example;
animation-duration: 2s;
}

@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>

I hope this is what you needed!

Visual Studio 2017: Display method references

For anyone who looks at this today after 2 years, Visual Studio 2019 (Community edition as well) shows the references

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

How do you convert a DataTable into a generic list?

I have added some modification to the code from this answer (https://stackoverflow.com/a/24588210/4489664) because for nullable Types it will return exception

public static List<T> DataTableToList<T>(this DataTable table) where T: new()
{
    List<T> list = new List<T>();
    var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new
        {
            PropertyInfo = propertyInfo,
            Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType
        }).ToList();

    foreach (var row in table.Rows.Cast<DataRow>())
    {
        T obj = new T();
        foreach (var typeProperty in typeProperties)
        {
            object value = row[typeProperty.PropertyInfo.Name];
            object safeValue = value == null || DBNull.Value.Equals(value)
                ? null
                : Convert.ChangeType(value, typeProperty.Type);

            typeProperty.PropertyInfo.SetValue(obj, safeValue, null);
        }
        list.Add(obj);
    }
    return list;
}

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

I was also facing the same issue.

I was using the code below in .aspx page without writing authentication configuration in web.config file. After writing the settings in Web.config, I am able to run my code.

<% If Request.IsAuthenticated Then%>
     <table></table>
<%end if%> 

How does collections.defaultdict work?

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int(), which will return the integer object 0. For the second example, default items are created using list(), which returns a new empty list object.

Bootstrap Modal sitting behind backdrop

In my case one of parents of my modal was animated and had this

.animated {
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
    z-index: 100;
}

The blocker here is animation-fill-mode: both;. I could not just move modal outside, so the solution was to override 'animation-fill-mode' to animation-fill-mode: none;. Animation still worked fine.

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

How to apply Hovering on html area tag?

You can use jQuery to achieve this

Example:

$(function () {
        $('.map').maphilight();
    });

Go through this LINK to know more.

If the above one doesnt work then go through this link.

EDIT :

Give same class to each area tag like class="mapping"

and try this below code

$('.mapping').mouseover(function() {
    alert($(this).attr('id'));
}).mouseout(function(){
    alert('Mouseout....');      
});

Setting a backgroundImage With React Inline Styles

If you are using ES5 -

backgroundImage: "url(" + Background + ")"

If you are using ES6 -

backgroundImage: `url(${Background})`

Basically removing unnecessary curly braces while adding value to backgroundImage property works will work.

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

Spring Boot default H2 jdbc connection (and H2 console)

I had only below properties in /resources/application.properties. After running spring boot, using this URL(http://localhost:8080/h2-console/), the table in H2 console was visible and read to view the table data, also you can run simple SQL commands. One thing, in your java code, while fetching data, the column names are upper-case, even though schema.sql is using lower-case names :)

spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=- 1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

It could be even caused by your ad blocker.

Try to disable it or adding an exception for the domain from which the images come from.

What is the equivalent of Java's System.out.println() in Javascript?

Essentially console.log("Put a message here.") if the browser has a supporting console.

Another typical debugging method is using alerts, alert("Put a message here.")

RE: Update II

This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.

Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print() method for evaluating expressions and printing them out. Checkout this documentation.

These links might be of interest to you.

QUnit and Automated Testing

JavaScript Unit Tests with QUnit

How to do jquery code AFTER page loading?

write the code that you want to be executed inside this. When your document is ready, this will be executed.

$(document).ready(function() { 

});

How to create JSON object using jQuery

Nested JSON object

var data = {
        view:{
            type: 'success', note:'Updated successfully',
        },
    };

You can parse this data.view.type and data.view.note

JSON Object and inside Array

var data = {
          view: [ 
                {type: 'success', note:'updated successfully'}
          ],  
     };

You can parse this data.view[0].type and data.view[0].note

Dynamically add child components in React

You need to pass your components as children, like this:

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);

And then append them in the component's body:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});

You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:

var App = React.createClass({

    getInitialState: function(){
        return [
            {id:1,name:"Some Name"}
        ]
    },

    addChild: function() {
        // State change will cause component re-render
        this.setState(this.state.concat([
            {id:2,name:"Another Name"}
        ]))
    }

    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <button onClick={this.addChild}>Add component</button>
                {
                    this.state.map((item) => (
                        <SampleComponent key={item.id} name={item.name}/>
                    ))
                }
            </div>
        );
    }

});

mat-form-field must contain a MatFormFieldControl

In my case, one of my closing parenthesis for "onChanges()" were missed on the input element and thus the input element was apparently not being rendered at all:

<input mat-menu-item 
      matInput type="text" 
      [formControl]="myFormControl"
      (ngModelChange)="onChanged()>

Is it possible to change the package name of an Android app on Google Play?

From Dianne Hackborn:

Things That Cannot Change:

The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.

More on things you cannot change here

Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.

Removing object properties with Lodash

You can use _.omit() for emitting the key from a JSON array if you have fewer objects:

_.forEach(data, (d) => {
    _.omit(d, ['keyToEmit1', 'keyToEmit2'])
});

If you have more objects, you can use the reverse of it which is _.pick():

_.forEach(data, (d) => {
    _.pick(d, ['keyToPick1', 'keyToPick2'])
});

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

How do I remove repeated elements from ArrayList?

Time Complexity : O(n) : Without Set

private static void removeDup(ArrayList<String> listWithDuplicateElements) {
    System.out.println(" Original Duplicate List :" + listWithDuplicateElements);
    List<String> listWithoutDuplicateElements = new ArrayList<>(listWithDuplicateElements.size());

    listWithDuplicateElements.stream().forEach(str -> {
        if (listWithoutDuplicateElements.indexOf(str) == -1) {
            listWithoutDuplicateElements.add(str);
        }
    });     

    System.out.println(" Without Duplicate List :" + listWithoutDuplicateElements);
}

Move to another EditText when Soft Keyboard Next is clicked on Android

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="vertical" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="666dp"
android:background="#1500FFe5"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<TextView
    android:id="@+id/TextView02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editGrWt"
    android:layout_marginTop="14dp"
    android:layout_toLeftOf="@+id/textView3"
    android:ems="6"
    android:text="    Diamond :"
    android:textColor="@color/background_material_dark"
    android:textSize="15sp" />
  <EditText
    android:id="@+id/editDWt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/TextView02"
    android:layout_alignLeft="@+id/editGrWt"
    android:background="@color/bright_foreground_inverse_material_light"
    android:ems="4"
    android:hint="Weight"
    android:inputType="numberDecimal"
    android:nextFocusLeft="@+id/editDRate"
    android:selectAllOnFocus="true"
    android:imeOptions="actionNext"

    />
 <requestFocus />


<TextView
    android:id="@+id/TextView03"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/TextView02"
    android:layout_below="@+id/TextView02"
    android:layout_marginTop="14dp"
    android:ems="6"
    android:text="    Diamond :"
    android:textColor="@color/background_material_dark"
    android:textSize="15sp" />

<EditText
    android:id="@+id/editDWt1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TextView03"
    android:layout_alignBottom="@+id/TextView03"
    android:layout_alignLeft="@+id/editDWt"
    android:background="@color/bright_foreground_inverse_material_light"
    android:ems="4"
    android:hint="Weight"
    android:inputType="numberDecimal"
    android:text="0"
    android:selectAllOnFocus="true"
    android:imeOptions="actionNext"/>
 <requestFocus />

<TextView
    android:id="@+id/TextView04"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editDWt1"
    android:layout_marginTop="14dp"
    android:layout_toLeftOf="@+id/textView3"
    android:ems="6"
    android:text="         Stone :"
    android:textColor="@color/background_material_dark"
    android:textSize="15sp" />

<EditText
    android:id="@+id/editStWt1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TextView04"
    android:layout_alignBottom="@+id/TextView04"
    android:layout_alignLeft="@+id/editDWt1"
    android:background="@color/bright_foreground_inverse_material_light"
    android:ems="4"
    android:hint="Weight"
    android:inputType="numberDecimal"
    android:nextFocusForward="@+id/editStRate1"
    android:imeOptions="actionNext" />
 <requestFocus />
  <TextView
     android:id="@+id/TextView05"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/TextView04"
     android:layout_below="@+id/editStRate1"
     android:layout_marginTop="14dp"
     android:ems="6"
     android:text="         Stone :"
     android:textColor="@color/background_material_dark"
     android:textSize="15sp" />


</RelativeLayout>

</ScrollView>

How to make <a href=""> link look like a button?

for those having problems after adding active and focus give a class or id name to your button and add this to css

for example

//html code

<button id="aboutus">ABOUT US</button>

//css code

#aboutus{background-color: white;border:none;outline-style: none;}

Javascript seconds to minutes and seconds

2020 UPDATE

Using basic math and simple javascript this can be done in just a few lines of code.

EXAMPLE - Convert 7735 seconds to HH:MM:SS.


MATH:

Calculations use:

  1. Math.floor() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

The Math.floor() function returns the largest integer less than or equal to a given number.

  1. % arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

Check out code below. Seconds are divided by 3600 to get number of hours and a remainder, which is used to calculate number of minutes and seconds.

HOURS => 7735 / 3600 = 2 remainder 535

MINUTES => 535 / 60 = 8 remainder 55

SECONDS => 55


LEADING ZEROS:

Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45, 04 etc. This can be done using padStart(). This works for strings so the number must be converted to string using toString().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.


CODE:

_x000D_
_x000D_
function secondsToTime(e){_x000D_
    var h = Math.floor(e / 3600).toString().padStart(2,'0'),_x000D_
        m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),_x000D_
        s = Math.floor(e % 60).toString().padStart(2,'0');_x000D_
    _x000D_
    return h + ':' + m + ':' + s;_x000D_
}_x000D_
_x000D_
console.log(secondsToTime(7735));  //02:08:55_x000D_
_x000D_
/*_x000D_
secondsToTime(SECONDS) => HH:MM:SS _x000D_
_x000D_
secondsToTime(8)       => 00:00:08 _x000D_
secondsToTime(68)      => 00:01:08_x000D_
secondsToTime(1768)    => 00:29:28_x000D_
secondsToTime(3600)    => 01:00:00_x000D_
secondsToTime(5296)    => 01:28:16_x000D_
secondsToTime(7735)    => 02:08:55_x000D_
secondsToTime(45296)   => 12:34:56_x000D_
secondsToTime(145296)  => 40:21:36_x000D_
secondsToTime(1145296) => 318:08:16_x000D_
*/
_x000D_
_x000D_
_x000D_

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

How do you convert WSDLs to Java classes using Eclipse?

You need to do next in command line:

wsimport -keep -s (name of folder where you want to store generated code) urlToWsdl

for example:

wsimport -keep -s C://NewFolder https://www.blablabla.com

Batch file: Find if substring is in string (not in a file)

If you are detecting for presence, here's the easiest solution:

SET STRING=F00BAH
SET SUBSTRING=F00
ECHO %STRING% | FINDSTR /C:"%SUBSTRING%" >nul & IF ERRORLEVEL 1 (ECHO CASE TRUE) else (ECHO CASE FALSE)

This works great for dropping the output of windows commands into a boolean variable. Just replace the echo with the command you want to run. You can also string Findstr's together to further qualify a statement using pipes. E.G. for Service Control (SC.exe)

SC QUERY WUAUSERV | findstr /C:"STATE" | FINDSTR /C:"RUNNING" & IF ERRORLEVEL 1 (ECHO case True) else (ECHO CASE FALSE)

That one evaluates the output of SC Query for windows update services which comes out as a multiline text, finds the line containing "state" then finds if the word "running" occurs on that line, and sets the errorlevel accordingly.

Powershell Log Off Remote Session

Here's a great scripted solution for logging people out remotely or locally. I'm using qwinsta to get session information and building an array out of the given output. This makes it really easy to iterate through each entry and log out only the actual users, and not the system or RDP listener itself which usually just throws an access denied error anyway.

$serverName = "Name of server here OR localhost"
$sessions = qwinsta /server $serverName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
$item.Active = $_.Substring(0,1) -match '>'
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item.Type = $_.Substring(56,12).Trim()
$item.Device = $_.Substring(68).Trim()
$item
} 

foreach ($session in $sessions){
    if ($session.Username -ne "" -or $session.Username.Length -gt 1){
        logoff /server $serverName $session.Id
    }
}

In the first line of this script give $serverName the appropriate value or localhost if running locally. I use this script to kick users before an automated process attempts to move some folders around. Prevents "file in use" errors for me. Another note, this script will have to be ran as an administrator user otherwise you can get accessed denied trying to log someone out. Hope this helps!

Installing SciPy with pip

In my case, it wasn't working until I also installed the following package : libatlas-base-dev, gfortran

 sudo apt-get install libatlas-base-dev gfortran

Then run pip install scipy

Android Studio Gradle Already disposed Module

In my case, same as in this question, it happened becayse I had my project in a symbolic link directory. After reopening the project in the real directory and reconfiguring gradle (File -> Sync with Gradle files) the problem went away. Shame on you, Android Studio!

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

How to convert a Java String to an ASCII byte array?

String s = "ASCII Text";
byte[] bytes = s.getBytes("US-ASCII");

How do I find the index of a character within a string in C?

Just subtract the string address from what strchr returns:

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

Note that the result is zero based, so in above example it will be 2.

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

Export to CSV using MVC, C# and jQuery

Simple excel file create in mvc 4

public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }

html5 audio player - jquery toggle click play/pause?

Here is my solution using jQuery

<script type="text/javascript">
    $('#mtoogle').toggle(
        function () {
            document.getElementById('playTune').pause();
        },
        function () {
            document.getElementById('playTune').play();
        }
    );
</script>

And the working demo

http://demo.ftutorials.com/html5-audio/

AngularJs: Reload page

Angular 2+

I found this while searching for Angular 2+, so here is the way:

$window.location.reload();

How to convert string to integer in PowerShell

Example:

2.032 MB (2,131,022 bytes)

$u=($mbox.TotalItemSize.value).tostring()

$u=$u.trimend(" bytes)") #yields 2.032 MB (2,131,022

$u=$u.Split("(") #yields `$u[1]` as 2,131,022

$uI=[int]$u[1]

The result is 2131022 in integer form.

How to insert data to MySQL having auto incremented primary key?

Set the auto increment field to NULL or 0 if you want it to be auto magically assigned...

How to view method information in Android Studio?

Yes, you can. Go to File -> Settings -> Editor -> Show quick documentation on mouse move

Or, in Mac OS X, go to Android Studio - > Preferences -> Editor - > General > Show quick documentation on mouse move.

CSS: auto height on containing div, 100% height on background div inside containing div

Try excluding height from the style element.

i.e. neither give height:100% nor to any other value.

How do I customize Facebook's sharer.php

It appears the following answer no longer works, and Facebook no longer accepts parameters on the Feed Dialog links

You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:

1) Create a link like:

   http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
        '&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
        '&picture=[LINK_TO_IMAGE]' +
        '&name=' + encodeURIComponent('[CONTENT_TITLE]') +
        '&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
        '&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
        '&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
        '&display=popup';

(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)

2) Open that link in a popup window with JavaScript on click of the share link

3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script> to close the popup window

The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.

ObjectiveC Parse Integer from String

Keep in mind that international users may be using a decimal separator other than . in which case values can get mixed up or just become nil when using intValue on a string.

For example, in the UK 1.23 is written 1,23, so the number 1.777 would be input by user as 1,777, which, as .intValue, will be 1777 not 1 (truncated).


I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).

#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)

iPhone system font

If you're doing programatic customisation, don't hard code the system font. Use UIFont systemFontOfSize:, UIFont boldSystemFontOfSize: and UIFont italicSystemFontOfSize (Apple documentation).

This has become especially relevant since iOS 7, which changed the system font to Helvetica Neue.

This has become super especially relevant since iOS 9, which changed the system font again to San Francisco.

Is there a function to round a float in C or do I need to write my own?

#include <math.h>

double round(double x);
float roundf(float x);

Don't forget to link with -lm. See also ceil(), floor() and trunc().

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

Set Background color programmatically

I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"

  yourView.setBackgroundColor(Color.parseColor("#ffffff"));

Why use 'git rm' to remove a file instead of 'rm'?

When using git rm, the removal will part of your next commit. So if you want to push the change you should use git rm

Padding between ActionBar's home icon and title

Im using a custom image instead of the default title text to the right of my apps logo. This is set up programatically like

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayUseLogoEnabled(true);
    actionBar.setCustomView(R.layout.include_ab_txt_logo);
    actionBar.setDisplayShowCustomEnabled(true);

The issues with the above answers for me are @Cliffus's suggestion does not work for me due to the issues others have outlined in the comments and while @dushyanth programatic padding setting may have worked in the past I would think that the fact that the spacing is now set using android:layout_marginEnd="8dip" since API 17 manually setting the padding should have no effect. See the link he posted to git to verify its current state.

A simple solution for me is to set a negative margin on my custom view in the actionBar, like so android:layout_marginLeft="-14dp". A quick test shows it works for me on 2.3.3 and 4.3 using ActionBarCompat

Hope this helps someone!

How to download file in swift?

Yes you can very easily downloads Files from the remote Url Using this code. This Code is working Fine for Me.

func DownlondFromUrl(){
   // Create destination URL 
let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")

//Create URL to the source file you want to download
let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG")

let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)

let request = URLRequest(url:fileURL!)

let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
    if let tempLocalUrl = tempLocalUrl, error == nil {
        // Success
        if let statusCode = (response as? HTTPURLResponse)?.statusCode {
            print("Successfully downloaded. Status code: \(statusCode)")
        }

        do {
            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
        } catch (let writeError) {
            print("Error creating a file \(destinationFileUrl) : \(writeError)")
        }

    } else {
        print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
    }
}
task.resume()
}

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient is deprecated in sdk 23.

You have to move on URLConnection or down sdk to 22

Still you need HttpClient with update gradle sdk 23

You have to add the dependencies of HttpClient in app/gradle as

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.0.1'

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    ...
}

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

Multiple simultaneous downloads using Wget?

Another program that can do this is axel.

axel -n <NUMBER_OF_CONNECTIONS> URL

For baisic HTTP Auth,

axel -n <NUMBER_OF_CONNECTIONS> "user:password@https://domain.tld/path/file.ext"

Ubuntu man page.

Decimal number regular expression, where digit after decimal is optional

/\d+\.?\d*/

One or more digits (\d+), optional period (\.?), zero or more digits (\d*).

Depending on your usage or regex engine you may need to add start/end line anchors:

/^\d+\.?\d*$/

Regular expression visualization

Debuggex Demo

Exercises to improve my Java programming skills

If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)

How to read a file in other directory in python

You can't "open" a directory using the open function. This function is meant to be used to open files.

Here, what you want to do is open the file that's in the directory. The first thing you must do is compute this file's path. The os.path.join function will let you do that by joining parts of the path (the directory and the file name):

fpath = os.path.join(direct, "5_1.txt")

You can then open the file:

f = open(fpath)

And read its content:

content = f.read()

Additionally, I believe that on Windows, using open on a directory does return a PermissionDenied exception, although that's not really the case.

What does `ValueError: cannot reindex from a duplicate axis` mean?

In my case, this error popped up not because of duplicate values, but because I attempted to join a shorter Series to a Dataframe: both had the same index, but the Series had fewer rows (missing the top few). The following worked for my purposes:

df.head()
                          SensA
date                           
2018-04-03 13:54:47.274   -0.45
2018-04-03 13:55:46.484   -0.42
2018-04-03 13:56:56.235   -0.37
2018-04-03 13:57:57.207   -0.34
2018-04-03 13:59:34.636   -0.33

series.head()
date
2018-04-03 14:09:36.577    62.2
2018-04-03 14:10:28.138    63.5
2018-04-03 14:11:27.400    63.1
2018-04-03 14:12:39.623    62.6
2018-04-03 14:13:27.310    62.5
Name: SensA_rrT, dtype: float64

df = series.to_frame().combine_first(df)

df.head(10)
                          SensA  SensA_rrT
date                           
2018-04-03 13:54:47.274   -0.45        NaN
2018-04-03 13:55:46.484   -0.42        NaN
2018-04-03 13:56:56.235   -0.37        NaN
2018-04-03 13:57:57.207   -0.34        NaN
2018-04-03 13:59:34.636   -0.33        NaN
2018-04-03 14:00:34.565   -0.33        NaN
2018-04-03 14:01:19.994   -0.37        NaN
2018-04-03 14:02:29.636   -0.34        NaN
2018-04-03 14:03:31.599   -0.32        NaN
2018-04-03 14:04:30.779   -0.33        NaN
2018-04-03 14:05:31.733   -0.35        NaN
2018-04-03 14:06:33.290   -0.38        NaN
2018-04-03 14:07:37.459   -0.39        NaN
2018-04-03 14:08:36.361   -0.36        NaN
2018-04-03 14:09:36.577   -0.37       62.2

Checking for an empty field with MySQL

You could use

IFNULL(email, '') > ''

$(window).width() not the same as media query

Javascript provides more than one method to check the viewport width. As you noticed, innerWidth doesn't include the toolbar width, and toolbar widths will differ across systems. There is also the outerWidth option, which will include the toolbar width. The Mozilla Javascript API states:

Window.outerWidth gets the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.

The state of javascript is such that one cannot rely on a specific meaning for outerWidth in every browser on every platform.

outerWidth is not well supported on older mobile browsers, though it enjoys support across major desktop browsers and most newer smart phone browsers.

As ausi pointed out, matchMedia would be a great choice as CSS is better standardised (matchMedia uses JS to read the viewport values detected by CSS). But even with accepted standards, retarded browsers still exist that ignore them (IE < 10 in this case, which makes matchMedia not very useful at least until XP dies).

In summary, if you are only developing for desktop browsers and newer mobile browsers, outerWidth should give you what you are looking for, with some caveats.

Oracle: SQL query that returns rows with only numeric values

What about 1.1E10, +1, -0, etc? Parsing all possible numbers is trickier than many people think. If you want to include as many numbers are possible you should use the to_number function in a PL/SQL function. From http://www.oracle-developer.net/content/utilities/is_number.sql:

CREATE OR REPLACE FUNCTION is_number (str_in IN VARCHAR2) RETURN NUMBER IS
   n NUMBER;
BEGIN
   n := TO_NUMBER(str_in);
   RETURN 1;
EXCEPTION
   WHEN VALUE_ERROR THEN
      RETURN 0;
END;
/

Return Boolean Value on SQL Select Statement

DECLARE @isAvailable      BIT = 0;

IF EXISTS(SELECT 1  FROM [User] WHERE (UserID = 20070022))
BEGIN
 SET @isAvailable = 1
END

initially isAvailable boolean value is set to 0

Angular bootstrap datepicker date format does not format ng-model value

Defining a new directive to work around a bug is not really ideal.

Because the datepicker displays later dates correctly, one simple workaround could be just setting the model variable to null first, and then to the current date after a while:

$scope.dt = null;
$timeout( function(){
    $scope.dt = new Date();
},100);

SQL update trigger only when column is modified

fyi The code I ended up with:

IF UPDATE (QtyToRepair)
    begin
        INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
        SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber 
        WHERE I.QtyToRepair <> D.QtyToRepair
end

How can I get a channel ID from YouTube?

You can get the channel ID with the username (in your case "klauskkpm") using the filter "forUsername", like this:

https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername=klauskkpm&part=id

More info here: https://developers.google.com/youtube/v3/docs/channels/list

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

How do I set log4j level on the command line?

As part of your jvm arguments you can set -Dlog4j.configuration=file:"<FILE_PATH>". Where FILE_PATH is the path of your log4j.properties file.

Please note that as of log4j2, the new system variable to use is log4j.configurationFile and you put in the actual path to the file (i.e. without the file: prefix) and it will automatically load the factory based on the extension of the configuration file:

-Dlog4j.configurationFile=/path/to/log4jconfig.{ext}

How to use Google App Engine with my own naked domain (not subdomain)?

You can redirect forward or mask your domain name in godaddy but I don't know about other hosting sites.Have a look on this link

How to use pagination on HTML tables?

There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:

HTML

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Gender</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people" b-paginate="5">
      <td>{{person.name}}</td>
      <td>{{person.gender}}</td>
      <td>{{person.age}}</td>
      <td>{{person.email}}</td>
    </tr>
  </tbody>
</table>
<ul></ul>

JS

var data={ people: [ {...}, {...}, ...] };

$(function() {
  breed.run({
    scope: 'people',
    input: data,
    runEnd: function(){ //This runEnd is just to mount the page buttons
        for(i=1 ; i<=breed.getPageCount('people') ; i++){
        $('ul').append(
            $('<li>',{
            html: i,
            onclick: "breed.paginate({scope: 'people', page: " + i + "});"
          })
        );
      }
    }
  });
});

Every time you want to change pages, just call:

breed.paginate({scope: 'people', page: pageNumber);

More info.

Working example.

How to run a single RSpec test?

For single example of spec file you need to add line number at the last , For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb:35

For single file you can specify your file path, For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb

For Whole Rspec Example in spec folder, you can try with this command

bundle exec rspec spec

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

The problem with editing JavaScript like you can CSS and HTML is that there is no clean way to propagate the changes. JavaScript can modify the DOM, send Ajax requests, and dynamically modify existing objects and functions at runtime. So, once you have loaded a page with JavaScript, it might be completely different after the JavaScript has run. The browser would have to keep track of every modification your JavaScript code performs so that when you edit the JS, it rolls back the changes to a clean page.

But, you can modify JavaScript dynamically a few other ways:

  • JavaScript injections in the URL bar: javascript: alert (1);
  • Via a JavaScript console (there's one built into Firefox, Chrome, and newer versions of IE
  • If you want to modify the JavaScript files as they are served to your browser (i.e. grabbing them in transit and modifying them), then I can't offer much help. I would suggest using a debugging proxy: http://www.fiddler2.com/fiddler2/

The first two options are great because you can modify any JavaScript variables and functions currently in scope. However, you won't be able to modify the code and run it with a "just-served" page like you can with the third option.

Other than that, as far as I know, there is no edit-and-run JavaScript editor in the browser. Hope this helps,

Finding partial text in range, return an index

I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B

I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.

what is the differences between sql server authentication and windows authentication..?

SQL Server Authentication Modes

SQL Server 2008 offers two authentication mode options:

Windows authentication mode requires users to provide a valid Windows username and password to access the database server. In enterprise environments, these credentials are normally Active Directory domain credentials.

Mixed authentication mode allows the use of Windows credentials but supplements them with local SQL Server user accounts that the administrator may create and maintain within SQL Server.

Illegal mix of collations error in MySql

I got this same error inside a stored procedure, in the where clause. i discovered that the problem ocurred with a local declared variable, previously loaded by the same table/column.

I resolved it casting the data to single char type.

What's the most concise way to read query parameters in AngularJS?

It's a bit late, but I think your problem was your URL. If instead of

http://127.0.0.1:8080/test.html?target=bob

you had

http://127.0.0.1:8080/test.html#/?target=bob

I'm pretty sure it would have worked. Angular is really picky about its #/

Concatenate a vector of strings/character

Try using an empty collapse argument within the paste function:

paste(sdata, collapse = '')

Thanks to http://twitter.com/onelinetips/status/7491806343

How to multiply duration by integer?

It's nice that Go has a Duration type -- having explicitly defined units can prevent real-world problems.

And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.

/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
    return time.Duration(factor) * d        // method 1 -- multiply in 'Duration'
 // return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}

The official documentation demonstrates using method #1:

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).

By the way, the int64 representation of Duration in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration, like int64, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292, and that's exactly how it is implemented:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

So, because we know that the underlying representation of Duration is an int64, performing the cast between int64 and Duration is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.

If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.

How to convert QString to int?

Don't forget to check if the conversion was successful!

bool ok;
auto str= tr("1337");
str.toDouble(&ok); // returns 1337.0, ok set to true
auto strr= tr("LEET");
strr.toDouble(&ok); // returns 0.0, ok set to false

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How to set the size of a column in a Bootstrap responsive table

You could use inline styles and define the width in the <th> tag. Make it so that the sum of the widths = 100%.

    <tr>
        <th style="width:10%">Size</th>
        <th style="width:30%">Bust</th>
        <th style="width:50%">Waist</th>
        <th style="width:10%">Hips</th>
    </tr>

Bootply demo

Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.

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

You can create a RegExp object to make it a bit more readable

str.replace(new RegExp('/'), 'foobar');

If you want to replace all of them add the "g" flag

str.replace(new RegExp('/', 'g'), 'foobar');

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

'too many values to unpack', iterating over a dict. key=>string, value=>list

For lists, use enumerate

for field, possible_values in enumerate(fields):
    print(field, possible_values)

iteritems will not work for list objects

What does 'public static void' mean in Java?

Public - means that the class (program) is available for use by any other class.

Static - creates a class. Can also be applied to variables and methods,making them class methods/variables instead of just local to a particular instance of the class.

Void - this means that no product is returned when the class completes processing. Compare this with helper classes that provide a return value to the main class,these operate like functions; these do not have void in the declaration.

How to search for a string inside an array of strings

It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:

Code:

Array.prototype.findFirstSubstring = function(s) {
            for(var i = 0; i < this.length;i++)
            {
                if(this[i].indexOf(s) !== -1)
                    return i;
            }
            return -1;
        };

Usage:

i.findFirstSubstring('height');

Returns:

-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2)

How to retrieve data from sqlite database in android and display it in TextView

TextView tekst = (TextView) findViewById(R.id.editText1); 

You cannot cast EditText to TextView.

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

I was facing the same problem when import projects into IntelliJ.

for in my case first, check SDK details and check you have configured JDK correctly or not.

Go to File-> Project Structure-> platform Settings-> SDKs

Check your JDK is correct or not.

enter image description here

Next, I Removed project from IntelliJ and delete all IntelliJ and IDE related files and folder from the project folder (.idea, .settings, .classpath, dependency-reduced-pom). Also, delete the target folder and re-import the project.

The above solution worked in my case.

Javascript checkbox onChange

function calc()
{
  if (document.getElementById('xxx').checked) 
  {
      document.getElementById('totalCost').value = 10;
  } else {
      calculate();
  }
}

HTML

<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Resource files not found from JUnit test cases

My mistake, the resource files WERE actually copied to target/test-classes. The problem seemed to be due to spaces in my project name, e.g. Project%20Name.

I'm now loading the file as follows and it works:

org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);

Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):

myClass().getResource("resourceFile.txt")??.toURI();

Set Radiobuttonlist Selected from Codebehind

var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;

//this for javascript in asp.net try this in .aspx page

// if you select other radiobutton increase [0] to [1] or [2] like this

jQuery callback for multiple ajax calls

I got some good hints from the answers on this page. I adapted it a bit for my use and thought I could share.

// lets say we have 2 ajax functions that needs to be "synchronized". 
// In other words, we want to know when both are completed.
function foo1(callback) {
    $.ajax({
        url: '/echo/html/',
        success: function(data) {
            alert('foo1');
            callback();               
        }
    });
}

function foo2(callback) {
    $.ajax({
        url: '/echo/html/',
        success: function(data) {
            alert('foo2');
            callback();
        }
    });
}

// here is my simplified solution
ajaxSynchronizer = function() {
    var funcs = [];
    var funcsCompleted = 0;
    var callback;

    this.add = function(f) {
        funcs.push(f);
    }

    this.synchronizer = function() {
        funcsCompleted++;
        if (funcsCompleted == funcs.length) {
            callback.call(this);
        }
    }

    this.callWhenFinished = function(cb) {
        callback = cb;
        for (var i = 0; i < funcs.length; i++) {
            funcs[i].call(this, this.synchronizer);
        }
    }
}

// this is the function that is called when both ajax calls are completed.
afterFunction = function() {
    alert('All done!');
}

// this is how you set it up
var synchronizer = new ajaxSynchronizer();
synchronizer.add(foo1);
synchronizer.add(foo2);
synchronizer.callWhenFinished(afterFunction);

There are some limitations here, but for my case it was ok. I also found that for more advanced stuff it there is also a AOP plugin (for jQuery) that might be useful: http://code.google.com/p/jquery-aop/

jQuery - How to dynamically add a validation rule

In case you want jquery validate to auto pick validations on dynamically added items, you can simply remove and add validation on the whole form like below

//remove validations on entire form
$("#yourFormId")
    .removeData("validator")
    .removeData("unobtrusiveValidation");

//Simply add it again
$.validator
    .unobtrusive
    .parse("#yourFormId");

Enter key in textarea

You could do something like this:

_x000D_
_x000D_
$("#txtArea").on("keypress",function(e) {_x000D_
    var key = e.keyCode;_x000D_
_x000D_
    // If the user has pressed enter_x000D_
    if (key == 13) {_x000D_
        document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
        return false;_x000D_
    }_x000D_
    else {_x000D_
        return true;_x000D_
    }_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
_x000D_
_x000D_

Load jQuery with Javascript and use jQuery

There is an other way to load jQuery dynamically (source). You could also use

document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');

It's considered bad practice to use document.write, but for sake of completion it's good to mention it.

See Why is document.write considered a "bad practice"? for the reasons. The pro is that document.write does block your page from loading other assests, so there is no need to create a callback function.

How to find duplicate records in PostgreSQL

In your case, because of the constraint you need to delete the duplicated records.

  1. Find the duplicated rows
  2. Organize them by created_at date - in this case I'm keeping the oldest
  3. Delete the records with USING to filter the right rows
WITH duplicated AS ( 
    SELECT id,
        count(*) 
    FROM products 
    GROUP BY id 
    HAVING count(*) > 1), 
ordered AS ( 
    SELECT p.id, 
        created_at, 
        rank() OVER (partition BY p.id ORDER BY p.created_at) AS rnk 
    FROM products o 
    JOIN     duplicated d ON d.id = p.id ), 
products_to_delete AS ( 
    SELECT id, 
        created_at 
    FROM   ordered 
    WHERE  rnk = 2
) 
DELETE 
FROM products 
USING products_to_delete 
WHERE products.id = products_to_delete.id 
    AND products.created_at = products_to_delete.created_at;

Change image onmouseover

<a href="" onMouseOver="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/ask-icon.png';" onMouseOut="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png';">
<img src="http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png" name="MyImage">

Demo http://jsfiddle.net/W6zs5/

LaTeX Optional Arguments

The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar is quite useful for such things.

The best answer for your question is to use the new xparse package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.

In your example you have a \sec macro that either takes one or two braced arguments. This would be implemented using xparse with the following:

\documentclass{article}
\usepackage{xparse}
\begin{document}
\DeclareDocumentCommand\sec{ m g }{%
    {#1%
        \IfNoValueF {#2} { and #2}%
    }%
}
(\sec{Hello})
(\sec{Hello}{Hi})
\end{document}

The argument { m g } defines the arguments of \sec; m means "mandatory argument" and g is "optional braced argument". \IfNoValue(T)(F) can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.

How to fix a Div to top of page with CSS only

Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following

#term-defs {
height: 300px;
overflow: scroll; }

This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.

#top {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 23px;
}

This will fix it to the top, on top of other content with a height of 23px.

The final implementation will depend on what effect you really want.

Can't use SURF, SIFT in OpenCV

You can proceed in this way. It must work for you as well!

Step 1:

virtualenv venv 
source venv/bin/activate

Step 2:

sudo python3 -m pip install opencv-python==3.4.2.16 
sudo python3 -m pip install opencv-contrib-python==3.4.2.16

Step 3:

import cv2
sift = cv2.xfeatures2d.SIFT_create()

Don't use cv2.SIFT() . It will raise an exception.

how to create inline style with :before and :after

You can, using CSS variables (more precisely called CSS custom properties).

  • Set your variable in your style attribute:
    style="--my-color-var: orange;"
  • Use the variable in your stylesheet:
    background-color: var(--my-color-var);

Browser compatibility

Minimal example:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  position: relative;
  border: 1px solid black;
}

div:after {
  background-color: var(--my-color-var);
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
_x000D_
_x000D_

Your example:

_x000D_
_x000D_
.bubble {
  position: relative;
  width: 30px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
  text-align: center;
  background-color: var(--bubble-color);
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent var(--bubble-color);
   display: block;
  width: 0;
  z-index: 1;
  
}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
_x000D_
_x000D_

Regular expression to remove HTML tags from a string

You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.


The following examples are Java, but the regex will be similar -- if not identical -- for other languages.


String target = someString.replaceAll("<[^>]*>", "");

Assuming your non-html does not contain any < or > and that your input string is correctly structured.

If you know they're a specific tag -- for example you know the text contains only <td> tags, you could do something like this:

String target = someString.replaceAll("(?i)<td[^>]*>", "");

Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.

For example, if the input string were <td>Something</td><td>Another Thing</td>, then the above would result in SomethingAnother Thing.

In a situation where multiple tags are expected, we could do something like:

String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();

This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.

How do I get the key at a specific index from a Dictionary in Swift?

SWIFT 3. Example for the first element

let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]

if let firstLang = wordByLanguage.first?.key {
    print(firstLang)  // English
}

In git, what is the difference between merge --squash and rebase?

Let's start by the following example:

enter image description here

Now we have 3 options to merge changes of feature branch into master branch:

  1. Merge commits
    Will keep all commits history of the feature branch and move them into the master branch
    Will add extra dummy commit.

  2. Rebase and merge
    Will append all commits history of the feature branch in the front of the master branch
    Will NOT add extra dummy commit.

  3. Squash and merge
    Will group all feature branch commits into one commit then append it in the front of the master branch
    Will add extra dummy commit.

You can find below how the master branch will look after each one of them.

enter image description here

In all cases:
We can safely DELETE the feature branch.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

After Xcode 6.1 Beta the code below works, slight edit on Tom S code that stopped working with the 6.1 beta (worked with previous beta):

   if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:") {
        // It's iOS 8
        var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
       var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
       UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    } else {
        // It's older
        var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
        UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
    }

Matching a Forward Slash with a regex

You can escape it by preceding it with a \ (making it \/), or you could use new RegExp('/') to avoid escaping the regex.

See example in JSFiddle.

'/'.match(/\//)            // matches /
'/'.match(new RegExp('/')  // matches /

Detect if the app was launched/opened from a push notification

When app is in background as shanegao you can use

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //opened from a push notification when the app was on background
    }
}

But if you want to launch the application and when app is closed and you want to debug your application you can go to Edit Scheme and in left menu select Run and then in launch select Wait for executable to be launched and then you application launch when you click on push notification

Edit Scheme > Run > Wait for executable to be launched

What is the difference between JavaScript and jQuery?

Javascript is base of jQuery.

jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing.

Search and replace part of string in database

I think 2 update calls should do

update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')

update VersionedFields
set Value = replace(value,'> </iframe>','</a>')

Understanding timedelta

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python.org/library/datetime.html#timedelta-objects

Change/Get check state of CheckBox

Needs to be:

if (document.forms[0].elements["checkAddress"].checked == true)

Assuming you have one form, otherwise use the form name.

As a side note, don't call the element and the function in the same name it can cause weird conflicts.

export html table to csv

(1)This is the native javascript solution for this issue. It works on most of modern browsers.

_x000D_
_x000D_
function export2csv() {_x000D_
  let data = "";_x000D_
  const tableData = [];_x000D_
  const rows = document.querySelectorAll("table tr");_x000D_
  for (const row of rows) {_x000D_
    const rowData = [];_x000D_
    for (const [index, column] of row.querySelectorAll("th, td").entries()) {_x000D_
      // To retain the commas in the "Description" column, we can enclose those fields in quotation marks._x000D_
      if ((index + 1) % 3 === 0) {_x000D_
        rowData.push('"' + column.innerText + '"');_x000D_
      } else {_x000D_
        rowData.push(column.innerText);_x000D_
      }_x000D_
    }_x000D_
    tableData.push(rowData.join(","));_x000D_
  }_x000D_
  data += tableData.join("\n");_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));_x000D_
  a.setAttribute("download", "data.csv");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Name</th>_x000D_
      <th>Author</th>_x000D_
      <th>Description</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>jQuery</td>_x000D_
      <td>John Resig</td>_x000D_
      <td>The Write Less, Do More, JavaScript Library.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>React</td>_x000D_
      <td>Jordan Walke</td>_x000D_
      <td>React makes it painless to create interactive UIs.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Vue.js</td>_x000D_
      <td>Yuxi You</td>_x000D_
      <td>The Progressive JavaScript Framework.</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button onclick="export2csv()">csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(2) If you want a pure javascript library, FileSaver.js could help you save the code snippets for triggering file download. Besides, FileSaver.js will not be responsible for constructing content for exporting. You have to construct the content by yourself in the format you want.

How to color System.out.println output?

Escape sequences must be interpreted by SOMETHING to be converted to color. The standard CMD.EXE used by java when started from the command line, doesn't support this so therefore Java does not.

Single Form Hide on Startup

I use this:

private void MainForm_Load(object sender, EventArgs e)
{
    if (Settings.Instance.HideAtStartup)
    {
        BeginInvoke(new MethodInvoker(delegate
        {
            Hide();
        }));
    }
}

Obviously you have to change the if condition with yours.

How can a file be copied?

For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file.

for line in open("file.txt", "r"):
    list.append(line)
    if len(list) == 1000000: 
        output.writelines(list)
        del list[:]

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Multiple aggregate functions in HAVING clause

GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

FormsAuthentication.SignOut() does not log the user out

Just try to send a session variable when you press log in. And on the welcome page, first check whether that session is empty like this in the page load or in the Init Event:

if(Session["UserID"] == null || Session["UserID"] == "")
{
    Response.Redirect("Login.aspx");
}

How to use css style in php

css :hover kinda is like js onmouseover

row1 {
    // your css
}
row1:hover {
    color: red;
}
row1:hover #a, .b, .c:nth-child[3] {
    border: 1px solid red;
}

not too sure how it works but css applies styles to echo'ed ids

TimePicker Dialog from clicking EditText

In all of the above, the EditText still needs the focusable="false" attribute in the xml in order to prevent the keyboard from popping up.

Compiled vs. Interpreted Languages

The Python Book © 2015 Imagine Publishing Ltd, simply distunguishes the difference by the following hint mentioned in page 10 as:

An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled language such as C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.

How can I make the browser wait to display the page until it's fully loaded?

Here's a solution using jQuery:

<script type="text/javascript">
$('#container').css('opacity', 0);
$(window).load(function() {
  $('#container').css('opacity', 1);
});
</script>

I put this script just after my </body> tag. Just replace "#container" with a selector for the DOM element(s) you want to hide. I tried several variations of this (including .hide()/.show(), and .fadeOut()/.fadeIn()), and just setting the opacity seems to have the fewest ill effects (flicker, changing page height, etc.). You can also replace css('opacity', 0) with fadeTo(100, 1) for a smoother transition. (No, fadeIn() won't work, at least not under jQuery 1.3.2.)

Now the caveats: I implemented the above because I'm using TypeKit and there's an annoying flicker when you refresh the page and the fonts take a few hundred milliseconds to load. So I don't want any text to appear on the screen until TypeKit has loaded. But obviously you're in big trouble if you use the code above and something on your page fails to load. There are two obvious ways that it could be improved:

  1. A maximum time limit (say, 1 second) after which everything appears whether the page is loaded or not
  2. Some kind of loading indicator (say, something from http://www.ajaxload.info/)

I won't bother implementing the loading indicator here, but the time limit is easy. Just add this to the script above:

$(document).ready(function() {
  setTimeout('$("#container").css("opacity", 1)', 1000);
});

So now, worst-case scenario, your page will take an extra second to appear.

How can I convert a DateTime to an int?

long n = long.Parse(date.ToString("yyyyMMddHHmmss"));

see Custom Date and Time Format Strings

How to set timeout in Retrofit library?

For Retrofit1.9 with OkHttp3 users, here is the solution,

.setClient(new Ok3Client(new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build()))

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

I've created config/initializers/secret_key.rb file and I wrote only following line of code:

Rails.application.config.secret_key_base = ENV["SECRET_KEY_BASE"]

But I think that solution posted by @Erik Trautman is more elegant ;)

Edit: Oh, and finally I found this advice on Heroku: https://devcenter.heroku.com/changelog-items/426 :)

Enjoy!

How to get second-highest salary employees in a table

 - Method 1

    select max(salary) from Employees
        where salary< (select max(salary) from Employees)



 - Method 2

 select MAX(salary) from Employees 
    where salary not in(select MAX(salary) from Employees)



 - Method 3

select MAX(salary) from Employees 
    where salary!= (select MAX(salary) from Employees )

Replacing from match to end-of-line

Use this, two<anything any number of times><end of line>

's/two.*$/BLAH/g'

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

MySQL date format DD/MM/YYYY select query?

Guessing you probably just want to format the output date? then this is what you are after

SELECT *, DATE_FORMAT(date,'%d/%m/%Y') AS niceDate 
FROM table 
ORDER BY date DESC 
LIMIT 0,14

Or do you actually want to sort by Day before Month before Year?

How do I request a file but not save it with Wget?

Curl does that by default without any parameters or flags, I would use it for your purposes:

curl $url > /dev/null 2>&1

Curl is more about streams and wget is more about copying sites based on this comparison.

Shell script to send email

mail -s "Your Subject" [email protected] < /file/with/mail/content

(/file/with/mail/content should be a plaintext file, not a file attachment or an image, etc)

$(document).ready equivalent without jQuery

The setTimeout/setInterval solutions presented here will only work in specific circumstances.

The problem shows up especially in older Internet Explorer versions up to 8.

The variables affecting the success of these setTimeout/setInterval solutions are:

1) dynamic or static HTML
2) cached or non cached requests
3) size of the complete HTML document
4) chunked or non chunked transfer encoding

the original (native Javascript) code solving this specific issue is here:

https://github.com/dperini/ContentLoaded
http://javascript.nwbox.com/ContentLoaded (test)

this is the code from which the jQuery team have built their implementation.

Python 3: EOF when reading a line (Sublime Text 2 is angry)

try:
    value = raw_input()
    do_stuff(value) # next line was found 
except (EOFError):
   break #end of file reached

This seems to be proper usage of raw_input when dealing with the end of the stream of input from piped input. [Refer this post][1]

How to extract this specific substring in SQL Server?

select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table

Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!

How do I find the width & height of a terminal window?

On POSIX, ultimately you want to be invoking the TIOCGWINSZ (Get WINdow SiZe) ioctl() call. Most languages ought to have some sort of wrapper for that. E.g in Perl you can use Term::Size:

use Term::Size qw( chars );

my ( $columns, $rows ) = chars \*STDOUT;

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Failed to open/create the internal network Vagrant on Windows10

  • Open Network and Sharing Center and go to the Change adapter settings in the sidebar.

  • Right-click on the host-only adapter in the list of adapters and then Configure button -> Driver tab -> Update driver button.

  • Select Browse my computer ... and in the next dialog select Let me pick .... You should see the list with just host-only driver in it.

  • Select it and click next. After the driver is updated, please try using host-only network in a VM again.

How to secure phpMyAdmin

The best way to secure phpMyAdmin is the combination of all these 4:

1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)

Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:

# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):

    sudo nano /etc/apache2/conf-available/phpmyadmin.conf
            /etc/phpmyadmin/apache.conf
        Change: phpmyadmin URL by this line:
            Alias /newphpmyadminname /usr/share/phpmyadmin
        Add: AllowOverride All
            <Directory /usr/share/phpmyadmin>
                Options FollowSymLinks
                DirectoryIndex index.php
                AllowOverride Limit
                ...
        sudo systemctl restart apache2
        sudo nano /usr/share/phpmyadmin/.htaccess
            deny from all
            allow from 127.0.0.1

        alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
        alias myip="echo ${SSH_CONNECTION%% *}"

# Secure Web Access to phpMyAdmin:

        Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
            https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04

        PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add

        C:\Windows\System32\drivers\etc
            Notepad - Run As Administrator - open: hosts
                127.0.0.1 pma.yourdomain.com

        https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
        https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)

        # Check to make sure you are on SSH Tunnel
            1. Windows - CMD:
                ping pma.yourdomain.com
                ping www.yourdomain.com

                # See PuTTY ports:
                netstat -ano |find /i "listening"

            2. Test live:
                https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/

If you are able to do these all successfully,

you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.

How to resize an image to fit in the browser window?

CSS3 introduces new units that are measured relative to the viewport, which is the window in this case. These are vh and vw, which measure viewport height and width, respectively. Here is a simple CSS only solution:

img {
    max-width: 100%;
    max-height: 100vh;
    height: auto;
}

The one caveat to this is that it only works if there are no other elements contributing height on the page.

How to force HTTPS using a web.config file

A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.

</configuration>
</system.webServer>
    <httpErrors>
        <clear/>
        <!--redirect if connected without SSL-->
        <error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
    </httpErrors>
</system.webServer>
</configuration>

How do I update Anaconda?

Here's the best practice (in my humble experience). Selecting these four packages will also update all other dependencies to the appropriate versions that will help you keep your environment consistent. The latter is a common problem others have expressed in earlier responses. This solution doesn't need the terminal.

Updating and upgrading Anaconda 3 or Anaconda 2 best practice

Datatable to html Table

Just in case anyone arrives here and was hoping for VB (I did, and I didn't enter c# as a search term), here's the basics of the first response..

Public Shared Function ConvertDataTableToHTML(dt As DataTable) As String
    Dim html As String = "<table>"
    html += "<tr>"
    For i As Integer = 0 To dt.Columns.Count - 1
        html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Columns(i).ColumnName) + "</td>"
    Next
    html += "</tr>"
    For i As Integer = 0 To dt.Rows.Count - 1
        html += "<tr>"
        For j As Integer = 0 To dt.Columns.Count - 1
            html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Rows(i)(j).ToString()) + "</td>"
        Next
        html += "</tr>"
    Next
    html += "</table>"
    Return html
End Function

FileNotFoundException..Classpath resource not found in spring?

Looking at your classpath you exclude src/main/resources and src/test/resources:

    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
    <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>

Is there a reason for it? Try not to exclude a classpath to spring-config.xml :)

Android, How can I Convert String to Date?

String source = "24/10/17";

String[] sourceSplit= source.split("/");

int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);

    GregorianCalendar calendar = new GregorianCalendar();
  calendar.set(anno,mese-1,giorno);
  Date   data1= calendar.getTime();
  SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");

    String   dayFormatted= myFormat.format(data1);

    System.out.println("data formattata,-->"+dayFormatted);

How to save an HTML5 Canvas as an image on a server?

Send canvas image to PHP:

var photo = canvas.toDataURL('image/jpeg');                
$.ajax({
  method: 'POST',
  url: 'photo_upload.php',
  data: {
    photo: photo
  }
});

Here's PHP script:
photo_upload.php

<?php

    $data = $_POST['photo'];
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);

    mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");

    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
    die;
?>

How to get user agent in PHP

You could also use the php native funcion get_browser()

IMPORTANT NOTE: You should have a browscap.ini file.

How do I launch a program from command line without opening a new cmd window?

You can use the call command...

Type: call /?

Usage: call [drive:][path]filename [batch-parameters]

For example call "Example File/Input File/My Program.bat" [This is also capable with calling files that have a .exe, .cmd, .txt, etc.

NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!

Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...

jQuery find parent form

I would suggest using closest, which selects the closest matching parent element:

$('input[name="submitButton"]').closest("form");

Instead of filtering by the name, I would do this:

$('input[type=submit]').closest("form");

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

Go to C:\app\insolution\product\11.2.0\client_1\BIN and find oci.dll. Right click on it -->Properties -->Under Security tab, click on Edit -->Then Click on Add Button --> Here add two new users with names IUSR and IIS_IUSRS and give them full controls. That's it.

How to embed a video into GitHub README.md?

just to extend @GabLeRoux's answer:

[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)

this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.

How can I add new dimensions to a Numpy array?

Pythonic

X = X[:, :, None]

which is equivalent to

X = X[:, :, numpy.newaxis] and X = numpy.expand_dims(X, axis=-1)

But as you are explicitly asking about stacking images, I would recommend going for stacking the list of images np.stack([X1, X2, X3]) that you may have collected in a loop.

If you do not like the order of the dimensions you can rearrange with np.transpose()

Shell script to delete directories older than n days

If you want to delete all subdirectories under /path/to/base, for example

/path/to/base/dir1
/path/to/base/dir2
/path/to/base/dir3

but you don't want to delete the root /path/to/base, you have to add -mindepth 1 and -maxdepth 1 options, which will access only the subdirectories under /path/to/base

-mindepth 1 excludes the root /path/to/base from the matches.

-maxdepth 1 will ONLY match subdirectories immediately under /path/to/base such as /path/to/base/dir1, /path/to/base/dir2 and /path/to/base/dir3 but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:

/path/to/base/dir1/dir1
/path/to/base/dir2/dir1
/path/to/base/dir3/dir1

and so forth.

So , to delete all the sub-directories under /path/to/base which are older than 10 days;

find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf

Two divs side by side - Fluid display

You can also use the Grid View its also Responsive its something like this:

#wrapper {
   width: auto;
    height: auto;
    box-sizing: border-box;
    display: grid;
    grid-auto-flow: row;
    grid-template-columns: repeat(6, 1fr);
}

#left{
    text-align: left;
    grid-column: 1/4;
}

#right {
    text-align: right;
    grid-column: 4/6;
}

and the HTML should look like this :

<div id="wrapper">
<div id="left" > ...some awesome stuff </div>
<div id="right" > ...some awesome stuff </div>
</div>

here is a link for more information:

https://www.w3schools.com/css/css_rwd_grid.asp

im quite new but i thougt i could share my little experience

How to remove a TFS Workspace Mapping?

I ran into the same problem, and was able to fix it by manually deleting all the files in the TFS cache, located here:

%LocalAppData%\Microsoft\Team Foundation\3.0\Cache

or 4.0, 5.0, etc.

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.