Programs & Examples On #Cck

The Content Construction Kit is a Drupal module that allows users to add custom fields to content types.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

Auto height div with overflow and scroll when needed

I'm surprised no one's mentioned calc() yet.

I wasn't able to make-out your specific case from your fiddles, but I understand your problem: you want a height: 100% container that can still use overflow-y: auto.

This doesn't work out of the box because overflow requires some hard-coded size constraint to know when it ought to start handling overflow. So, if you went with height: 100px, it'd work as expected.

The good news is that calc() can help, but it's not as simple as height: 100%.

calc() lets you combine arbitrary units of measure.

So, for the situation you describe in the picture you include: picture of desired state

Since all the elements above and below the pink div are of a known height (let's say, 200px in total height), you can use calc to determine the height of ole pinky:

height: calc(100vh - 200px);

or, 'height is 100% of the view height minus 200px.'

Then, overflow-y: auto should work like a charm.

Global variables in header file

@glglgl already explained why what you were trying to do was not working. Actually, if you are really aiming at defining a variable in a header, you can trick using some preprocessor directives:

file1.c:

#include <stdio.h>

#define DEFINE_I
#include "global.h"

int main()
{
    printf("%d\n",i);
    foo();
    return 0;
}

file2.c:

#include <stdio.h>
#include "global.h"

void foo()
{
    i = 54;
    printf("%d\n",i);
}

global.h:

#ifdef DEFINE_I
int i = 42;
#else
extern int i;
#endif

void foo();

In this situation, i is only defined in the compilation unit where you defined DEFINE_I and is declared everywhere else. The linker does not complain.

I have seen this a couple of times before where an enum was declared in a header, and just below was a definition of a char** containing the corresponding labels. I do understand why the author preferred to have that definition in the header instead of putting it into a specific source file, but I am not sure whether the implementation is so elegant.

one line if statement in php

Something like this?

($var > 2 ? echo "greater" : echo "smaller")

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

I finally found a solution. I wasted hours just trying to figure what this issue was. I tried deleting all those files suggested above and it didn't work for me, I tried adding new inbound rules to firewall for myslqd.exe and it didn't work. The thing that is causing this error is MySQL port is misconfigured and the fix was really simple. if you are using Wamp or Xampp go to Main Folder/Bin/mysql/mysql/ and find a file named my.ini

Open my.ini file press CTRL + F and inside it search for PORT and change whatever value of port to - 3306 and save file;

After that go to Wamp icon at the bottom of the taskbar (system tray) and left click choose mysql option and click "test port 3306 used" and see if it gives you any error. you can also click use other port other than whatever is shown there and port 3306.

Goodluck. if it works comment.

enter image description here

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

What character represents a new line in a text area

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

If you use anything else you will cause issues with cut and paste on Windows platforms.

The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.

Interestingly, in spite of the Unix line end convention being \n, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n. Yes, it may not make a lot of sense, but that's history and evolving standards for you!

ValueError: not enough values to unpack (expected 11, got 1)

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

Dynamically create Bootstrap alerts box through JavaScript

Try this (see a working example of this code in jsfiddle: http://jsfiddle.net/periklis/7ATLS/1/)

<input type = "button" id = "clickme" value="Click me!"/>
<div id = "alert_placeholder"></div>
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
            $('#alert_placeholder').html('<div class="alert"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
        }

$('#clickme').on('click', function() {
            bootstrap_alert.warning('Your text goes here');
});
</script>?

EDIT: There are now libraries that simplify and streamline this process, such as bootbox.js

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String
     }]

or

trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

Laravel Redirect Back with() Message

Just set the flash message and redirect to back from your controller functiion.

    session()->flash('msg', 'Successfully done the operation.');
    return redirect()->back();

And then you can get the message in the view blade file.

   {!! Session::has('msg') ? Session::get("msg") : '' !!}

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

Zach is correct about the direct answer to the question.

An interesting side note is that the following two loops do not execute the same:

for i=1:10000
  % do something
end
for i=[1:10000]
  % do something
end

The first loop creates a variable i that is a scalar and it iterates it like a C for loop. Note that if you modify i in the loop body, the modified value will be ignored, as Zach says. In the second case, Matlab creates a 10k-element array, then it walks all elements of the array.

What this means is that

for i=1:inf
  % do something
end

works, but

for i=[1:inf]
  % do something
end

does not (because this one would require allocating infinite memory). See Loren's blog for details.

Also note that you can iterate over cell arrays.

write a shell script to ssh to a remote machine and execute commands

There are a number of ways to handle this.

My favorite way is to install http://pamsshagentauth.sourceforge.net/ on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what's a couple more files?)

With your ssh agent forwarded, you can now log in to every system without a password.

And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user's) rights as needed.

You don't need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.

You should also look into packages like Capistrano. Definitely look around that site; it has an introduction to remote scripting.

Individual script lines might look something like this:

ssh remote-system-name command arguments ... # so, for exmaple,
ssh target.mycorp.net sudo puppet apply

How to append to New Line in Node.js

use \r\n combination to append a new line in node js

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

How to Use slideDown (or show) function on a table row?

I liked the plugin that Vinny's written and have been using. But in case of tables inside sliding row (tr/td), the rows of nested table are always hidden even after slid up. So I did a quick and simple hack in the plugin not to hide the rows of nested table. Just change the following line

var $cells = $(this).find('td');

to

var $cells = $(this).find('> td');

which finds only immediate tds not nested ones. Hope this helps someone using the plugin and have nested tables.

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

With Java 8 there is this API method to accomplish your requirement.

map.putIfAbsent(key, value)

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

'heroku' does not appear to be a git repository

My problem was that I used git (instead of heroku git) to clone the app. Then I had to:

git remote add heroku [email protected]:MyApp.git

Remember to change MyApp to your app name.

Then I could proceed:

git push heroku master

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I am having the same issue here is my scenario

i put empty('') where value is NULL now this '' value does not match with the parent table's id

here is things need to check , all value with presented in parent table otherwise remove data from parent table then try enter image description here

enter image description here enter image description here

How can I get the current stack trace in Java?

I suggest that

  Thread.dumpStack()

is an easier way and has the advantage of not actually constructing an exception or throwable when there may not be a problem at all, and is considerably more to the point.

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Create boolean column in MySQL with false as default value?

You can set a default value at creation time like:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
Married boolean DEFAULT false);

Matching strings with wildcard

Just FYI, you could use the VB.NET Like-Operator:

string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);  

Use CompareMethod.Text if you want to ignore the case.

You need to add using Microsoft.VisualBasic.CompilerServices;.

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.

DispatchQueue.global(qos: .background).async {
    
    // Background Thread
    
    DispatchQueue.main.async {
        // Run UI Updates
    }
}

Should I use Java's String.format() if performance is important?

To expand/correct on the first answer above, it's not translation that String.format would help with, actually.
What String.format will help with is when you're printing a date/time (or a numeric format, etc), where there are localization(l10n) differences (ie, some countries will print 04Feb2009 and others will print Feb042009).
With translation, you're just talking about moving any externalizable strings (like error messages and what-not) into a property bundle so that you can use the right bundle for the right language, using ResourceBundle and MessageFormat.

Looking at all the above, I'd say that performance-wise, String.format vs. plain concatenation comes down to what you prefer. If you prefer looking at calls to .format over concatenation, then by all means, go with that.
After all, code is read a lot more than it's written.

How to order a data frame by one descending and one ascending column?

In @dudusan's example, you could also reverse the order of I1, and then sort ascending:

> rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
+   2   3   5   52  43  61  6   b
+   6   4   3   72  NA  59  1   a
+   1   5   6   55  48  60  6   f
+   2   4   4   65  64  58  2   b
+   1   5   6   55  48  60  6   c"), header = TRUE)
> f=factor(rum$I1)   
> levels(f) <- sort(levels(f), decreasing = TRUE)
> rum[order(as.character(f), rum$I2), ]
  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a
> 

This seems a bit shorter, you don't reverse the order of I2 twice.

Cannot get a text value from a numeric cell “Poi”

    Cell cell = sheet.getRow(i).getCell(0);
    cell.setCellType ( Cell.CELL_TYPE_STRING );
    String j_username = cell.getStringCellValue();

UPDATE

Ok, as have been said in comments, despite this works it isn't correct method of retrieving data from an Excel's cell.

According to the manual here:

If what you want to do is get a String value for your numeric cell, stop!. This is not the way to do it. Instead, for fetching the string value of a numeric or boolean or date cell, use DataFormatter instead.

And according to the DataFormatter API

DataFormatter contains methods for formatting the value stored in an Cell. This can be useful for reports and GUI presentations when you need to display data exactly as it appears in Excel. Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.

So, right way to show numeric cell's value is as following:

 DataFormatter formatter = new DataFormatter(); //creating formatter using the default locale
 Cell cell = sheet.getRow(i).getCell(0);
 String j_username = formatter.formatCellValue(cell); //Returns the formatted value of a cell as a String regardless of the cell type.

Css height in percent not working

the root parent have to be in pixels if you want to work freely with percents,

<body style="margin: 0px; width: 1886px; height: 939px;">
<div id="containerA" class="containerA" style="height:65%;width:100%;">
    <div id="containerAinnerDiv" style="position: relative; background-color: aqua;width:70%;height: 80%;left:15%;top:10%;">
       <div style="height: 100%;width: 50%;float: left;"></div>
       <div style="height: 100%;width: 28%;float:left">
            <img src="img/justimage.png" style="max-width:100%;max-height:100%;">
       </div>
       <div style="height: 100%;width: 22%;float: left;"></div>
    </div>
</div>
</body>

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

Yeah, there appears to be a bug in Chrome when it comes to modifying the body, trying to make it into an offsetParent. As a work-around, I suggest you simply add another div to wrap the #content div, and make that scroll:

html, body { height: 100%; padding: 0; } 
html { width: 100%; background-color: #222; overflow: hidden; margin: 0; } 
body 
{ 
   width: 40em; margin: 0px auto; /* narrow center column layout */
   background-color: white; 
   position: relative; /* allow positioning children relative to this element */
} 
#scrollContainer /* wraps #content, scrolls */
{ 
  overflow: auto; /* scroll! */
  position:absolute; /* make offsetParent */
  top: 0; height: 100%; width: 100%; /* fill parent */
} 
#header 
{ 
  position: absolute; 
  top: 0px; height: 50px; width: 38.5em; 
  background-color: white; 
  z-index: 1; /* sit above #content in final layout */
} 
#content { padding: 5px 14px 50px 5px;  } 

Tested in FF 3.5.5, Chrome 3.0.195.33, IE8

Live demonstration:

_x000D_
_x000D_
$(function() {_x000D_
        $('#header').find('button').click(function(ev) {_x000D_
          var button = $(this), target = $('div.' + button.attr('class'));_x000D_
          var scroll = target.offsetParent().scrollTop(); _x000D_
          target.offsetParent().scrollTop(target.offset().top + scroll - 50);_x000D_
        });_x000D_
      });
_x000D_
html, body { height: 100%; padding: 0; }_x000D_
      html { width: 100%; background-color: #222; overflow: hidden; margin: 0; }_x000D_
      body { width: 40em; margin: 0px auto; background-color: white; position: relative; }_x000D_
      #scrollContainer { overflow: auto; position:absolute; top: 0; height: 100%; width: 100%; }_x000D_
      #header { position: absolute; top: 0px; height: 50px; width: 38.5em; background-color: white; z-index: 1; }_x000D_
      #content { padding: 5px 14px 50px 5px;  }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
    <div id='header'> _x000D_
      Header Box_x000D_
      <button class='A'>A</button> _x000D_
      <button class='B'>B</button> _x000D_
      <button class='C'>C</button> _x000D_
    </div> _x000D_
    <div id='scrollContainer'>_x000D_
    <div id='content'> _x000D_
      <div style='height: 50px'> </div> _x000D_
      <div class='A'> _x000D_
        <h1>A</h1> _x000D_
        <p>My name is Boffer Bings. I was born of honest parents in one of the humbler walks of life, my father being a manufacturer of dog-oil and my mother having a small studio in the shadow of the village church, where she disposed of unwelcome babes. In my boyhood I was trained to habits of industry; I not only assisted my father in procuring dogs for his vats, but was frequently employed by my mother to carry away the debris of her work in the studio. In performance of this duty I sometimes had need of all my natural intelligence for all the law officers of the vicinity were opposed to my mother's business. They were not elected on an opposition ticket, and the matter had never been made a political issue; it just happened so. My father's business of making dog-oil was, naturally, less unpopular, though the owners of missing dogs sometimes regarded him with suspicion, which was reflected, to some extent, upon me. My father had, as silent partners, all the physicians of the town, who seldom wrote a prescription which did not contain what they were pleased to designate as _Ol. can._ It is really the most valuable medicine ever discovered. But most persons are unwilling to make personal sacrifices for the afflicted, and it was evident that many of the fattest dogs in town had been forbidden to play with me--a fact which pained my young sensibilities, and at one time came near driving me to become a pirate._x000D_
      </div> _x000D_
      <div class='B'> _x000D_
        <h1>B</h1> _x000D_
        <p> _x000D_
        Looking back upon those days, I cannot but regret, at times, that by indirectly bringing my beloved parents to their death I was the author of misfortunes profoundly affecting my future._x000D_
        <p> _x000D_
        One evening while passing my father's oil factory with the body of a foundling from my mother's studio I saw a constable who seemed to be closely watching my movements. Young as I was, I had learned that a constable's acts, of whatever apparent character, are prompted by the most reprehensible motives, and I avoided him by dodging into the oilery by a side door which happened to stand ajar. I locked it at once and was alone with my dead. My father had retired for the night. The only light in the place came from the furnace, which glowed a deep, rich crimson under one of the vats, casting ruddy reflections on the walls. Within the cauldron the oil still rolled in indolent ebullition, occasionally pushing to the surface a piece of dog. Seating myself to wait for the constable to go away, I held the naked body of the foundling in my lap and tenderly stroked its short, silken hair. Ah, how beautiful it was! Even at that early age I was passionately fond of children, and as I looked upon this cherub I could almost find it in my heart to wish that the small, red wound upon its breast--the work of my dear mother--had not been mortal._x000D_
      </div> _x000D_
      <div class='C'> _x000D_
        <h1>C</h1> _x000D_
        <p>It had been my custom to throw the babes into the river which nature had thoughtfully provided for the purpose, but that night I did not dare to leave the oilery for fear of the constable. "After all," I said to myself, "it cannot greatly matter if I put it into this cauldron. My father will never know the bones from those of a puppy, and the few deaths which may result from administering another kind of oil for the incomparable _ol. can._ are not important in a population which increases so rapidly." In short, I took the first step in crime and brought myself untold sorrow by casting the babe into the cauldron._x000D_
      </div> _x000D_
      <div style='height: 75em;'> </div> _x000D_
    </div> _x000D_
    </div>
_x000D_
_x000D_
_x000D_

Multi-gradient shapes

You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)

<!-- Normal state. -->
<item>
    <layer-list>
        <item>  
            <shape>
                <gradient 
                    android:startColor="@color/grey_light"
                    android:endColor="@color/grey_dark"
                    android:type="linear"
                    android:angle="270"
                    android:centerColor="@color/grey_mediumtodark" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
        <item>  
            <shape>
                <gradient 
                    android:startColor="#00666666"
                    android:endColor="#77666666"
                    android:type="radial"
                    android:gradientRadius="200"
                    android:centerColor="#00666666"
                    android:centerX="0.5"
                    android:centerY="0" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
    </layer-list>
</item>

How to check if image exists with given url?

Use Case

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API :

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

Note : rm means here risk managment .


Another Use Case :

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • 'http://example/1.png' : if not exist 'http://example/2.png'

  • 'http://example/2.png' : if not exist 'http://example/3.png'

Error: Uncaught SyntaxError: Unexpected token <

I too got this error, when developing a Backbone application using HTML5 push state in conjunction with an .htaccess which redirects any unknown files to index.html.

It turns out that when visiting a URL such as /something/5, my /index.html was effectively being served at /something/index.html (thanks to my .htaccess). This had the effect of breaking all the relative URLs to my JavaScript files (from inside the index.html ), which meant that they should have 404'd on me.

However, again due to my htaccess, instead of 404'ing when attempting to retrieve the JS files, they instead returned my index.html. Thus the browser was given an index.html for every JavaScript file it tried to pull in, and when it evaluated the HTML as if it were JavaScript, it returned a JS error due to the leading < (from my tag in index.html).

The fix in my case (as I was serving the site from inside a subdirectory) was to add a base tag in my html head.

<base href="/my-app/">

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.

If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.

How to check if an integer is within a range?

Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:

Check if $n is between $a and $b even if:
    $a < $b  
    $a > $b
    $a = $b

All numbers can be real, not only integer.

There is an easy way to test.
I base the test it in the fact that ($n-$a) and ($n-$b) have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

Visual Studio: ContextSwitchDeadlock

In Visual Studio 2017 Spanish version.

"Depurar" -> "Ventanas" -> "Configuración de Excepciones"

and search "ContextSwitchDeadlock". Then, uncheck it. Or shortcut

Ctrl+D,E

Best.

How to focus on a form input text field on page load using jQuery?

Sorry for bumping an old question. I found this via google.

Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.

eg.

$('#myform input,#myform textarea').first().focus();

This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.

How to find serial number of Android device?

There is an excellent post on the Android Developer's Blog discussing this.

It recommends against using TelephonyManager.getDeviceId() as it doesn't work on Android devices which aren't phones such as tablets, it requires the READ_PHONE_STATE permission and it doesn't work reliably on all phones.

Instead you could use one of the following:

  • Mac Address
  • Serial Number
  • ANDROID_ID

The post discusses the pros and cons of each and it's worth reading so you can work out which would be the best for your use.

RSA: Get exponent and modulus given a public key

I manage to find the answer for this solution, have to do javascript injection for this to install atob

const atob:any = require('atob');
asn1(pem: any){
      asn1parser.Enc.base64ToBuf = function (b64:any) {
    return asn1parser.Enc.binToBuf(atob(b64));
  };
  const dertest = asn1parser.PEM.parseBlock(pem).der;
   var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
   var buf = asn1parser.ASN1.parse(dertest);
  var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true) is set.

This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do

index.html

Set the <base> element properly

<base href="@(Request.ApplicationPath + "/")">

web.config

First redirect 404 to a custom page, for example "Home/Error"

<system.web>
    <customErrors mode="On">
        <error statusCode="404" redirect="~/Home/Error" />
    </customErrors>
</system.web>

Home controller

Implement a simple ActionResult to "translate" input in a clientside route.

public ActionResult Error(string aspxerrorpath) {
    return this.Redirect("~/#/" + aspxerrorpath);
}

This is the simplest way.


It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes

.when("/", {
    templateUrl: "Base/Home",
    controller: "controllerHome"
})
.when("/New", {
    templateUrl: "Base/New",
    controller: "controllerNew"
})
.when("/Show/:title", {
    templateUrl: "Base/Show",
    controller: "controllerShow"
})

It makes sense to redirect URL to client only when it start with "/New" or "/Show/"

public ActionResult Error(string aspxerrorpath) {
    // get clientside route path
    string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);

    // create a set of valid clientside path
    string[] validPaths = { "/New", "/Show/" };

    // check if clientPath is valid and redirect properly
    foreach (string validPath in validPaths) {
        if (clientPath.StartsWith(validPath)) {
            return this.Redirect("~/#/" + clientPath);
        }
    }

    return new HttpNotFoundResult();
}

This is just an example of improved logic, of course every web application has different needs

how to fire event on file select

vanilla js using es6

document.querySelector('input[name="file"]').addEventListener('change', (e) => {
 const file = e.target.files[0];
  // todo: use file pointer
});

notifyDataSetChanged not working on RecyclerView

Try this method:

List<Business> mBusinesses2 = mBusinesses;
mBusinesses.clear();
mBusinesses.addAll(mBusinesses2);
//and do the notification

a little time consuming, but it should work.

How to embed PDF file with responsive width

If you're using Bootstrap 3, you can use the embed-responsive class and set the padding bottom as the height divided by the width plus a little extra for toolbars. For example, to display an 8.5 by 11 PDF, use 130% (11/8.5) plus a little extra (20%).

<div class='embed-responsive' style='padding-bottom:150%'>
    <object data='URL.pdf' type='application/pdf' width='100%' height='100%'></object>
</div>

Here's the Bootstrap CSS:

.embed-responsive {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}

Nginx: Job for nginx.service failed because the control process exited

$ ps ax | grep nginx<br>
$ kill -9 PIDs
$ service nginx start



or set back /etc/nginx/sites-available/default

location / {
     # First attempt to serve request as file, then
     # as directory, then fall back to displaying a 404.

     try_files $uri $uri/ =404;
}

Remove Primary Key in MySQL

First backup the database. Then drop any foreign key associated with the table. truncate the foreign key table.Truncate the current table. Remove the required primary keys. Use sqlyog or workbench or heidisql or dbeaver or phpmyadmin.

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
        MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

        cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg", self.myJson[indexPath.row][@"movieId"]]];

        NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data) {
                UIImage *image = [UIImage imageWithData:data];
                if (image) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
                        if (updateCell)
                            updateCell.poster.image = image;
                    });
                }
            }
        }];
        [task resume];

        return cell;
    }

How to retrieve the LoaderException property?

try
{
  // load the assembly or type
}
catch (Exception ex)
{
  if (ex is System.Reflection.ReflectionTypeLoadException)
  {
    var typeLoadException = ex as ReflectionTypeLoadException;
    var loaderExceptions  = typeLoadException.LoaderExceptions;
  }
}

Java, List only subdirectories from a directory, not files

Here is solution for my code. I just did a litlle change from first answer. This will list all folders only in desired directory line by line:

try {
            File file = new File("D:\\admir\\MyBookLibrary");
            String[] directories = file.list(new FilenameFilter() {
              @Override
              public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
              }
            });
            for(int i = 0;i < directories.length;i++) {
                if(directories[i] != null) {
                    System.out.println(Arrays.asList(directories[i]));

                }
            }
        }catch(Exception e) {
            System.err.println("Error!");
        }

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

What is the best/simplest way to read in an XML file in Java application?

I've only used jdom. It's pretty easy.

Go here for documentation and to download it: http://www.jdom.org/

If you have a very very large document then it's better not to read it all into memory, but use a SAX parser which calls your methods as it hits certain tags and attributes. You have to then create a state machine to deal with the incoming calls.

Use SELECT inside an UPDATE query

I did want to add one more answer that utilizes a VBA function, but it does get the job done in one SQL statement. Though, it can be slow.

UPDATE FUNCTIONS
SET FUNCTIONS.Func_TaxRef = DLookUp("MinOfTax_Code", "SELECT
FUNCTIONS.Func_ID,Min(TAX.Tax_Code) AS MinOfTax_Code
FROM TAX, FUNCTIONS
WHERE (((FUNCTIONS.Func_Pure)<=[Tax_ToPrice]) AND ((FUNCTIONS.Func_Year)=[Tax_Year]))
GROUP BY FUNCTIONS.Func_ID;", "FUNCTIONS.Func_ID=" & Func_ID)

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

I was able to sort this out using Gorgando's fix, but instead of moving imports away, I commented each out individually, built the app, then edited accordingly until I got rid of them.

wampserver doesn't go green - stays orange

Make a Ctrl+Alt+Suppr in order to see if no other Apache version is ever runing on your computer. It was the case for me, I just stop them and the light pass green!

Cheers!

Drawing in Java using Canvas

Suggestions:

  • Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
  • Instead use a JPanel or JComponent.
  • Don't get your Graphics object by calling getGraphics() on a component as the Graphics object obtained will be transient.
  • Draw in the JPanel's paintComponent() method.
  • All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?

Key tutorial links:

How to check if an Object is a Collection Type in Java?

Test if the object implements either java.util.Collection or java.util.Map. (Map has to be tested separately because it isn't a sub-interface of Collection.)

File upload from <input type="file">

just try (onclick)="this.value = null"

in your html page add onclick method to remove previous value so user can select same file again.

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

How can I get the executing assembly version?

using System.Reflection;
{
    string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}

Remarks from MSDN http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly%28v=vs.110%29.aspx:

The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.

Opening a SQL Server .bak file (Not restoring!)

It doesn't seem possible with SQL Server 2008 alone. You're going to need a third-party tool's help.

It will help you make your .bak act like a live database:

http://www.red-gate.com/products/dba/sql-virtual-restore/

Correct way to initialize empty slice

They are equivalent. See this code:

mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))

Output:

mySlice1 0
mySlice2 0

Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

See similar questions:

What is the point of having nil slice and empty slice in golang?

nil slices vs non-nil slices vs empty slices in Go language

How to replace spaces in file names using a bash script

A find/rename solution. rename is part of util-linux.

You need to descend depth first, because a whitespace filename can be part of a whitespace directory:

find /tmp/ -depth -name "* *" -execdir rename " " "_" "{}" ";"

Use child_process.execSync but keep output in console

Simply:

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    console.log(`Status Code: ${error.status} with '${error.message}'`;
 }

Ref: https://stackoverflow.com/a/43077917/104085

// nodejs
var execSync = require('child_process').execSync;

// typescript
const { execSync } = require("child_process");

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    error.status;  // 0 : successful exit, but here in exception it has to be greater than 0
    error.message; // Holds the message you typically want.
    error.stderr;  // Holds the stderr output. Use `.toString()`.
    error.stdout;  // Holds the stdout output. Use `.toString()`.
 }

enter image description here

enter image description here

When command runs successful: enter image description here

Cannot connect to repo with TortoiseSVN

Try clearing the settings under "Saved Data" - refer to:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html

This worked for me with Windows 7.

Eric

Taking multiple inputs from user in python

You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed

user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:
    print(i)

How to do a subquery in LINQ?

This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.

from u in Users
join c in (
    from crt in CompanyRolesToUsers
    where CompanyRoleId == 2
    || CompanyRoleId == 3
    || CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

You need to store the returned function and call it to unsubscribe from the event.

var deregisterListener = $scope.$on("onViewUpdated", callMe);
deregisterListener (); // this will deregister that listener

This is found in the source code :) at least in 1.0.4. I'll just post the full code since it's short

/**
  * @param {string} name Event name to listen on.
  * @param {function(event)} listener Function to call when the event is emitted.
  * @returns {function()} Returns a deregistration function for this listener.
  */
$on: function(name, listener) {
    var namedListeners = this.$$listeners[name];
    if (!namedListeners) {
      this.$$listeners[name] = namedListeners = [];
    }
    namedListeners.push(listener);

    return function() {
      namedListeners[indexOf(namedListeners, listener)] = null;
    };
},

Also, see the docs.

How to backup a local Git repository?

[Just leaving this here for my own reference.]

My bundle script called git-backup looks like this

#!/usr/bin/env ruby
if __FILE__ == $0
        bundle_name = ARGV[0] if (ARGV[0])
        bundle_name = `pwd`.split('/').last.chomp if bundle_name.nil? 
        bundle_name += ".git.bundle"
        puts "Backing up to bundle #{bundle_name}"
        `git bundle create /data/Dropbox/backup/git-repos/#{bundle_name} --all`
end

Sometimes I use git backup and sometimes I use git backup different-name which gives me most of the possibilities I need.

CR LF notepad++ removal

"View -> Show Symbol -> uncheck Show All characters" may not work if you have pending update for notepad++. So update Notepad++ and then View -> Show Symbol -> uncheck Show All characters

Hope this is helpful!

A python class that acts like dict

Like this

class CustomDictOne(dict):
   def __init__(self,*arg,**kw):
      super(CustomDictOne, self).__init__(*arg, **kw)

Now you can use the built-in functions, like dict.get() as self.get().

You do not need to wrap a hidden self._dict. Your class already is a dict.

How to Get Element By Class in JavaScript?

When some elements lack ID, I use jQuery like this:

$(document).ready(function()
{
    $('.myclass').attr('id', 'myid');
});

This might be a strange solution, but maybe someone find it useful.

Add space between HTML elements only using CSS

You can style elements with excluding first one, just in one line of code:

span ~ span {
    padding-left: 10px;
}

No need to change any classes.

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

How can I set my Cygwin PATH to find javac?

as you write the it with double-quotes, you don't need to escape spaces with \

export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"

of course this also works:

export PATH=$PATH:/cygdrive/C/Program\ Files/Java/jdk1.6.0_23/bin/

Passing environment-dependent variables in webpack

Just another option, if you want to use only a cli interface, just use the define option of webpack. I add the following script in my package.json :

"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"

So I just have to run npm run build-production.

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

How to programmatically set cell value in DataGridView?

I came across the same problem and solved it as following for VB.NET. It's the .NET Framework so you should be possible to adapt. Wanted to compare my solution and now I see that nobody seems to solve it my way.

Make a field declaration.

Private _currentDataView as DataView

So looping through all the rows and searching for a cell containing a value that I know is next to the cell I want to change works for me.

Public Sub SetCellValue(ByVal value As String)
    Dim dataView As DataView = _currentDataView

    For i As Integer = 0 To dataView.Count - 1
        If dataView(i).Row.Item("projID").ToString.Equals("139") Then
            dataView(i).Row.Item("Comment") = value
            Exit For ' Exit early to save performance
        End If
    Next
End Sub

So that you can better understand it. I know that ColumnName "projID" is 139. I loop until I find it and then I can change the value of "ColumnNameofCell" in my case "Comment". I use this for comments added on runtime.

dataview

How to assign execute permission to a .sh file in windows to be executed in linux

The ZIP file format does allow to store the permission bits, but Windows programs normally ignore it. The zip utility on Cygwin however does preserve the x bit, just like it does on Linux. If you do not want to use Cygwin, you can take a source code and tweak it so that all *.sh files get the executable bit set. Or write a script like explained here

Script not served by static file handler on IIS7.5

I had the same issue, I just changed the target framework version on the website to the version it is developed in,Same in IIS. This solved my problem. Hope this helps...

Thank You

How can I use pointers in Java?

you can have pointers for literals as well. You have to implement them yourself. It is pretty basic for experts ;). Use an array of int/object/long/byte and voila you have the basics for implementing pointers. Now any int value can be a pointer to that array int[]. You can increment the pointer, you can decrement the pointer, you can multiply the pointer. You indeed have pointer arithmetics! That's the only way to implements 1000 int attributes classes and have a generic method that applies to all attributes. You can also use a byte[] array instead of an int[]

However I do wish Java would let you pass literal values by reference. Something along the lines

//(* telling you it is a pointer) public void myMethod(int* intValue);

Spring Boot Java Config Set Session Timeout

You should be able to set the server.session.timeout in your application.properties file.

ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Disable validation of HTML5 form elements

I found a solution for Chrome with CSS this following selector without bypassing the native verification form which could be very useful.

form input::-webkit-validation-bubble-message, 
form select::-webkit-validation-bubble-message,
form textarea::-webkit-validation-bubble-message {
    display:none;
} 

By this way, you can also customise your message...

I got the solution on this page : http://trac.webkit.org/wiki/Styling%20Form%20Controls

Creating a UIImage from a UIColor to use as a background image for UIButton

CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);

What is the curl error 52 "empty reply from server"?

In my case this was caused by a PHP APC problem. First place to look would be the Apache error logs (if you are using Apache).

Hope this helps somebody.

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

PHP: How can I determine if a variable has a value that is between two distinct constant values?

if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
   // A value between 1 to 10, or 20 to 40.
}

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|")));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|", -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

Create the perfect JPA entity

I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.

Entity Class: implement Serializable?

Keys needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.

Constructors: create a constructor with all required fields of the entity?

Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.

Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.

OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.

Constructors: also, package private default constructor?

Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.

Fields/Properties

Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.

As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.

Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.

Protected is better for (Hibernate) performance?

Unlikely.

Equals/HashCode?

This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.

A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.

The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!

So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.

You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.

Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized

Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.

Equals/HashCode -- never refer to related entities

"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"

Sounds like good advice.

Hope this helps!

White space showing up on right side of page when background image should extend full length of page

Apparently the (-o-min-device-pixel-ratio: 3/2) is causing problems. On my test site it was causing the right side to be cut off. I found a workaround on github that works for now. Using(-o-min-device-pixel-ratio: ~"3/2") seems to work fine.

Why can't I have "public static const string S = "stuff"; in my Class?

From the C# language specification (PDF page 287 - or 300th page of the PDF):

Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.

Overriding the java equals() method - not working?

in Android Studio is alt + insert ---> equals and hashCode

Example:

    @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Proveedor proveedor = (Proveedor) o;

    return getId() == proveedor.getId();

}

@Override
public int hashCode() {
    return getId();
}

How do I set default value of select box in angularjs

if you don't even want to initialize ng-model to a static value and each value is DB driven, it can be done in the following way. Angular compares the evaluated value and populates the drop down.

Here below modelData.unitId is retrieved from DB and is compared to the list of unit id which is a separate list from db-

_x000D_
_x000D_
 <select id="uomList" ng-init="modelData.unitId"_x000D_
                         ng-model="modelData.unitId" ng-options="unitOfMeasurement.id as unitOfMeasurement.unitName for unitOfMeasurement in unitOfMeasurements">
_x000D_
_x000D_
_x000D_

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar issue with Spring Data MongoDB: I had to add the package path to @EnableMongoRepositories

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

JavaScript: How to pass object by value?

Using the spread operator like obj2 = { ...obj1 } Will have same values but different references

How to get the file path from HTML input form in Firefox 3

This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.

http://www.ab-d.fr/date/2008-07-12/

It is in french, but the code is javascript :)

This are the references the article points to: http://developer.mozilla.org/en/nsIDOMFile http://developer.mozilla.org/en/nsIDOMFileList

Use IntelliJ to generate class diagram

Use Diagrams | Show Diagram... from the context menu of a package. Invoking it on the project root will show module dependencies diagram.

If you need multiple packages, you can drag & drop them to the already opened diagram for the first package and press e to expand it.

Note: This feature is available in the Ultimate Edition, not the free Community Edition.

What is the correct XPath for choosing attributes that contain "foo"?

If you also need to match the content of the link itself, use text():

//a[contains(@href,"/some_link")][text()="Click here"]

Saving an image in OpenCV

In my experience OpenCV writes a black image when SaveImage is given a matrix with bit depth different from 8 bit. In fact, this is sort of documented:

Only 8-bit single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use cvCvtScale and cvCvtColor to convert it before saving, or use universal cvSave to save the image to XML or YAML format.

In your case you may first investigate what kind of image is captured, change capture properties (I suppose CV_CAP_PROP_CONVERT_RGB might be important) or convert it manually afterwards.

This is an example how to convert to 8-bit representation with OpenCV. cc here is an original matrix of type CV_32FC1, cc8u is its scaled version which is actually written by SaveImage:

# I want to save cc here
cc8u = CreateMat(cc.rows, cc.cols, CV_8U)
ccmin,ccmax,minij,maxij = MinMaxLoc(cc)
ccscale, ccshift = 255.0/(ccmax-ccmin), -ccmin
CvtScale(cc, cc8u, ccscale, ccshift)
SaveImage("cc.png", cc8u)

(sorry, this is Python code, but it should be easy to translate it to C/C++)

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

Just reset your simulator by clicking Simulator-> Reset Contents and Settings..

Dynamic variable names in Bash

For indexed arrays, you can reference them like so:

foo=(a b c)
bar=(d e f)

for arr_var in 'foo' 'bar'; do
    declare -a 'arr=("${'"$arr_var"'[@]}")'
    # do something with $arr
    echo "\$$arr_var contains:"
    for char in "${arr[@]}"; do
        echo "$char"
    done
done

Associative arrays can be referenced similarly but need the -A switch on declare instead of -a.

How to use pip with python 3.4 on windows?

Assuming you don't have any other Python installations, you should be able to do python -m pip after a default installation. Something like the following should be in your system path:

C:\Python34\Scripts

This would obviously be different, if you installed Python in a different location.

How to convert const char* to char* in C?

First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char* arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash.

Use cast:

(char*)const_char_ptr

failed to find target with hash string android-23

In my case, clearing caché didn't work.

On SDK Manager, be sure to check the box on "show package descriptions"; then you should also select the "Google APIs" for the version you are willing to install.

Install it and then you should be ok

Difference between SurfaceView and View?

The main difference is that SurfaceView can be drawn on by background theads but Views can't. SurfaceViews use more resources though so you don't want to use them unless you have to.

Exit/save edit to sudoers file? Putty SSH

Be careful to type exactly :wq as Wouter Verleur said at step 7. After type enter, you will save the changes and exit the visudo editor to bash.

At least one JAR was scanned for TLDs yet contained no TLDs

If one wants to have the conf\logging.properties read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\ folder and then add the lines :

-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager

to the VM arguments of the launch configuration one is using.

This may have taken a restart or two (or not) but finally I saw in the console in bright red :

FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc

I still don't know when exactly this FINE warning appears - does not appear immediately on tomcat launch EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".


Bonus: To make the warning go away add in catalina.properties :

# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar

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

Yo! I had lots of problems with this. It seems that Github brings its own console which you need to look for in your drive. I managed to finally run it by doing the following:

  1. Press Start.
  2. Search for "GitHub" (without quotes)
  3. Right click on "GitHub" and select "Open File Location"

*This shall open *

C:\Users\UserName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\GitHub, Inc

Where username is your PC's username

  1. Look for a program called "Git Shell". Double click on it.

This will open a PowerShell command prompt. Then you can run your git commands normally on it.

Find first element by predicate

return dataSource.getParkingLots()
                 .stream()
                 .filter(parkingLot -> Objects.equals(parkingLot.getId(), id))
                 .findFirst()
                 .orElse(null);

I had to filter out only one object from a list of objects. So i used this, hope it helps.

In the shell, what does " 2>&1 " mean?

File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).

Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: 2>&1.

Consider >& as redirect merger operator.

nginx- duplicate default server error

OS Debian 10 + nginx. In my case, i unlinked the "default" page as:

  1. cd/etc/nginx/sites-enabled
  2. unlink default
  3. service nginx restart

How can I trim beginning and ending double quotes from a string?

public String removeDoubleQuotes(String request) {
    return request.replace("\"", "");
}

Node.js check if path is file or directory

Seriously, question exists five years and no nice facade?

function is_dir(path) {
    try {
        var stat = fs.lstatSync(path);
        return stat.isDirectory();
    } catch (e) {
        // lstatSync throws an error if path doesn't exist
        return false;
    }
}

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

What linux shell command returns a part of a string?

If you are looking for a shell utility to do something like that, you can use the cut command.

To take your example, try:

echo "abcdefg" | cut -c3-5

which yields

cde

Where -cN-M tells the cut command to return columns N to M, inclusive.

Perform curl request in javascript?

You can use JavaScripts Fetch API (available in your browser) to make network requests.

If using node, you will need to install the node-fetch package.

const url = "https://api.wit.ai/message?v=20140826&q=";

const options = {
  headers: {
    Authorization: "Bearer 6Q************"
  }
};

fetch(url, options)
  .then( res => res.json() )
  .then( data => console.log(data) );

How to justify a single flexbox item (override justify-content)

I solved a similar case by setting the inner item's style to margin: 0 auto.
Situation: My menu usually contains three buttons, in which case they need to be justify-content: space-between. But when there's only one button, it will now be center aligned instead of to the left.

What is the memory consumption of an object in Java?

It depends on architecture/jdk. For a modern JDK and 64bit architecture, an object has 12-bytes header and padding by 8 bytes - so minimum object size is 16 bytes. You can use a tool called Java Object Layout to determine a size and get details about object layout and internal structure of any entity or guess this information by class reference. Example of an output for Integer on my environment:

Running 64-bit HotSpot VM.
Using compressed oop with 3-bit shift.
Using compressed klass with 3-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]

java.lang.Integer object internals:
 OFFSET  SIZE  TYPE DESCRIPTION                    VALUE
      0    12       (object header)                N/A
     12     4   int Integer.value                  N/A
Instance size: 16 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

So, for Integer, instance size is 16 bytes, because 4-bytes int compacted in place right after header and before padding boundary.

Code sample:

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.util.VMSupport;

public static void main(String[] args) {
    System.out.println(VMSupport.vmDetails());
    System.out.println(ClassLayout.parseClass(Integer.class).toPrintable());
}

If you use maven, to get JOL:

<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.3.2</version>
</dependency>

Adding the "Clear" Button to an iPhone UITextField

On Xcode 8 (8A218a):

Swift:

textField.clearButtonMode = UITextField.ViewMode.whileEditing;

The "W" went from capital to non-cap "w".

Spring JSON request getting 406 (not Acceptable)

Can you remove the headers element in @RequestMapping and try..

Like


@RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)

I guess spring does an 'contains check' rather than exact match for accept headers. But still, worth a try to remove the headers element and check.

Make Axios send cookies in its requests automatically

for people still not able to solve it, this answer helped me. stackoverflow answer: 34558264

TLDR; one needs to set {withCredentials: true} in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.

Load image from resources area of project in C#

You can also save the bmp in a var like this:

var bmp = Resources.ImageName;

hope it helps!

What is a NullPointerException, and how do I fix it?

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NullPointerException would be:

public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

how to apply click event listener to image in android

ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       // your code here
    }
});

Python - abs vs fabs

math.fabs() always returns float, while abs() may return integer.

REST API - Bulk Create or Update in single request

PUT ing

PUT /binders/{id}/docs Create or update, and relate a single document to a binder

e.g.:

PUT /binders/1/docs HTTP/1.1
{
  "docNumber" : 1
}

PATCH ing

PATCH /docs Create docs if they do not exist and relate them to binders

e.g.:

PATCH /docs HTTP/1.1
[
    { "op" : "add", "path" : "/binder/1/docs", "value" : { "doc_number" : 1 } },
    { "op" : "add", "path" : "/binder/8/docs", "value" : { "doc_number" : 8 } },
    { "op" : "add", "path" : "/binder/3/docs", "value" : { "doc_number" : 6 } }
] 

I'll include additional insights later, but in the meantime if you want to, have a look at RFC 5789, RFC 6902 and William Durand's Please. Don't Patch Like an Idiot blog entry.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

first step: use all https://example.in or ssl certificate URL , dont use http://example.in

second step: faceboook application setting->basic setting->add your domain or subdomain

third step: faceboook application login setting->Valid OAuth Redirect URIs->add your all redirect url after login

fourth step: faceboook application setting->advance setting->Domain Manager->add your domain name

do all this step then use your application id, application version ,app secret for setup

Cannot ping AWS EC2 instance

might be your internal network is blocking that IP to ping or blocked ping packet in your firewall if you have opened in security group and VPC is correct.

How to write palindrome in JavaScript

str1 is the original string with deleted non-alphanumeric characters and spaces and str2 is the original string reversed.

function palindrome(str) {

  var str1 = str.toLowerCase().replace(/\s/g, '').replace(
    /[^a-zA-Z 0-9]/gi, "");

  var str2 = str.toLowerCase().replace(/\s/g, '').replace(
    /[^a-zA-Z 0-9]/gi, "").split("").reverse().join("");


  if (str1 === str2) {
    return true;
  }
  return false;
}

palindrome("almostomla");

Is JavaScript's "new" keyword considered harmful?

Another case for new is what I call Pooh Coding. Winnie the Pooh follows his tummy. I say go with the language you are using, not against it.

Chances are that the maintainers of the language will optimize the language for the idioms they try to encourage. If they put a new keyword into the language they probably think it makes sense to be clear when creating a new instance.

Code written following the language's intentions will increase in efficiency with each release. And code avoiding the key constructs of the language will suffer with time.

EDIT: And this goes well beyond performance. I can't count the times I've heard (or said) "why the hell did they do that?" when finding strange looking code. It often turns out that at the time when the code was written there was some "good" reason for it. Following the Tao of the language is your best insurance for not having your code ridiculed some years from now.

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Alright so after some debugging the following dependencies are using an older version of touch:

./node_modules/bower/node_modules/decompress-zip/package.json:    "touch": "0.0.3"
./node_modules/bower/node_modules/lockfile/package.json:    "touch": "0"
./node_modules/gulp-nodemon/node_modules/nodemon/package.json:    "touch": "1.0.0",
./node_modules/gulp-nodemon/node_modules/touch/package.json:    "touch": "./bin/touch.js"
./node_modules/nodemon/package.json:    "touch": "~0.0.3",

With that I was able to get meanJS working with node 5.

Here is the history on the commands I ran:

git clone https://github.com/meanjs/mean.git
cd mean
nvm install 5
nvm use 5
npm install
which node-gyp
npm install -g node-pre-gyp
sudo xcodebuild -license
npm install

Had some issues and then:

I added the following line:

#!/usr/bin/env node

To the top of the file ./mean/node_modules/.bin/touch

And then:

npm install

And of course maybe throw in a sudo rm -rf ./node_modules && npm cache clean before retrying.

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Does a valid XML file require an XML declaration?

In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.

Note that in an XML Declaration the encoding and standalone are both optional. Only the version is mandatory. Also, these are not attributes, so if they are present they must be in that order: version, followed by any encoding, followed by any standalone.

<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>

If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.

The standalone indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.

Update:

A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.

Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?> which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding and simply say <?xml version="1.0"?>. You could also edit it to say encoding="UTF-16" but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.

Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!

Get absolute path to workspace directory in Jenkins Pipeline plugin

Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}

Convert integer into byte array (Java)

Here's a method that should do the job just right.

public byte[] toByteArray(int value)
{
    final byte[] destination = new byte[Integer.BYTES];
    for(int index = Integer.BYTES - 1; index >= 0; index--)
    {
        destination[i] = (byte) value;
        value = value >> 8;
    };
    return destination;
};

Inserting created_at data with Laravel

In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:

// Create new user
$user = factory(User::class)->create();

// Add an email verification token to the 
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();

// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);

// Do the update
\DB::update(
    'UPDATE email_verification_tokens SET created_at = ?',
    [$created_at]
);

Note: For anything other than unit testing, I would look at the other answers here.

disable all form elements inside div

$('#mydiv').find('input, textarea, button, select').attr('disabled','disabled');

simple way to display data in a .txt file on a webpage?

If you just want to throw the contents of the file onto the screen you can try using PHP.

<?php
    $myfilename = "mytextfile.txt";
    if(file_exists($myfilename)){
      echo file_get_contents($myfilename);
    }
?>

RestSharp simple complete example

Changing

RestResponse response = client.Execute(request);

to

IRestResponse response = client.Execute(request);

worked for me.

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/ directory, or Scripts\ on Windows).

The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.

Failed to authenticate on SMTP server error using gmail

Did you turn on the "Allow less secure apps" on? go to this link

https://myaccount.google.com/security#connectedapps

Take a look at the Sign-in & security -> Apps with account access menu.

You must turn the option "Allow less secure apps" ON.

If is still doesn't work try one of these:

And change your .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls

because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.

Oracle SQL, concatenate multiple columns + add text

The Oracle/PLSQL CONCAT function allows to concatenate two strings together.

CONCAT( string1, string2 )

string1

The first string to concatenate.

string2

The second string to concatenate.

E.g.

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake FROM table;

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

Generating a drop down list of timezones with PHP

Here's one that creates a multidimensional array sorted by offset and niceified name:

function timezones() {
    $timezones = [];

    foreach (timezone_identifiers_list() as $timezone) {
        $datetime = new \DateTime('now', new DateTimeZone($timezone));
        $timezones[] = [
            'sort' => str_replace(':', '', $datetime->format('P')),
            'offset' => $datetime->format('P'),
            'name' => str_replace('_', ' ', implode(', ', explode('/', $timezone))),
            'timezone' => $timezone,
        ];
    }

    usort($timezones, function($a, $b) {
        return $a['sort'] - $b['sort'] ?: strcmp($a['name'], $b['name']);
    });

    return $timezones;
}

foreach (timezones() as $timezone) {
    echo '(UTC '.$timezone['offset'].') '.$timezone['name'].'<br>';
}

Echos:

(UTC -11:00) Pacific, Midway
(UTC -11:00) Pacific, Niue
(UTC -11:00) Pacific, Pago Pago
(UTC -10:00) Pacific, Honolulu
(UTC -10:00) Pacific, Johnston
(UTC -10:00) Pacific, Rarotonga
(UTC -10:00) Pacific, Tahiti
(UTC -09:30) Pacific, Marquesas
(UTC -09:00) America, Adak
(UTC -09:00) Pacific, Gambier
(UTC -08:00) America, Anchorage
(UTC -08:00) America, Juneau
...

When should you use 'friend' in C++?

One specific instance where I use friend is when creating Singleton classes. The friend keyword lets me create an accessor function, which is more concise than always having a "GetInstance()" method on the class.

/////////////////////////
// Header file
class MySingleton
{
private:
    // Private c-tor for Singleton pattern
    MySingleton() {}

    friend MySingleton& GetMySingleton();
}

// Accessor function - less verbose than having a "GetInstance()"
//   static function on the class
MySingleton& GetMySingleton();


/////////////////////////
// Implementation file
MySingleton& GetMySingleton()
{
    static MySingleton theInstance;
    return theInstance;
}

Paging with Oracle

Something like this should work: From Frans Bouma's Blog

SELECT * FROM
(
    SELECT a.*, rownum r__
    FROM
    (
        SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'
        ORDER BY OrderDate DESC, ShippingDate DESC
    ) a
    WHERE rownum < ((pageNumber * pageSize) + 1 )
)
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)

Send message to specific client with socket.io and node.js

You can use

//send message only to sender-client

socket.emit('message', 'check this');

//or you can send to all listeners including the sender

io.emit('message', 'check this');

//send to all listeners except the sender

socket.broadcast.emit('message', 'this is a message');

//or you can send it to a room

socket.broadcast.to('chatroom').emit('message', 'this is the message to all');

How do I initialize an empty array in C#?

Try this:

string[] a = new string[] { };

How to get previous month and year relative to today, using strtotime and date?

If you want the previous year and month relative to a specific date and have DateTime available then you can do this:

$d = new DateTime('2013-01-01', new DateTimeZone('UTC')); 
$d->modify('first day of previous month');
$year = $d->format('Y'); //2012
$month = $d->format('m'); //12

flutter corner radius with transparent background

Use transparent background color for the modalbottomsheet and give separate color for box decoration


   showModalBottomSheet(
      backgroundColor: Colors.transparent,
      context: context, builder: (context) {
    return Container(

      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
            topLeft:Radius.circular(40) ,
            topRight: Radius.circular(40)
        ),
      ),
      padding: EdgeInsets.symmetric(vertical: 20,horizontal: 60),
      child: Settings_Form(),
    );
  });

AngularJS is rendering <br> as text not as a newline

Why so complicated?

I solved my problem this way simply:

  <pre>{{existingCategory+thisCategory}}</pre>

It will make <br /> automatically if the string contains '\n' that contain when I was saving data from textarea.

php execute a background process

Write the process as a server-side script in whatever language (php/bash/perl/etc) is handy and then call it from the process control functions in your php script.

The function probably detects if standard io is used as the output stream and if it is then that will set the return value..if not then it ends

proc_close( proc_open( "./command --foo=1 &", array(), $foo ) );

I tested this quickly from the command line using "sleep 25s" as the command and it worked like a charm.

(Answer found here)

Reverse a string without using reversed() or [::-1]?

I have got an example to reverse strings in python from thecrazyprogrammer.com:

string1 =  "IkNoWwHeReYoUlIvE"
string2 = ""

i = len(string1)-1

while(i>=0):
  string2 = string2 + string1[i]
  i = i-1

print("original = " + string1)
print("reverse  = " + string2)

Where is Java Installed on Mac OS X?

Use unix find function to find javas installed...

sudo find / -name java

Finding element in XDocument?

You can do it this way:

xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "Name of the node to find")

where xml is a XDocument.

Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.

XPath test if node value is number

I've been dealing with 01 - which is a numeric.

string(number($v)) != string($v) makes the segregation

Convert List<String> to List<Integer> directly

If you're allowed to use lambdas from Java 8, you can use the following code sample.

final String text = "1:2:3:4:5";
final List<Integer> list = Arrays.asList(text.split(":")).stream()
  .map(s -> Integer.parseInt(s))
  .collect(Collectors.toList());
System.out.println(list);

No use of external libraries. Plain old new Java!

Text size of android design TabLayout tabs

Do as following.

1. Add the Style to the XML

    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
    </style>

2. Apply Style

Find the Layout containing the TabLayout and add the style. The added line is bold.

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/MyTabLayoutTextAppearance" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

Is there a limit on number of tcp/ip connections between machines on linux?

Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux

How to set selected index JComboBox by value

public static void setSelectedValue(JComboBox comboBox, int value)
    {
        ComboItem item;
        for (int i = 0; i < comboBox.getItemCount(); i++)
        {
            item = (ComboItem)comboBox.getItemAt(i);
            if (item.getValue().equalsIgnoreCase(value))
            {
                comboBox.setSelectedIndex(i);
                break;
            }
        }
    }

Hope this help :)

How to change the type of a field?

I need to change datatype of multiple fields in the collection, so I used the following to make multiple data type changes in the collection of documents. Answer to an old question but may be helpful for others.

db.mycoll.find().forEach(function(obj) { 

    if (obj.hasOwnProperty('phone')) {
        obj.phone = "" + obj.phone;  // int or longint to string
    }

    if (obj.hasOwnProperty('field-name')) {
     obj.field-name = new NumberInt(obj.field-name); //string to integer
    }

    if (obj.hasOwnProperty('cdate')) {
        obj.cdate = new ISODate(obj.cdate); //string to Date
    }

    db.mycoll.save(obj); 
});

Sorting std::map using value

U can consider using boost::bimap that might gave you a feeling that map is sorted by key and by values simultaneously (this is not what really happens, though)

PHP class not found but it's included

After nearly two hours of debugging I have concluded that the best solution to this is to give the file name a different name to the class that it contains. For Example:

Before example.php contains:

<?php
 class example {

 }

Solution: rename the file to example.class.php (or something like that), or rename the class to example_class (or something like that)

Hope this helps.

java.net.UnknownHostException: Invalid hostname for server: local

If your /etc/localhosts file has entry as below: Add hostname entry as below:

127.0.0.1 local host (add your hostname here)
::1 (add hostname here) (the last one is IPv6).

This should resolve the issue.

Mapping list in Yaml to list of objects in Spring Boot

I tried 2 solutions, both work.

Solution_1

.yml

available-users-list:
  configurations:
    -
      username: eXvn817zDinHun2QLQ==
      password: IP2qP+BQfWKJMVeY7Q==
    -
      username: uwJlOl/jP6/fZLMm0w==
      password: IP2qP+BQKJLIMVeY7Q==

LoginInfos.java

@ConfigurationProperties(prefix = "available-users-list")
@Configuration
@Component
@Data
public class LoginInfos {
    private List<LoginInfo> configurations;

    @Data
    public static class LoginInfo {
        private String username;
        private String password;
    }

}
List<LoginInfos.LoginInfo> list = loginInfos.getConfigurations();

Solution_2

.yml

available-users-list: '[{"username":"eXvn817zHBVn2QLQ==","password":"IfWKJLIMVeY7Q=="}, {"username":"uwJlOl/g9jP6/0w==","password":"IP2qWKJLIMVeY7Q=="}]'

Java

@Value("${available-users-listt}")
String testList;

ObjectMapper mapper = new ObjectMapper();
LoginInfos.LoginInfo[] array = mapper.readValue(testList, LoginInfos.LoginInfo[].class);

get list of packages installed in Anaconda

in terminal, type : conda list to obtain the packages installed using conda.

for the packages that pip recognizes, type : pip list

There may be some overlap of these lists as pip may recognize packages installed by conda (but maybe not the other way around, IDK).

There is a useful source here, including how to update or upgrade packages..

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

To understand, let's consider below code snippet:

struct Foo{};
struct Bar{};

int main(int argc, char** argv)
{
    Foo* f = new Foo;

    Bar* b1 = f;                              // (1)
    Bar* b2 = static_cast<Bar*>(f);           // (2)
    Bar* b3 = dynamic_cast<Bar*>(f);          // (3)
    Bar* b4 = reinterpret_cast<Bar*>(f);      // (4)
    Bar* b5 = const_cast<Bar*>(f);            // (5)

    return 0;
}

Only line (4) compiles without error. Only reinterpret_cast can be used to convert a pointer to an object to a pointer to an any unrelated object type.

One this to be noted is: The dynamic_cast would fail at run-time, however on most compilers it will also fail to compile because there are no virtual functions in the struct of the pointer being casted, meaning dynamic_cast will work with only polymorphic class pointers.

When to use C++ cast:

  • Use static_cast as the equivalent of a C-style cast that does value conversion, or when we need to explicitly up-cast a pointer from a class to its superclass.
  • Use const_cast to remove the const qualifier.
  • Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if we know what we are doing and we understand the aliasing issues.

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

How do I clone a range of array elements to a new array?

As far as cloning goes, I don't think serialization calls your constructors. This may break class invariants if you're doing interesting things in the ctor's.

It seems the safer bet is virtual clone methods calling copy constructors.

protected MyDerivedClass(MyDerivedClass myClass) 
{
  ...
}

public override MyBaseClass Clone()
{
  return new MyDerivedClass(this);
}

How to Use Order By for Multiple Columns in Laravel 4?

Use order by like this:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
    ->orderBy('email', 'DESC')
    ...
    ->get();

Python Selenium accessing HTML source

driver.page_source will help you get the page source code. You can check if the text is present in the page source or not.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("some url")
if "your text here" in driver.page_source:
    print('Found it!')
else:
    print('Did not find it.')

If you want to store the page source in a variable, add below line after driver.get:

var_pgsource=driver.page_source

and change the if condition to:

if "your text here" in var_pgsource:

Can I use a case/switch statement with two variables?

First, JavaScript's switch is no faster than if/else (and sometimes much slower).

Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:

var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
    case "foo-bar": ...
    ...
}

But, personally, I would rather see a set of if/else statements.

Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.

Turning off hibernate logging console output

Try to set more reasonable logging level. Setting logging level to info means that only log event at info or higher level (warn, error and fatal) are logged, that is debug logging events are ignored.

log4j.logger.org.hibernate=info

or in XML version of log4j config file:

<logger name="org.hibernate">
  <level value="info"/> 
</logger>

See also log4j manual.

CSS content generation before or after 'input' elements

fyi <form> supports :before / :after as well, might be of help if you wrap your <input> element with it... (got myself a design issue with that too)

Make a Bash alias that takes a parameter?

An alternative solution is to use marker, a tool I've created recently that allows you to "bookmark" command templates and easily place cursor at command place-holders:

commandline marker

I found that most of time, I'm using shell functions so I don't have to write frequently used commands again and again in the command-line. The issue of using functions for this use case, is adding new terms to my command vocabulary and having to remember what functions parameters refer to in the real-command. Marker goal is to eliminate that mental burden.

converting CSV/XLS to JSON?

I just found this:

http://tamlyn.org/tools/csv2json/

( Note: you have to have your csv file available via a web address )

Accessing last x characters of a string in Bash

You can use tail:

$ foo="1234567890"
$ echo -n $foo | tail -c 3
890

A somewhat roundabout way to get the last three characters would be to say:

echo $foo | rev | cut -c1-3 | rev

Simplest SOAP example

You can use the jquery.soap plugin to do the work for you.

This script uses $.ajax to send a SOAPEnvelope. It can take XML DOM, XML string or JSON as input and the response can be returned as either XML DOM, XML string or JSON too.

Example usage from the site:

$.soap({
    url: 'http://my.server.com/soapservices/',
    method: 'helloWorld',

    data: {
        name: 'Remy Blom',
        msg: 'Hi!'
    },

    success: function (soapResponse) {
        // do stuff with soapResponse
        // if you want to have the response as JSON use soapResponse.toJSON();
        // or soapResponse.toString() to get XML string
        // or soapResponse.toXML() to get XML DOM
    },
    error: function (SOAPResponse) {
        // show error
    }
});

Is it possible to remove inline styles with jQuery?

$('div[style*=block]').removeAttr('style');

Datatables warning(table id = 'example'): cannot reinitialise data table

You can also destroy the old datatable by using the following code before creating the new datatable:

$("#example").dataTable().fnDestroy();

Use StringFormat to add a string to a WPF XAML binding

Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Content will not work

NSRange from Swift Range?

For cases like the one you described, I found this to work. It's relatively short and sweet:

 let attributedString = NSMutableAttributedString(string: "follow the yellow brick road") //can essentially come from a textField.text as well (will need to unwrap though)
 let text = "follow the yellow brick road"
 let str = NSString(string: text) 
 let theRange = str.rangeOfString("yellow")
 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: theRange)

java.math.BigInteger cannot be cast to java.lang.Long

Better option is use SQLQuery#addScalar than casting to Long or BigDecimal.

Here is modified query that returns count column as Long

Query query = session
             .createSQLQuery("SELECT COUNT(*) as count
                             FROM SpyPath 
                             WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) 
                             GROUP BY DATE(time) 
                             ORDER BY time;")
             .addScalar("count", LongType.INSTANCE);

Then

List<Long> result = query.list(); //No ClassCastException here  

Related link

How to calculate the median of an array?

Arrays.sort(numArray);
return (numArray[size/2] + numArray[(size-1)/2]) / 2;

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

How to increase the clickable area of a <a> tag button?

Yes you can if you are using HTML5, this code is valid not otherwise:

<a href="#foo"><div>.......</div></a>

If you are not using HTML5, you can make your link block:

<a href="#foo" id="link">Click Here</a>

CSS:

#link {
  display : block;
  width:100px;
  height:40px;
}

Notice that you can apply width, height only after making your link block level element.

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

Check if element is visible in DOM

Use the same code as jQuery does:

jQuery.expr.pseudos.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

So, in a function:

function isVisible(e) {
    return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}

Works like a charm in my Win/IE10, Linux/Firefox.45, Linux/Chrome.52...

Many thanks to jQuery without jQuery!

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

await is only valid in async function

I had the same problem and the following block of code was giving the same error message:

repositories.forEach( repo => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:

repositories.forEach( async(repo) => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

How to call stopservice() method of Service class from the calling activity class

That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.

If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.

AutoService

class AutoService extends IntentService {
     private static final String TAG = "AutoService";
     private Timer timer;    
     private TimerTask task;

     public onCreate() {
          timer = new Timer();
          timer = new TimerTask() {
            public void run() 
            {
                System.out.println("done");
            }
          }
     }

     protected void onHandleIntent(Intent i) {
        Log.d(TAG, "onHandleIntent");     

        int delay = 5000; // delay for 5 sec.
        int period = 5000; // repeat every sec.


        timer.scheduleAtFixedRate(timerTask, delay, period);
     }

     public boolean stopService(Intent name) {
        // TODO Auto-generated method stub
        timer.cancel();
        task.cancel();
        return super.stopService(name);
    }

}

How do you serve a file for download with AngularJS or Javascript?

Try this

<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">

and visit this site it could be helpful for you :)

http://docs.angularjs.org/guide/

Fetch: reject promise and catch the error if status is not OK?

I just checked the status of the response object:

$promise.then( function successCallback(response) {  
  console.log(response);
  if (response.status === 200) { ... }
});

Extract substring from a string

substring():

str.substring(startIndex, endIndex);