Programs & Examples On #Sharepoint timer job

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

Chrome desktop notification example

Notify.js is a wrapper around the new webkit notifications. It works pretty well.

http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/

How to declare and add items to an array in Python?

I believe you are all wrong. you need to do:

array = array[] in order to define it, and then:

array.append ["hello"] to add to it.

Can you break from a Groovy "each" closure?

You could break by RETURN. For example

  def a = [1, 2, 3, 4, 5, 6, 7]
  def ret = 0
  a.each {def n ->
    if (n > 5) {
      ret = n
      return ret
    }
  }

It works for me!

Determine the line of code that causes a segmentation fault?

All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.

If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.

It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)

How to call a method in MainActivity from another class?

Use this code in sub Fragment of MainActivity to call the method on it.

((MainActivity) getActivity()).startChronometer();

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

Access parent URL from iframe

I couldnt get previous solution to work but I found out that if I set the iframe scr with for example http:otherdomain.com/page.htm?from=thisdomain.com/thisfolder then I could, in the iframe extract thisdomain.com/thisfolder by using following javascript:

var myString = document.location.toString();
var mySplitResult = myString.split("=");
fromString = mySplitResult[1];

Angular 5 Button Submit On Enter Key Press

try use keyup.enter or keydown.enter

  <button type="submit" (keyup.enter)="search(...)">Search</button>

java.lang.ClassCastException

According to the documentation:

Thrown to indicate that the code has attempted to cast an Object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

Object x = new Integer(0);
System.out.println((String)x); 

JavaScript for handling Tab Key press

You need to use Regular Expression For Website URL it is

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

Use this Expression as in example

var regex = new RegExp(urlPattern ); var t = 'www.google.com';
var res = t.match(regex /g);

For You have to pass your web page as string to this javascript in variable t and get array

Convert pyQt UI to python

You can use pyuic4 command on shell: pyuic4 input.ui -o output.py

How to put a jpg or png image into a button in HTML

This may work for you, try it and see if it works:

<input type="image" src="/library/graphics/cecb2.gif">

How can I initialize an ArrayList with all zeroes in Java?

The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:

for (int i = 0; i < 60; i++) {
    list.add(0);
}

Vuejs and Vue.set(), update array

One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.

So you this should work as well:

var tempArray[];

tempArray = this.items;

tempArray[targetPosition]  = value;

this.items = tempArray;

This then should also update your DOM.

How to add custom html attributes in JSX

uniqueId is custom attribute.

<a {...{ "uniqueId": `${item.File.UniqueId}` }}  href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>

MVC 4 client side validation not working

In Global.asax.cs, Application_Start() method add:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));

How to compare two maps by their values

If you assume that there can be duplicate values the only way to do this is to put the values in lists, sort them and compare the lists viz:

List<String> values1 = new ArrayList<String>(map1.values());
List<String> values2 = new ArrayList<String>(map2.values());
Collections.sort(values1);
Collections.sort(values2);
boolean mapsHaveEqualValues = values1.equals(values2);

If values cannot contain duplicate values then you can either do the above without the sort using sets.

What is the difference between server side cookie and client side cookie?

You probably mean the difference between Http Only cookies and their counter part?

Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.

Count number of days between two dates

def business_days_between(date1, date2)
  business_days = 0
  date = date2
  while date > date1
   business_days = business_days + 1 unless date.saturday? or date.sunday?
   date = date - 1.day
  end
  business_days
end

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

For me i wanted to implement a 2-way handshake, meaning:
- the parent window will load faster then the iframe
- the iframe should talk to the parent window as soon as its ready
- the parent is ready to receive the iframe message and replay

this code is used to set white label in the iframe using [CSS custom property]
code:
iframe

$(function() {
    window.onload = function() {
        // create listener
        function receiveMessage(e) {
            document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
            document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
            document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
            //alert(e.data.data.header_bg);
        }
        window.addEventListener('message', receiveMessage);
        // call parent
        parent.postMessage("GetWhiteLabel","*");
    }
});

parent

$(function() {
    // create listener
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    eventer(messageEvent, function (e) {
        // replay to child (iframe) 
        document.getElementById('wrapper-iframe').contentWindow.postMessage(
            {
                event_id: 'white_label_message',
                wl: {
                    header_bg: $('#Header').css('background-color'),
                    header_text: $('#Header .HoverMenu a').css('color'),
                    button_bg: $('#Header .HoverMenu a').css('background-color')
                }
            },
            '*'
        );
    }, false);
});

naturally you can limit the origins and the text, this is easy-to-work-with code
i found this examlpe to be helpful:
[Cross-Domain Messaging With postMessage]

Change arrow colors in Bootstraps carousel

I too had a similar problem, some images were very light and some dark, so the arrows didn't always show up clearly so I took a more simplistic approach.

In the modal-body section I just removed the following lines:

    <!-- Left and right controls -->
    <a class="carousel-control-prev" href="#id" data-slide="prev">
       <span class="carousel-control-prev-icon"></span>
    </a>
    <a class="carousel-control-next" href="#id" data-slide="next">
      <span class="carousel-control-next-icon"></span>
    </a>

and inserted the following into the modal-header section

    <!-- Left and right controls -->
    <a  href="#gamespandp" data-slide="prev" class="btn btn-outline-secondary btn-sm">&#10094;</a>
    <a  href="#gamespandp"  data-slide="next" class="btn btn-outline-secondary btn-sm">&#10095;</a>

The indicators can now be clearly seen, no adding extra icons or messing with style sheets, although you could style them however you wanted!

See this demo image:

[demo Image]

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Let us consider a binary tree of height 'h'. A binary tree is called a complete binary tree if all the leaves are present at height 'h' or 'h-1' without any missing numbers in the sequence.

                   1
                 /   \
              2       3
            /    \         
         4        5

It is a complete binary tree.

                   1
                 /   \
              2       3
            /        /    
         4         6    

It is not a complete binary tree as the node of number 5 is missing in the sequence

Node.js Generate html

If you want to create static files, you can use Node.js File System Library to do that. But if you are looking for a way to create dynamic files as a result of your database or similar queries then you will need a template engine like SWIG. Besides these options you can always create HTML files as you would normally do and serve them over Node.js. To do that, you can read data from HTML files with Node.js File System and write it into response. A simple example would be:

var http = require('http');
var fs   = require('fs');

http.createServer(function (req, res) {
  fs.readFile(req.params.filepath, function (err, content) {
    if(!err) {
      res.end(content);
    } else {
      res.end('404');
    }
  }
}).listen(3000);

But I suggest you to look into some frameworks like Express for more useful solutions.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

I find this quite tricky, but there is some information on it here at the MatPlotLib FAQ. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...

Update: The page states that the tight_layout() function is the easiest way to go, which attempts to automatically correct spacing.

Otherwise, it shows ways to acquire the sizes of various elements (eg. labels) so you can then correct the spacings/positions of your axes elements. Here is an example from the above FAQ page, which determines the width of a very wide y-axis label, and adjusts the axis width accordingly:

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
   bboxes = []
   for label in labels:
       bbox = label.get_window_extent()
       # the figure transform goes from relative coords->pixels and we
       # want the inverse of that
       bboxi = bbox.inverse_transformed(fig.transFigure)
       bboxes.append(bboxi)

   # this is the bbox that bounds all the bboxes, again in relative
   # figure coords
   bbox = mtransforms.Bbox.union(bboxes)
   if fig.subplotpars.left < bbox.width:
       # we need to move it over
       fig.subplots_adjust(left=1.1*bbox.width) # pad a little
       fig.canvas.draw()
   return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.show()

Wrapping text inside input type="text" element HTML/CSS

To create a text input in which the value under the hood is a single line string but is presented to the user in a word-wrapped format you can use the contenteditable attribute on a <div> or other element:

_x000D_
_x000D_
const el = document.querySelector('div[contenteditable]');_x000D_
_x000D_
// Get value from element on input events_x000D_
el.addEventListener('input', () => console.log(el.textContent));_x000D_
_x000D_
// Set some value_x000D_
el.textContent = 'Lorem ipsum curae magna venenatis mattis, purus luctus cubilia quisque in et, leo enim aliquam consequat.'
_x000D_
div[contenteditable] {_x000D_
  border: 1px solid black;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div contenteditable></div>
_x000D_
_x000D_
_x000D_

Update a submodule to the latest commit

If you update a submodule and commit to it, you need to go to the containing, or higher level repo and add the change there.

git status

will show something like:

modified:
   some/path/to/your/submodule

The fact that the submodule is out of sync can also be seen with

git submodule

the output will show:

+afafaffa232452362634243523 some/path/to/your/submodule

The plus indicates that the your submodule is pointing ahead of where the top repo expects it to point to.

simply add this change:

git add some/path/to/your/submodule

and commit it:

git commit -m "referenced newer version of my submodule"

When you push up your changes, make sure you push up the change in the submodule first and then push the reference change in the outer repo. This way people that update will always be able to successfully run

git submodule update

More info on submodules can be found here http://progit.org/book/ch6-6.html.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

@Amit's answer is good because it will work in both Mustache and Handlebars.

As far as Handlebars-only solutions, I've seen a few and I like the each_with_key block helper at https://gist.github.com/1371586 the best.

  • It allows you to iterate over object literals without having to restructure them first, and
  • It gives you control over what you call the key variable. With many other solutions you have to be careful about using object keys named 'key', or 'property', etc.

How do I access the $scope variable in browser's console using AngularJS?

For only debugging purposes I put this to the start of the controller.

   window.scope = $scope;

  $scope.today = new Date();

And this is how I use it.

enter image description here

then delete it when I am done debugging.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Android: remove left margin from actionbar's custom layout

If you are adding the Toolbar via XML, you can simply add XML attributes to remove content insets.

<android.support.v7.widget.Toolbar
    xmlns:app="schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primaryColor"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    android:contentInsetRight="0dp"
    android:contentInsetEnd="0dp"
    app:contentInsetRight="0dp"
    app:contentInsetEnd="0dp" />

BACKUP LOG cannot be performed because there is no current database backup

I just deleted the existing DB that i wanted to override with the backup and restored it from backup and it worked without the error.

How to validate phone numbers using regex

Do a replace on formatting characters, then check the remaining for phone validity. In PHP,

 $replace = array( ' ', '-', '/', '(', ')', ',', '.' ); //etc; as needed
 preg_match( '/1?[0-9]{10}((ext|x)[0-9]{1,4})?/i', str_replace( $replace, '', $phone_num );

Breaking a complex regexp like this can be just as effective, but much more simple.

Creating InetAddress object in Java

This is a project for getting IP address of any website , it's usefull and so easy to make.

import java.net.InetAddress;
import java.net.UnkownHostExceptiin;

public class Main{
    public static void main(String[]args){
        try{
            InetAddress addr = InetAddresd.getByName("www.yahoo.com");
            System.out.println(addr.getHostAddress());

          }catch(UnknownHostException e){
             e.printStrackTrace();
        }
    }
}

Cluster analysis in R: determine the optimal number of clusters

Splendid answer from Ben. However I'm surprised that the Affinity Propagation (AP) method has been here suggested just to find the number of cluster for the k-means method, where in general AP do a better job clustering the data. Please see the scientific paper supporting this method in Science here:

Frey, Brendan J., and Delbert Dueck. "Clustering by passing messages between data points." science 315.5814 (2007): 972-976.

So if you are not biased toward k-means I suggest to use AP directly, which will cluster the data without requiring knowing the number of clusters:

library(apcluster)
apclus = apcluster(negDistMat(r=2), data)
show(apclus)

If negative euclidean distances are not appropriate, then you can use another similarity measures provided in the same package. For example, for similarities based on Spearman correlations, this is what you need:

sim = corSimMat(data, method="spearman")
apclus = apcluster(s=sim)

Please note that those functions for similarities in the AP package are just provided for simplicity. In fact, apcluster() function in R will accept any matrix of correlations. The same before with corSimMat() can be done with this:

sim = cor(data, method="spearman")

or

sim = cor(t(data), method="spearman")

depending on what you want to cluster on your matrix (rows or cols).

How to round a numpy array?

Numpy provides two identical methods to do this. Either use

np.round(data, 2)

or

np.around(data, 2)

as they are equivalent.

See the documentation for more information.


Examples:

>>> import numpy as np
>>> a = np.array([0.015, 0.235, 0.112])
>>> np.round(a, 2)
array([0.02, 0.24, 0.11])
>>> np.around(a, 2)
array([0.02, 0.24, 0.11])
>>> np.round(a, 1)
array([0. , 0.2, 0.1])

jQuery: Check if div with certain class name exists

Use this to search whole page

if($('*').hasClass('mydivclass')){
// Do Stuff
}

How to import JsonConvert in C# application?

JsonConvert is from the namespace Newtonsoft.Json, not System.ServiceModel.Web

Use NuGet to download the package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

When & why to use delegates?

Delegates are extremely useful when wanting to declare a block of code that you want to pass around. For example when using a generic retry mechanism.

Pseudo:

function Retry(Delegate func, int numberOfTimes)
    try
    {
       func.Invoke();
    }
    catch { if(numberOfTimes blabla) func.Invoke(); etc. etc. }

Or when you want to do late evaluation of code blocks, like a function where you have some Transform action, and want to have a BeforeTransform and an AfterTransform action that you can evaluate within your Transform function, without having to know whether the BeginTransform is filled, or what it has to transform.

And of course when creating event handlers. You don't want to evaluate the code now, but only when needed, so you register a delegate that can be invoked when the event occurs.

Android ListView selected item stay highlighted

One way you can do this, is to Keep track of the current selected position in your activity:

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
        currentPosition = position
        lv_cli.notifyDataSetChanged();
    }

Now, be sure you assign an ID to the parent layout (linearLayout, boxLayout, relativeLayout, .. Whatever you prefer) of your list item.

Then in your ListView you can do something Like this:

layoutBackground = (LinearLayout) convertView.findViewById(R.id.layout_background);

if (YourActivity.this.currentPosition == position) {
    layoutBackground.setBackgroundColor(YourActivity.this.getResources().getColor(R.color.hilight_color));
} else{
    layoutBackground.setBackgroundResource(R.drawable.list_item_drawable);
}

Basically, you just set the hilight color to the layout as a background when it equals your current selected position. Notice how I set a drawable background resource when the item is not selected. This could be in your case different (since you posted no code). In my case, this drawable is a selector which makes sure the item is hi-lighted when pressed.

NOTE: This simple code doesn't use a view-holder, but I really recommend using one.

Combining CSS Pseudo-elements, ":after" the ":last-child"

An old thread, nonetheless someone may benefit from this:

li:not(:last-child)::after { content: ","; }
li:last-child::after { content: "."; }

This should work in CSS3 and [untested] CSS2.

How to return a class object by reference in C++?

You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:

Object& return_Object()
{
    Object object_to_return;
    // ... do stuff ...

    return object_to_return;
}

If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.

How to close Browser Tab After Submitting a Form?

try onsubmit="submit(); window.close()"

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

Python, how to read bytes from file and save it?

with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

Using LINQ to remove elements from a List<T>

If you really need to remove items then what about Except()?
You can remove based on a new list, or remove on-the-fly by nesting the Linq.

var authorsList = new List<Author>()
{
    new Author{ Firstname = "Bob", Lastname = "Smith" },
    new Author{ Firstname = "Fred", Lastname = "Jones" },
    new Author{ Firstname = "Brian", Lastname = "Brains" },
    new Author{ Firstname = "Billy", Lastname = "TheKid" }
};

var authors = authorsList.Where(a => a.Firstname == "Bob");
authorsList = authorsList.Except(authors).ToList();
authorsList = authorsList.Except(authorsList.Where(a=>a.Firstname=="Billy")).ToList();

Can you do greater than comparison on a date in a Rails 3 search?

Rails 6.1 added a new 'syntax' for comparison operators in where conditions, for example:

Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)

So your query can be rewritten as follows:

Note
  .where(user_id: current_user.id, notetype: p[:note_type], 'date >', p[:date])
  .order(date: :asc, created_at: :asc)

Here is a link to PR where you can find more examples.

Disable/Enable button in Excel/VBA

Others are correct in saying that setting button.enabled = false doesn't prevent the button from triggering. However, I found that setting button.visible = false does work. The button disappears and can't be clicked until you set visible to true again.

Reverse Singly Linked List Java

Using Recursion It's too easy :

package com.config;

import java.util.Scanner;

public class Help {

    public static void main(String args[]){

        Scanner sc = new Scanner(System.in);
        Node head = null;
        Node temp = null;
        int choice = 0;
        boolean flage = true;
        do{
            Node node = new Node();
            System.out.println("Enter Node");
            node.data = sc.nextInt();
            if(flage){
                head = node;
                flage = false;
            }
            if(temp!=null)
                temp.next = node;
            temp = node;

            System.out.println("Enter 0 to exit.");
            choice = sc.nextInt();
        }while(choice!=0);

        Help.getAll(head);

        Node reverse = Help.reverse(head,null);
        //reverse = Help.reverse(head, null);

        Help.getAll(reverse);

    }

    public static void getAll(Node head){
        if(head==null)
            return ;
        System.out.println(head.data+"Memory Add "+head.hashCode());
        getAll(head.next);
    }

    public static Node reverse(Node head,Node tail){
        Node next = head.next;
        head.next = tail;
        return (next!=null? reverse(next,head) : head);
    }
}

class Node{
    int data = 0;
    Node next = null;
}

How to detect if CMD is running as Administrator/has elevated privileges?

the solution:

at >nul
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )

does not work under Windows 10

for all versions of Windows can be do so:

openfiles >nul 2>&1
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )

How can I replace non-printable Unicode characters in Java?

I have used this simple function for this:

private static Pattern pattern = Pattern.compile("[^ -~]");
private static String cleanTheText(String text) {
    Matcher matcher = pattern.matcher(text);
    if ( matcher.find() ) {
        text = text.replace(matcher.group(0), "");
    }
    return text;
}

Hope this is useful.

ERROR: Sonar server 'http://localhost:9000' can not be reached

When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.

jquery background-color change on focus and blur

in code there should be coma"," not colon ":"

the code must be $(this).css({'background-color' , '#FFFFEE'});

i hope it helps.

regards Saleha

Getting the number of filled cells in a column (VBA)

To find the last filled column use the following :

lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

How can I read a large text file line by line using Java?

The clear way to achieve this,

For example:

If you have dataFile.txt on your current directory

import java.io.*;
import java.util.Scanner;
import java.io.FileNotFoundException;

public class readByLine
{
    public readByLine() throws FileNotFoundException
    {
        Scanner linReader = new Scanner(new File("dataFile.txt"));

        while (linReader.hasNext())
        {
            String line = linReader.nextLine();
            System.out.println(line);
        }
        linReader.close();

    }

    public static void main(String args[])  throws FileNotFoundException
    {
        new readByLine();
    }
}

The output like as below, enter image description here

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

ImportError: No module named 'google'

Use this both installation and then go ahead with your python code

pip install google-cloud    
pip install google-cloud-vision

What's the easy way to auto create non existing dir in ansible

To ensure success with a full path use recurse=yes

- name: ensure custom facts directory exists
    file: >
      path=/etc/ansible/facts.d
      recurse=yes
      state=directory

Could not open a connection to your authentication agent

Let me offer another solution. If you have just installed Git 1.8.2.2 or thereabouts, and you want to enable SSH, follow the well-writen directions.

Everything through to Step 5.6 where you might encounter a slight snag. If an SSH agent is already be running you could get the following error message when you restart bash

Could not open a connection to your authentication agent

If you do, use the following command to see if more than one ssh-agent process is running

ps aux | grep ssh

If you see more than one ssh-agent service, you will need to kill all of these processes. Use the kill command as follows (the PID will be unique on your computer)

kill <PID>

Example:

kill 1074

After you have removed all of the ssh-agent processes, run the px aux | grep ssh command again to be sure they are gone, then restart Bash.

Voila, you should now get something like this:

Initializing new SSH agent...
succeeded
Enter passphrase for /c/Users/username/.ssh/id_rsa:

Now you can continue on Step 5.7 and beyond.

show/hide a div on hover and hover out

May be there no need for JS. You can achieve this with css also. Write like this:

.flyout {
    position: absolute;
    width: 1000px;
    height: 450px;
    background: red;
    overflow: hidden;
    z-index: 10000;
    display: none;
}
#menu:hover + .flyout {
    display: block;
}

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

VBA error 1004 - select method of range class failed

Removing the range select before the copy worked for me. Thanks for the posts.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

First, I mostly agree with beberlei on his suggestions. However, you may be designing yourself into a trap. Your domain appears to be considering the title to be the natural key for a track, which is likely the case for 99% of the scenarios you come across. However, what if Battery on Master of the Puppets is a different version (different length, live, acoustic, remix, remastered, etc) than the version on The Metallica Collection.

Depending on how you want to handle (or ignore) that case, you could either go beberlei's suggested route, or just go with your proposed extra logic in Album::getTracklist(). Personally, I think the extra logic is justified to keep your API clean, but both have their merit.

If you do wish to accommodate my use case, you could have Tracks contain a self referencing OneToMany to other Tracks, possibly $similarTracks. In this case, there would be two entities for the track Battery, one for The Metallica Collection and one for Master of the Puppets. Then each similar Track entity would contain a reference to each other. Also, that would get rid of the current AlbumTrackReference class and eliminate your current "issue". I do agree that it is just moving the complexity to a different point, but it is able to handle a usecase it wasn't previously able to.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

Per Noalt's answer is correct. However, if you want the snap-in mentioned in the title (Users and Computers), you'll also have to run these commands at a command-line afterwards, as an Administrator:

dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-SnapIns

Note - I had to run these in order for AD Users and Computers to show up, as they were disabled on my computer after the install. This might not be the case for all users.

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

How to pass argument to Makefile from command line?

Much easier aproach. Consider a task:

provision:
        ansible-playbook -vvvv \
        -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory \
        --private-key=.vagrant/machines/default/virtualbox/private_key \
        --start-at-task="$(AT)" \
        -u vagrant playbook.yml

Now when I want to call it I just run something like:

AT="build assets" make provision

or just:

make provision in this case AT is an empty string

How would you do a "not in" query with LINQ?

You can use a combination of Where and Any for finding not in:

var NotInRecord =list1.Where(p => !list2.Any(p2 => p2.Email  == p.Email));

How can I access each element of a pair in a pair list?

Use tuple unpacking:

>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
...    print a, b
... 
a 1
b 2
c 3

See also: Tuple unpacking in for loops.

clientHeight/clientWidth returning different values on different browsers

What I did to fix my issue with clientHeight is to use the clientHight of the controls firstChild. I use IE 11 to print labels from a database and the clientHeight that worked in IE 8 was returning the height of 0 in IE 11. I found a property in that control that was listed as firstChild and that had a property if clientHeight and actually had the height I was looking for. So if your control is returning a clientSize of 0 take a look at the property of its firstChild. It helped me...

Check if EditText is empty.

Try this out with using If ELSE If conditions. You can validate your editText fields easily.

 if(TextUtils.isEmpty(username)) {
                userNameView.setError("User Name Is Essential");
                return;
         } else  if(TextUtils.isEmpty(phone)) {
                phoneView.setError("Please Enter Your Phone Number");
                return;
            }

Remap values in pandas column with a dict

map can be much faster than replace

If your dictionary has more than a couple of keys, using map can be much faster than replace. There are two versions of this approach, depending on whether your dictionary exhaustively maps all possible values (and also whether you want non-matches to keep their values or be converted to NaNs):

Exhaustive Mapping

In this case, the form is very simple:

df['col1'].map(di)       # note: if the dictionary does not exhaustively map all
                         # entries then non-matched entries are changed to NaNs

Although map most commonly takes a function as its argument, it can alternatively take a dictionary or series: Documentation for Pandas.series.map

Non-Exhaustive Mapping

If you have a non-exhaustive mapping and wish to retain the existing variables for non-matches, you can add fillna:

df['col1'].map(di).fillna(df['col1'])

as in @jpp's answer here: Replace values in a pandas series via dictionary efficiently

Benchmarks

Using the following data with pandas version 0.23.1:

di = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H" }
df = pd.DataFrame({ 'col1': np.random.choice( range(1,9), 100000 ) })

and testing with %timeit, it appears that map is approximately 10x faster than replace.

Note that your speedup with map will vary with your data. The largest speedup appears to be with large dictionaries and exhaustive replaces. See @jpp answer (linked above) for more extensive benchmarks and discussion.

PDF to byte array and vice versa

I have implemented similiar behaviour in my Application too without fail. Below is my version of code and it is functional.

    byte[] getFileInBytes(String filename) {
    File file  = new File(filename);
    int length = (int)file.length();
    byte[] bytes = new byte[length];
    try {
        BufferedInputStream reader = new BufferedInputStream(new 
    FileInputStream(file));
    reader.read(bytes, 0, length);
    System.out.println(reader);
    // setFile(bytes);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return bytes;
    }

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

I can also propose following solution for C++11.

for (auto p = 0U; p < sys.size(); p++) {

}

(C++ is not smart enough for auto p = 0, so I have to put p = 0U....)

Sorting multiple keys with Unix sort

I believe in your case something like

sort -t@ -k1.1,1.4 -k1.5,1.7 ... <inputfile

will work better. @ is the field separator, make sure it is a character that appears nowhere. then your input is considered as consisting of one column.

Edit: apparently clintp already gave a similar answer, sorry. As he points out, the flags 'n' and 'r' can be added to every -k.... option.

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

Run a shell script with an html button

This is really just an expansion of BBB's answer which lead to to get my experiment working.

This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".

This requires 3 files.

  1. The actual HTML Website with a button.
  2. A php script which executes the script
  3. A Script

The File Tree:

root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh

1. The main WebPage:

root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
    <input type="submit" value="Open Script">
</form>

2. The PHP Page that runs the script and redirects back to the main page:

root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>

3. The Script :

root@test:/var/www/html# cat testscript/test.sh

#!/bin/bash

touch /tmp/testfile

ElasticSearch - Return Unique Values

You can use the terms aggregation.

{
"size": 0,
"aggs" : {
    "langs" : {
        "terms" : { "field" : "language",  "size" : 500 }
    }
}}

The size parameter within the aggregation specifies the maximum number of terms to include in the aggregation result. If you need all results, set this to a value that is larger than the number of unique terms in your data.

A search will return something like:

{
"took" : 16,
"timed_out" : false,
"_shards" : {
  "total" : 2,
  "successful" : 2,
  "failed" : 0
},
"hits" : {
"total" : 1000000,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
  "langs" : {
    "buckets" : [ {
      "key" : "10",
      "doc_count" : 244812
    }, {
      "key" : "11",
      "doc_count" : 136794
 
    }, {
      "key" : "12",
      "doc_count" : 32312
       } ]
    }
  }
}

Set min-width in HTML table's <td>

One way should be to add a <div style="min-width:XXXpx"> within the td, and let the <td style="width:100%">

"405 method not allowed" in IIS7.5 for "PUT" method

For Windows server 2012 -> Go to Server manager -> Remove Roles and Features -> Server Roles -> Web Server (IIS) -> Web Server -> Common HTTP Features -> Uncheck WebDAV Publishing and remove it -> Restart server.

How to locate the php.ini file (xampp)

Write the following inside phpini_path.php( or AnyNameAsYouLike.php) and run it in the browser.

<?php phpinfo();?>

Among various other parameters you'll get Loaded Configuration File parameter which value is the path of php.ini on the server.

The location of php.ini depends on server operating system:

Windows (With Xampp Installation):

/xampp/php/php.ini 

macOS, OS X:

/private/etc/php.ini

Linux:

/etc/php.ini
/usr/bin/php5/bin/php.ini
/etc/php/php.ini
/etc/php5/apache2/php.ini

Property 'map' does not exist on type 'Observable<Response>'

In my case it wouldn't enough to include only map and promise:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

I solved this problem by importing several rxjs components as official documentation recommends:

1) Import statements in one app/rxjs-operators.ts file:

// import 'rxjs/Rx'; // adds ALL RxJS statics & operators to Observable

// See node_module/rxjs/Rxjs.js
// Import just the rxjs statics and operators we need for THIS app.

// Statics
import 'rxjs/add/observable/throw';

// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';

2) Import rxjs-operator itself in your service:

// Add the RxJS Observable operators we need in this app.
import './rxjs-operators';

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

Export a list into a CSV or TXT file in R

So essentially you have a list of lists, with mylist being the name of the main list and the first element being $f10010_1 which is printed out (and which contains 4 more lists).

I think the easiest way to do this is to use lapply with the addition of dataframe (assuming that each list inside each element of the main list (like the lists in $f10010_1) has the same length):

lapply(mylist, function(x) write.table( data.frame(x), 'test.csv'  , append= T, sep=',' ))

The above will convert $f10010_1 into a dataframe then do the same with every other element and append one below the other in 'test.csv'

You can also type ?write.table on your console to check what other arguments you need to pass when you write the table to a csv file e.g. whether you need row names or column names etc.

How to make EditText not editable through XML in Android?

If you want to do it in java code just use this line to disable it:

editText.setEnabled(false);

And this to enable it:

editText.setEnabled(true);

Where is nodejs log file?

If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name

That will show you STDOUT and STDERR.

throwing an exception in objective-c/cocoa

I believe you should never use Exceptions to control normal program flow. But exceptions should be thrown whenever some value doesn't match a desired value.

For example if some function accepts a value, and that value is never allowed to be nil, then it's fine to trow an exception rather then trying to do something 'smart'...

Ries

Styling HTML email for Gmail

I agree with everyone who supports classes AND inline styles. You might have learned this by now, but if there is a single mistake in your style sheet, Gmail will disregard it.

You might think that your CSS is perfect, because you've done it so often, why would I have mistakes in my CSS? Run it through the CSS Validator (for example http://www.css-validator.org/) and see what happens. I did that after encountering some Gmail display issues, and to my surprise, several Microsoft Outlook specific style declarations showed up as mistakes.

Which made sense to me, so I removed them from the style sheet and put them into a only for Microsoft code block, like so:

<!--[if mso]>
<style type="text/css">
body, table, td, .mobile-text {
font-family: Arial, sans-serif !important;
}
</style>
<xml>
  <o:OfficeDocumentSettings>
    <o:AllowPNG/>
    <o:PixelsPerInch>96</o:PixelsPerInch>
  </o:OfficeDocumentSettings>
</xml>
<![endif]-->

This is just a simple example, but, who know, it might come in handy some time.

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

Waiting for another flutter command to release the startup lock

In Android Studio, It's Work for me

Stop your app if it still runs on the phone or disconnect the your testing device.

Then try to install the package again.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I faced a similar situation, so i replaced all the external jar files(poi-bin-3.17-20170915) and make sure you add other jar files present in lib and ooxml-lib folders.

Hope this helps!!!:)

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

Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
But they serve different purposes.

will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

 git checkout stable

      X                   stable
     /                   
a---b---c---d---e---f---g tmp

to:

git merge --squash tmp
git commit -m "squash tmp"

      X-------------------G stable
     /                   
a---b---c---d---e---f---g tmp

and then deleting tmp branch.


Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
(Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

merge: refuse --commit with --squash

Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

git/git builtin/merge.c#cmd_merge() now includes:

if (option_commit > 0)
    die(_("You cannot combine --squash with --commit."));

replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

git checkout tmp
git rebase -i stable

      stable
      X-------------------G tmp
     /                     
a---b

If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

So the differences are:

  • squash does not touch your source branch (tmp here) and creates a single commit where you want.
  • rebase allows you to go on on the same source branch (still tmp) with:
    • a new base
    • a cleaner history

Groovy built-in REST/HTTP client?

You can take advantage of Groovy features like with(), improvements to URLConnection, and simplified getters/setters:

GET:

String getResult = new URL('http://mytestsite/bloop').text

POST:

String postResult
((HttpURLConnection)new URL('http://mytestsite/bloop').openConnection()).with({
    requestMethod = 'POST'
    doOutput = true
    setRequestProperty('Content-Type', '...') // Set your content type.
    outputStream.withPrintWriter({printWriter ->
        printWriter.write('...') // Your post data. Could also use withWriter() if you don't want to write a String.
    })
    // Can check 'responseCode' here if you like.
    postResult = inputStream.text // Using 'inputStream.text' because 'content' will throw an exception when empty.
})

Note, the POST will start when you try to read a value from the HttpURLConnection, such as responseCode, inputStream.text, or getHeaderField('...').

res.sendFile absolute path

If you want to set this up once and use it everywhere, just configure your own middleware. When you are setting up your app, use the following to define a new function on the response object:

app.use((req, res, next) => {
  res.show = (name) => {
    res.sendFile(`/public/${name}`, {root: __dirname});
  };
  next();
});

Then use it as follows:

app.get('/demo', (req, res) => {
  res.show("index1.html");
});

How to apply a CSS class on hover to dynamically generated submit buttons?

You have two options:

  1. Extend your .paging class definition:

    .paging:hover {
        border:1px solid #999;
        color:#000;
    }
    
  2. Use the DOM hierarchy to apply the CSS style:

    div.paginate input:hover {
        border:1px solid #999;
        color:#000;
    }
    

100% width Twitter Bootstrap 3 template

You're right using div.container-fluid and you also need a div.row child. Then, the content must be placed inside without any grid columns. If you have a look at the docs you can find this text:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
  • Use rows to create horizontal groups of columns.

Not using grid columns it's ok as stated here:

  • Content should be placed within columns, and only columns may be immediate children of rows.

And looking at this example, you can read this text:

Full width, single column: No grid classes are necessary for full-width elements.

Here's a live example showing some elements using the correct layout. This way you don't need any custom CSS or hack.

How to add parameters to an external data query in Excel which can't be displayed graphically?

Easy Workaround (no VBA required)

  1. Right Click Table, expand "Table" context manu, select "External Data Properties"
  2. Click button "Connection Properties" (labelled in tooltip only)
  3. Go-to Tab "Definition"

From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.

Using os.walk() to recursively traverse directories in Python

You can use os.walk, and that is probably the easiest solution, but here is another idea to explore:

import sys, os

FILES = False

def main():
    if len(sys.argv) > 2 and sys.argv[2].upper() == '/F':
        global FILES; FILES = True
    try:
        tree(sys.argv[1])
    except:
        print('Usage: {} <directory>'.format(os.path.basename(sys.argv[0])))

def tree(path):
    path = os.path.abspath(path)
    dirs, files = listdir(path)[:2]
    print(path)
    walk(path, dirs, files)
    if not dirs:
        print('No subfolders exist')

def walk(root, dirs, files, prefix=''):
    if FILES and files:
        file_prefix = prefix + ('|' if dirs else ' ') + '   '
        for name in files:
            print(file_prefix + name)
        print(file_prefix)
    dir_prefix, walk_prefix = prefix + '+---', prefix + '|   '
    for pos, neg, name in enumerate2(dirs):
        if neg == -1:
            dir_prefix, walk_prefix = prefix + '\\---', prefix + '    '
        print(dir_prefix + name)
        path = os.path.join(root, name)
        try:
            dirs, files = listdir(path)[:2]
        except:
            pass
        else:
            walk(path, dirs, files, walk_prefix)

def listdir(path):
    dirs, files, links = [], [], []
    for name in os.listdir(path):
        path_name = os.path.join(path, name)
        if os.path.isdir(path_name):
            dirs.append(name)
        elif os.path.isfile(path_name):
            files.append(name)
        elif os.path.islink(path_name):
            links.append(name)
    return dirs, files, links

def enumerate2(sequence):
    length = len(sequence)
    for count, value in enumerate(sequence):
        yield count, count - length, value

if __name__ == '__main__':
    main()

You might recognize the following documentation from the TREE command in the Windows terminal:

Graphically displays the folder structure of a drive or path.

TREE [drive:][path] [/F] [/A]

   /F   Display the names of the files in each folder.
   /A   Use ASCII instead of extended characters.

How can I make a JPA OneToOne relation lazy

To get lazy loading working on nullable one-to-one mappings you need to let hibernate do compile time instrumentation and add a @LazyToOne(value = LazyToOneOption.NO_PROXY) to the one-to-one relation.

Example Mapping:

@OneToOne(fetch = FetchType.LAZY)  
@JoinColumn(name="other_entity_fk")
@LazyToOne(value = LazyToOneOption.NO_PROXY)
public OtherEntity getOther()

Example Ant Build file extension (for doing the Hibernate compile time instrumentation):

<property name="src" value="/your/src/directory"/><!-- path of the source files --> 
<property name="libs" value="/your/libs/directory"/><!-- path of your libraries --> 
<property name="destination" value="/your/build/directory"/><!-- path of your build directory --> 

<fileset id="applibs" dir="${libs}"> 
  <include name="hibernate3.jar" /> 
  <!-- include any other libraries you'll need here --> 
</fileset> 

<target name="compile"> 
  <javac srcdir="${src}" destdir="${destination}" debug="yes"> 
    <classpath> 
      <fileset refid="applibs"/> 
    </classpath> 
  </javac> 
</target> 

<target name="instrument" depends="compile"> 
  <taskdef name="instrument" classname="org.hibernate.tool.instrument.javassist.InstrumentTask"> 
    <classpath> 
      <fileset refid="applibs"/> 
    </classpath> 
  </taskdef> 

  <instrument verbose="true"> 
    <fileset dir="${destination}"> 
      <!-- substitute the package where you keep your domain objs --> 
      <include name="/com/mycompany/domainobjects/*.class"/> 
    </fileset> 
  </instrument> 
</target>

How to add element in List while iterating in java?

Iterate through a copy of the list and add new elements to the original list.

for (String s : new ArrayList<String>(list))     
{
    list.add("u");
}

See How to make a copy of ArrayList object which is type of List?

How do you properly use namespaces in C++?

Namespaces are packages essentially. They can be used like this:

namespace MyNamespace
{
  class MyClass
  {
  };
}

Then in code:

MyNamespace::MyClass* pClass = new MyNamespace::MyClass();

Or, if you want to always use a specific namespace, you can do this:

using namespace MyNamespace;

MyClass* pClass = new MyClass();

Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).

And as you asked below, you can use as many namespaces as you like.

Storyboard doesn't contain a view controller with identifier

For those with the same issue as @Ravi Bhanushali, here is a Swift 4 solution:

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

Slidedown and slideup layout with animation

I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.

Refer to the link for more details: https://github.com/mancj/SlideUp-Android

To set up the library(copied from the ReadMe portion of its Github page on request):

Get SlideUp library

Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" } // or google() in AS 3.0
  }
}

Add the dependency (in the Module gradle)

dependencies {
    compile 'com.github.mancj:SlideUp-Android:2.2.1'
    compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
    compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}

To add the SlideUp into your project, follow these three simple steps:

Step 1:

create any type of layout

<LinearLayout
  android:id="@+id/slideView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

Step 2:

Find that view in your activity/fragment

View slideView = findViewById(R.id.slideView);

Step 3:

Create a SlideUp object and pass in your view

slideUp = new SlideUpBuilder(slideView)
                .withStartState(SlideUp.State.HIDDEN)
                .withStartGravity(Gravity.BOTTOM)

                //.withSlideFromOtherView(anotherView)
                //.withGesturesEnabled()
                //.withHideSoftInputWhenDisplayed()
                //.withInterpolator()
                //.withAutoSlideDuration()
                //.withLoggingEnabled()
                //.withTouchableAreaPx()
                //.withTouchableAreaDp()
                //.withListeners()
                //.withSavedState()
                .build();

You may also refer to the sample project on the link. I found it quite useful.

Check if value exists in enum in TypeScript

There is a very simple and easy solution to your question:

var districtId = 210;

if (DistrictsEnum[districtId] != null) {

// Returns 'undefined' if the districtId not exists in the DistrictsEnum 
    model.handlingDistrictId = districtId;
}

What exactly is nullptr?

It is a keyword because the standard will specify it as such. ;-) According to the latest public draft (n2914)

2.14.7 Pointer literals [lex.nullptr]

pointer-literal:
nullptr

The pointer literal is the keyword nullptr. It is an rvalue of type std::nullptr_t.

It's useful because it does not implicitly convert to an integral value.

Java better way to delete file if exists

I was working on this type of function, maybe this will interests some of you ...

public boolean deleteFile(File file) throws IOException {
    if (file != null) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();

            for (File f: files) {
                deleteFile(f);
            }
        }
        return Files.deleteIfExists(file.toPath());
    }
    return false;
}

The Use of Multiple JFrames: Good or Bad Practice?

I'm just wondering whether it is good practice to use multiple JFrames?

Bad (bad, bad) practice.

  • User unfriendly: The user sees multiple icons in their task bar when expecting to see only one. Plus the side effects of the coding problems..
  • A nightmare to code and maintain:
    • A modal dialog offers the easy opportunity to focus attention on the content of that dialog - choose/fix/cancel this, then proceed. Multiple frames do not.
    • A dialog (or floating tool-bar) with a parent will come to front when the parent is clicked on - you'd have to implement that in frames if that was the desired behavior.

There are any number of ways of displaying many elements in one GUI, e.g.:

  • CardLayout (short demo.). Good for:
    1. Showing wizard like dialogs.
    2. Displaying list, tree etc. selections for items that have an associated component.
    3. Flipping between no component and visible component.
  • JInternalFrame/JDesktopPane typically used for an MDI.
  • JTabbedPane for groups of components.
  • JSplitPane A way to display two components of which the importance between one or the other (the size) varies according to what the user is doing.
  • JLayeredPane far many well ..layered components.
  • JToolBar typically contains groups of actions or controls. Can be dragged around the GUI, or off it entirely according to user need. As mentioned above, will minimize/restore according to the parent doing so.
  • As items in a JList (simple example below).
  • As nodes in a JTree.
  • Nested layouts.

But if those strategies do not work for a particular use-case, try the following. Establish a single main JFrame, then have JDialog or JOptionPane instances appear for the rest of the free-floating elements, using the frame as the parent for the dialogs.

Many images

In this case where the multiple elements are images, it would be better to use either of the following instead:

  1. A single JLabel (centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer.
  2. A single row JList. As seen in this answer. The 'single row' part of that only works if they are all the same dimensions. Alternately, if you are prepared to scale the images on the fly, and they are all the same aspect ratio (e.g. 4:3 or 16:9).

How to store directory files listing into an array?

This might work for you:

OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"

What is the best way to implement constants in Java?

One of the way I do it is by creating a 'Global' class with the constant values and do a static import in the classes that need access to the constant.

How does the compilation/linking process work?

The compilation of a C++ program involves three steps:

  1. Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.

  2. Compilation: the compiler takes the pre-processor's output and produces an object file from it.

  3. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.

Preprocessing

The preprocessor handles the preprocessor directives, like #include and #define. It is agnostic of the syntax of C++, which is why it must be used with care.

It works on one C++ source file at a time by replacing #include directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define), and selecting different portions of text depending of #if, #ifdef and #ifndef directives.

The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as replacing tokens with other tokens (the operator ## enables merging two tokens when it makes sense).

After all this, the preprocessor produces a single output that is a stream of tokens resulting from the transformations described above. It also adds some special markers that tell the compiler where each line came from so that it can use those to produce sensible error messages.

Some errors can be produced at this stage with clever use of the #if and #error directives.

Compilation

The compilation step is performed on each output of the preprocessor. The compiler parses the pure C++ source code (now without any preprocessor directives) and converts it into assembly code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.

Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily produce the object file as long as the source code is well-formed.

Compilers usually let you stop compilation at this point. This is very useful because with it you can compile each source code file separately. The advantage this provides is that you don't need to recompile everything if you only change a single file.

The produced object files can be put in special archives called static libraries, for easier reusing later on.

It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution errors, are reported.

Linking

The linker is what produces the final compilation output from the object files the compiler produced. This output can be either a shared (or dynamic) library (and while the name is similar, they haven't got much in common with static libraries mentioned earlier) or an executable.

It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.

At this stage the most common errors are missing definitions or duplicate definitions. The former means that either the definitions don't exist (i.e. they are not written), or that the object files or libraries where they reside were not given to the linker. The latter is obvious: the same symbol was defined in two different object files or libraries.

open a url on click of ok button in android

    Button imageLogo = (Button)findViewById(R.id.iv_logo);
    imageLogo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String url = "http://www.gobloggerslive.com";

            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }
    });

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

initializing a Guava ImmutableMap

Notice that your error message only contains five K, V pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of() methods, accepting between zero and five key-value pairings. There is not an of(...) overload accepting a varags parameter because K and V can be different types.

You want an ImmutableMap.Builder:

ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
    .put("key1", "value1") 
    .put("key2", "value2") 
    .put("key3", "value3") 
    .put("key4", "value4") 
    .put("key5", "value5") 
    .put("key6", "value6") 
    .put("key7", "value7") 
    .put("key8", "value8") 
    .put("key9", "value9")
    .build();

Fixed digits after decimal with f-strings

a = 10.1234

print(f"{a:0.2f}")

in 0.2f:

  • 0 is telling python to put no limit on the total number of digits to display
  • .2 is saying that we want to take only 2 digits after decimal (the result will be same as a round() function)
  • f is telling that it's a float number. If you forget f then it will just print 1 less digit after the decimal. In this case, it will be only 1 digit after the decimal.

A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606

How to see the changes between two commits without commits in-between?

To compare two git commits 12345 and abcdef as patches one can use the diff command as

diff <(git show 123456) <(git show abcdef)

How to create a css rule for all elements except one class?

The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.

Regular Expression to select everything before and up to a particular text

After executing the below regex, your answer is in the first capture.

/^(.*?)\.txt/

Is it possible to have SSL certificate for IP address, not domain name?

The C/A Browser forum sets what is and is not valid in a certificate, and what CA's should reject.

According to their Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates document, CAs must, since 2015, not issue certificats where the common name, or common alternate names fields contains a reserved IP or internal name, where reserved IP addresses are IPs that IANA has listed as reserved - which includes all NAT IPs - and internal names are any names that don't resolve on the public DNS.

Public IP addresses CAN be used (and the baseline requirements doc specifies what kinds of checks a CA must perform to ensure the applicant owns the IP).

How to get client IP address using jQuery

jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON method, for example:

_x000D_
_x000D_
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
    console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

This example is of a really simple JSONP service implemented on with api.ipify.org.

If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.

Inversion of Control vs Dependency Injection

As for this question, I'd say the wiki has already provided detailed and easy-understanding explanations. I will just quote the most significant here.

Implementation of IoC

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:

  1. Using a service locator pattern Using dependency injection, for example Constructor injection Parameter injection Setter injection Interface injection;
  2. Using a contextualized lookup;
  3. Using template method design pattern;
  4. Using strategy design pattern

As for Dependency Injection

dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

DropdownList DataSource

It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.

Soft hyphen in HTML (<wbr> vs. &shy;)

This is a crossbrowser solution that I was looking at a little while ago that runs on the client and using jQuery:

(function($) { 
  $.fn.breakWords = function() { 
    this.each(function() { 
      if(this.nodeType !== 1) { return; } 

      if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') { 
        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 
        this.runtimeStyle.wordBreak = 'break-all'; 
      } 
      else if(document.createTreeWalker) { 

        //Faster Trim in Javascript, Flagrant Badassery 
        //http://blog.stevenlevithan.com/archives/faster-trim-javascript 

        var trim = function(str) { 
          str = str.replace(/^\s\s*/, ''); 
          var ws = /\s/, 
          i = str.length; 
          while (ws.test(str.charAt(--i))); 
          return str.slice(0, i + 1); 
        }; 

        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 

        //For Opera, Safari, and Firefox 
        var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false); 
        var node,s,c = String.fromCharCode('8203'); 
        while (dWalker.nextNode()) { 
          node = dWalker.currentNode; 
          //we need to trim String otherwise Firefox will display 
          //incorect text-indent with space characters 
          s = trim( node.nodeValue ).split('').join(c); 
          node.nodeValue = s; 
        } 
      } 
    }); 

    return this; 
  }; 
})(jQuery); 

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Multiple bluetooth connection

Have you looked into the BluetoothAdapter Android class? You set up one device as a server and the other as a client. It may be possible (although I haven't looked into it myself) to connect multiple clients to the server.

I have had success connecting a BlueTooth audio device to a phone while it also had this BluetoothAdapter connection to another phone, but I haven't tried with three phones. At least this tells me that the Bluetooth radio can tolerate multiple simultaneous connections :)

Interface or an Abstract Class: which one to use?

Best practice is to use an interface to specify the contract and an abstract class as just one implementation thereof. That abstract class can fill in a lot of the boilerplate so you can create an implementation by just overriding what you need to or want to without forcing you to use a particular implementation.

Html5 Full screen video

No, there is no way to do this yet. I wish they add a future like this in browsers.

EDIT:

Now there is a Full Screen API for the web You can requestFullscreen on an Video or Canvas element to ask user to give you permisions and make it full screen.

Let's consider this element:

<video controls id="myvideo">
  <source src="somevideo.webm"></source>
  <source src="somevideo.mp4"></source>
</video>

We can put that video into fullscreen mode with script like this:

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { 
  elem.msRequestFullscreen();
}

Full documentation

How to uncheck checkbox using jQuery Uniform library

The other way to do is is,

use $('#check2').click();

this causes uniform to check the checkbox and update it's masks

How to detect scroll direction

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});

Demo: http://jsfiddle.net/AlienWebguy/Bka6F/

How the single threaded non blocking IO model works in Node.js

if you read a bit further - "Of course, on the backend, there are threads and processes for DB access and process execution. However, these are not explicitly exposed to your code, so you can’t worry about them other than by knowing that I/O interactions e.g. with the database, or with other processes will be asynchronous from the perspective of each request since the results from those threads are returned via the event loop to your code."

about - "everything runs in parallel except your code" - your code is executed synchronously, whenever you invoke an asynchronous operation such as waiting for IO, the event loop handles everything and invokes the callback. it just not something you have to think about.

in your example: there are two requests A (comes first) and B. you execute request A, your code continue to run synchronously and execute request B. the event loop handles request A, when it finishes it invokes the callback of request A with the result, same goes to request B.

Convert an integer to an array of digits

Use:

int count = 0;
String newString = n + "";
char [] stringArray = newString.toCharArray();
int [] intArray = new int[stringArray.length];
for (char i : stringArray) {
  int m = Character.getNumericValue(i);
  intArray[count] = m;
  count += 1;
}
return intArray;

You'll have to put this into a method.

What does "yield break;" do in C#?

The yield keyword is used together with the return keyword to provide a value to the enumerator object. yield return specifies the value, or values, returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.

To explain the meaning using an example:

    public IEnumerable<int> SampleNumbers()
    {
        int counter = 0;
        yield return counter;

        counter = counter + 2;

        yield return counter;

        counter = counter + 3;

        yield return counter ;
    }

Values returned when this is iterated are: 0, 2, 5.

It’s important to note that counter variable in this example is a local variable. After the second iteration which returns the value of 2, third iteration starts from where it left before, while preserving the previous value of local variable named counter which was 2.

Link to reload current page

<a href="/">Clicking me refreshes the page</a>

<a href="?">Click Me To Reload the page</a>

NodeJs : TypeError: require(...) is not a function

I think this means that module.exports in your ./app/routes module is not assigned to be a function so therefore require('./app/routes') does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport).

Show us ./app/routes if you want us to comment further on that.

It should look something like this;

module.exports = function(app, passport) {
    // code here
}

You are exporting a function that can then be called like require('./app/routes')(app, passport).


One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B) and module B is trying to require(A). When this happens, it will be detected by the require() sub-system and one of them will come back as null and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.

Different ways of clearing lists

There are two cases in which you might want to clear a list:

  1. You want to use the name old_list further in your code;
  2. You want the old list to be garbage collected as soon as possible to free some memory;

In case 1 you just go on with the assigment:

    old_list = []    # or whatever you want it to be equal to

In case 2 the del statement would reduce the reference count to the list object the name old list points at. If the list object is only pointed by the name old_list at, the reference count would be 0, and the object would be freed for garbage collection.

    del old_list

How do I find duplicates across multiple columns?

A little late to the game on this post, but I found this way to be pretty flexible / efficient

select 
    s1.id
    ,s1.name
    ,s1.city 
from 
    stuff s1
    ,stuff s2
Where
    s1.id <> s2.id
    and s1.name = s2.name
    and s1.city = s2.city

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

You can define the _CRT_SECURE_NO_WARNINGS symbol to suppress them and undefine it to reinstate them back.

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

Trigger a button click with JavaScript on the Enter key in a text box

This is a solution for all the YUI lovers out there:

Y.on('keydown', function() {
  if(event.keyCode == 13){
    Y.one("#id_of_button").simulate("click");
  }
}, '#id_of_textbox');

In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...

Why use double indirection? or Why use pointers to pointers?

Compare modifying value of variable versus modifying value of pointer:

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

void changeA(int (*a))
{
  (*a) = 10;
}

void changeP(int *(*P))
{
  (*P) = malloc(sizeof((*P)));
}

int main(void)
{
  int A = 0;

  printf("orig. A = %d\n", A);
  changeA(&A);
  printf("modi. A = %d\n", A);

  /*************************/

  int *P = NULL;

  printf("orig. P = %p\n", P);
  changeP(&P);
  printf("modi. P = %p\n", P);

  free(P);

  return EXIT_SUCCESS;
}

This helped me to avoid returning value of pointer when the pointer was modified by the called function (used in singly linked list).

OLD (bad):

int *func(int *P)
{
  ...
  return P;
}

int main(void)
{
  int *pointer;
  pointer = func(pointer);
  ...
}    

NEW (better):

void func(int **pointer)
{
  ...
}

int main(void)
{
  int *pointer;
  func(&pointer);
  ...
}    

How to find the type of an object in Go?

The Go reflection package has methods for inspecting the type of variables.

The following snippet will print out the reflection type of a string, integer and float.

package main

import (
    "fmt"
    "reflect"
)

func main() {

    tst := "string"
    tst2 := 10
    tst3 := 1.2

    fmt.Println(reflect.TypeOf(tst))
    fmt.Println(reflect.TypeOf(tst2))
    fmt.Println(reflect.TypeOf(tst3))

}

Output:

Hello, playground
string
int
float64

see: http://play.golang.org/p/XQMcUVsOja to view it in action.

More documentation here: http://golang.org/pkg/reflect/#Type

Android Studio - How to increase Allocated Heap Size

-------EDIT--------

Android Studio 2.0 and above, you can create/edit this file by accessing "Edit Custom VM Options" from the Help menu.

-------ORIGINAL ANSWER--------

Open file located at

/Applications/Android\ Studio.app/Contents/bin/studio.vmoptions

Change the content to

-Xms128m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=200m
-XX:+UseCompressedOops

Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool. Your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory.

Save the studio.vmoptions file and restart Android Studio.

Note:

If you changed the heap size for the IDE, you must restart Android Studio before the new memory settings are applied. (source)

How can query string parameters be forwarded through a proxy_pass with nginx?

To redirect Without Query String add below lines in Server block under listen port line:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/;
}

With Query String:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/?$query_string;
}

How to give the background-image path in CSS?

There are two basic ways:

url(../../images/image.png)

or

url(/Web/images/image.png)

I prefer the latter, as it's easier to work with and works from all locations in the site (so useful for inline image paths too).

Mind you, I wouldn't do so much deep nesting of folders. It seems unnecessary and makes life a bit difficult, as you've found.

Curl GET request with json parameter

If you really want to submit the GET request with JSON in the body (say for an XHR request and you know the server supports processing the body on GET requests), you can:

curl -X GET \
  -H "Content-type: application/json" \
  -H "Accept: application/json" \
  -d '{"param0":"pradeep"}' \
  "http://server:5050/a/c/getName"

Most modern web servers accept this type of request.

Getting value from a cell from a gridview on RowDataBound event

The above are good suggestions, but you can get at the text value of a cell in a grid view without wrapping it in a literal or label control. You just have to know what event to wire up. In this case, use the DataBound event instead, like so:

protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[0].Text.Contains("sometext"))
        {
            e.Row.Cells[0].Font.Bold = true;
        }
    }
}

When running a debugger, you will see the text appear in this method.

Get checkbox list values with jQuery

$(document).ready(function() {
    $('#someButton').click(function() {
        var names = [];
        $('#MyDiv input:checked').each(function() {
            names.push(this.name);
        });
        // now names contains all of the names of checked checkboxes
        // do something with it
    });
});

Select From all tables - MySQL

As Suhel Meman said in the comments:

SELECT column1, column2, column3 FROM table 1
UNION
SELECT column1, column2, column3 FROM table 2
...

would work.

But all your SELECTS would have to consist of the same amount of columns. And because you are displaying it in one resulting table they should contain the same information.

What you might want to do, is a JOIN on Product ID or something like that. This way you would get more columns, which makes more sense most of the time.

How to detect if a browser is Chrome using jQuery?

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

PHP: How to send HTTP response code?

I just found this question and thought it needs a more comprehensive answer:

As of PHP 5.4 there are three methods to accomplish this:

Assembling the response code on your own (PHP >= 4.0)

The header() function has a special use-case that detects a HTTP response line and lets you replace that with a custom one

header("HTTP/1.1 200 OK");

However, this requires special treatment for (Fast)CGI PHP:

$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi')
    header("Status: 404 Not Found");
else
    header("HTTP/1.1 404 Not Found");

Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.

Note: php_sapi_name() requires PHP 4.0.1

3rd argument to header function (PHP >= 4.3)

There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.

Since 4.3, the header function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:

header(':', true, 404);
header('X-PHP-Response-Code: 404', true, 404);

I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.

http_response_code function (PHP >= 5.4)

The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.

http_response_code(404);

That's all.

Compatibility

Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the "new" http_response_code function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know...

// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
    function http_response_code($newcode = NULL)
    {
        static $code = 200;
        if($newcode !== NULL)
        {
            header('X-PHP-Response-Code: '.$newcode, true, $newcode);
            if(!headers_sent())
                $code = $newcode;
        }       
        return $code;
    }
}

Rails how to run rake task

In rails 4.2 the above methods didn't work.

  1. Go to the Terminal.
  2. Change the directory to the location where your rake file is present.
  3. run rake task_name.
  4. In the above case, run rake iqmedier - will run only iqmedir task.
  5. run rake euroads - will run only the euroads task.
  6. To Run all the tasks in that file assign the following inside the same file and run rake all

    task :all => [:iqmedier, :euroads, :mikkelsen, :orville ] do #This will print all the tasks o/p on the screen 
    end
    

clear form values after submission ajax

it works: call this function after ajax success and send your form id as it's paramete. something like this:

This function clear all input fields value including button, submit, reset, hidden fields

function resetForm(formid) {
 $('#' + formid + ' :input').each(function(){  
  $(this).val('').attr('checked',false).attr('selected',false);
 });
}

* This function clears all input fields value except button, submit, reset, hidden fields * */

 function resetForm(formid) {
   $(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
  .removeAttr('checked') .removeAttr('selected');
  }

example:

<script>
   (function($){
       function processForm( e ){
           $.ajax({
               url: 'insert.php',
               dataType: 'text',
               type: 'post',
               contentType: 'application/x-www-form-urlencoded',
               data: $(this).serialize(),
               success: function( data, textStatus, jQxhr ){
                $('#alertt').fadeIn(2000);
                $('#alertt').html( data );
                $('#alertt').fadeOut(3000);
               resetForm('userInf');
            },
            error: function( jqXhr, textStatus, errorThrown ){
                console.log( errorThrown );
            }
        });

        e.preventDefault();
    }

    $('#userInf').submit( processForm );
})(jQuery);

 function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
  .removeAttr('checked') .removeAttr('selected');
 }
  </script>

jQuery UI DatePicker to show month year only

@Ben Koehler, that's prefect! I made a minor modification so that using a single instance of the date picker more than once works as expected. Without this modification the date is parsed incorrectly and the previously selected date is not highlighted.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
    <script type="text/javascript">
    $(function() {
        $('.date-picker').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) { 
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, month, 1));
            },
            beforeShow : function(input, inst) {
                var datestr;
                if ((datestr = $(this).val()).length > 0) {
                    year = datestr.substring(datestr.length-4, datestr.length);
                    month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNamesShort'));
                    $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
                    $(this).datepicker('setDate', new Date(year, month, 1));
                }
            }
        });
    });
    </script>
    <style>
    .ui-datepicker-calendar {
        display: none;
        }
    </style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

FileProvider - IllegalArgumentException: Failed to find configured root

Hello Friends Try This

In this Code

1) How to Declare 2 File Provider in Manifest.

2) First Provider for file Download

3) second Provider used for camera and gallary

STEP 1

     <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

Provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="apks" path="." />
</paths>

Second Provider

     <provider
        android:name=".Utils.MyFileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true"
        tools:replace="android:authorities"
        tools:ignore="InnerclassSeparator">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_path" />
    </provider>

file_path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="storage/emulated/0" path="."/>
</paths>

.Utils.MyFileProvider

Create Class MyFileProvider (only Create class no any method declare)

When you used File Provider used (.fileprovider) this name and you used for image (.provider) used this.

IF any one Problem to understand this code You can Contact on [email protected] i will help you.

How to write inline if statement for print?

Well why don't you simply write:

if b:
    print a
else:
    print 'b is false'

No connection could be made because the target machine actively refused it (PHP / WAMP)

  1. Go to C:\wamp\bin\mysql\mysql[your-version]\data
  2. Copy and save "ib_logfile0" and "ib_logfile1" anywhere else.
  3. delete "ib_logfile0" and ib_logfile1

Did the trick for me. hope it works for you too.

Its working fine. But we will have to stop apache and mysql, We need to quit xampp and then delete file. when deleted successfully. now start xampp it will work properly..

Find integer index of rows with NaN in pandas dataframe

Let the dataframe be named df and the column of interest(i.e. the column in which we are trying to find nulls) is 'b'. Then the following snippet gives the desired index of null in the dataframe:

   for i in range(df.shape[0]):
       if df['b'].isnull().iloc[i]:
           print(i)

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

It seems like your Maven is unable to connect to Maven repository at http://repo1.maven.org/maven2.

If you are using proxy and can access the link with browser the same settings need to be applied to Spring Source Tool Suite (if you are running within suite) or Maven.

For Maven proxy setting create a settings.xml in the .m2 directory with following details

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <proxies>
    <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>PROXY</host>
      <port>3120</port>
      <nonProxyHosts>maven</nonProxyHosts>
    </proxy>
  </proxies>
</settings>

If you are not using proxy and can access the link with browser, remove any proxy settings described above.

How to sort with a lambda?

To much code, you can use it like this:

#include<array>
#include<functional>

int main()
{
    std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };

    std::sort(std::begin(vec), 
              std::end(vec), 
              [](int a, int b) {return a > b; });

    for (auto item : vec)
      std::cout << item << " ";

    return 0;
}

Replace "vec" with your class and that's it.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

i think this is the better query for stamp_created and stamp_updated

CREATE TABLE test_table( 
    id integer not null auto_increment primary key, 
    stamp_created TIMESTAMP DEFAULT now(), 
    stamp_updated TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE now() 
); 

because when the record created, stamp_created should be filled by now() and stamp_updated should be filled by '0000-00-00 00:00:00'

How to check if another instance of my shell script is running

I didn't want to hardcode abc.sh in the check, so I used the following:

MY_SCRIPT_NAME=`basename "$0"`
if pidof -o %PPID -x $MY_SCRIPT_NAME > /dev/null; then
    echo "$MY_SCRIPT_NAME already running; exiting"
    exit 1
fi

How do you handle multiple submit buttons in ASP.NET MVC Framework?

I've came across this 'problem' as well but found a rather logical solution by adding the name attribute. I couldn't recall having this problem in other languages.

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2

  • ...
  • If a form contains more than one submit button, only the activated submit button is successful.
  • ...

Meaning the following code value attributes can be changed, localized, internationalized without the need for extra code checking strongly-typed resources files or constants.

<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="send" value="Send" />
<input type="submit" name="cancel" value="Cancel" />
<input type="submit" name="draft" value="Save as draft" />
<% Html.EndForm(); %>`

On the receiving end you would only need to check if any of your known submit types isn't null

public ActionResult YourAction(YourModel model) {

    if(Request["send"] != null) {

        // we got a send

    }else if(Request["cancel"]) {

        // we got a cancel, but would you really want to post data for this?

    }else if(Request["draft"]) {

        // we got a draft

    }

}

How to import an existing project from GitHub into Android Studio

Steps:

  1. Download the Zip from the website or clone from Github Desktop. Don't use VCS in android studio.
  2. (Optional)Copy the folder extracted into your AndroidStudioProjects folder which must contain the hidden .git folder.
  3. Open Android Studio-> File-> Open-> Select android directory.
  4. If it's a Eclipse project then convert it to gradle(Provided by Android Studio). Otherwise, it's done.

Javascript: console.log to html

This post has helped me a lot, and after a few iterations, this is what we use.

The idea is to post log messages and errors to HTML, for example if you need to debug JS and don't have access to the console.

You do need to change 'console.log' with 'logThis', as it is not recommended to change native functionality.

What you'll get:

  • A plain and simple 'logThis' function that will display strings and objects along with current date and time for each line
  • A dedicated window on top of everything else. (show it only when needed)
  • Can be used inside '.catch' to see relevant errors from promises.
  • No change of default console.log behavior
  • Messages will appear in the console as well.

_x000D_
_x000D_
function logThis(message) {
  // if we pass an Error object, message.stack will have all the details, otherwise give us a string
  if (typeof message === 'object') {
    message = message.stack || objToString(message);
  }

  console.log(message);

  // create the message line with current time
  var today = new Date();
  var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
  var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
  var dateTime = date + ' ' + time + ' ';

  //insert line
  document.getElementById('logger').insertAdjacentHTML('afterbegin', dateTime + message + '<br>');
}

function objToString(obj) {
  var str = 'Object: ';
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      str += p + '::' + obj[p] + ',\n';
    }
  }
  return str;
}

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

logThis(object1)
logThis('And all the roads we have to walk are winding, And all the lights that lead us there are blinding')
_x000D_
#logWindow {
  overflow: auto;
  position: absolute;
  width: 90%;
  height: 90%;
  top: 5%;
  left: 5%;
  right: 5%;
  bottom: 5%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 20;
}
_x000D_
<div id="logWindow">
  <pre id="logger"></pre>
</div>
_x000D_
_x000D_
_x000D_

Thanks this answer too, JSON.stringify() didn't work for this.

How to define custom exception class in Java, the easiest way?

and don't forget the easiest way to throw an exception (you don't need to create a class)

if (rgb > MAX) throw new RuntimeException("max color exceeded");

Best way to disable button in Twitter's Bootstrap

The easiest way to do this, is to use the disabled attribute, as you had done in your original question:

<button class="btn btn-disabled" disabled>Content of Button</button>

As of now, Twitter Bootstrap doesn't have a method to disable a button's functionality without using the disabled attribute.

Nonetheless, this would be an excellent feature for them to implement into their javascript library.

Double.TryParse or Convert.ToDouble - which is faster and safer?

I have always preferred using the TryParse() methods because it is going to spit back success or failure to convert without having to worry about exceptions.

How to pass command-line arguments to a PowerShell ps1 file

You may not get "xuxu p1 p2 p3 p4" as it seems. But when you are in PowerShell and you set

PS > set-executionpolicy Unrestricted -scope currentuser

You can run those scripts like this:

./xuxu p1 p2 p3 p4

or

.\xuxu p1 p2 p3 p4

or

./xuxu.ps1 p1 p2 p3 p4

I hope that makes you a bit more comfortable with PowerShell.

Using android.support.v7.widget.CardView in my project (Eclipse)

I finally found a way to use CardView in ADT/Eclipse. It's actually pretty easy:

  1. Create a new project in Android Studio
  2. Add the CardView dependency as explained in the other answers to this question
  3. Open ADT and create a new library project with package name android.support.v7.cardview
  4. Delete all resources ADT auto-created
  5. Find the exploded-aar folder in Android Studio and copy the following files to these locations:
    • res/values/values.xml to the same location in your ADT project
    • classes.jar to libs/ in your ADT project
    • AndroidManifest.xml use it to replace the auto-generated manifest in ADT
  6. Add classes.jar to the build path and make sure it's exported
  7. Add a reference to the library project in the project you want to use CardView in. You can follow the steps provided under Adding libraries with resources here: https://developer.android.com/tools/support-library/setup.html

As an alternative to having to create a new Android Studio project in order to get the AAR's content, you could also simply find and unzip the AAR from the local maven repo. Just follow the steps provided by Andrew Chen below.

Please note the CardView library might not be available in source- and ADT-compatible-form because it's still only a preview and a WIP. As there might be bug fixes and improvements in following releases, it's important to keep the library up-to-date, which is easy using the Gradle dependency, but must be done manually when using the steps provided above.

How can I check if a value is a json object?

Since it's just false and json object, why don't you check whether it's false, otherwise it must be json.

if(ret == false || ret == "false") {
    // json
}

ToString() function in Go

When you have own struct, you could have own convert-to-string function.

package main

import (
    "fmt"
)

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

func (c Color) String() string {
    return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}

func main() {
    c := Color{Red: 123, Green: 11, Blue: 34}
    fmt.Println(c) //[123, 11, 34]
}

How to set image in circle in swift

imageView.layer.cornerRadius = imageView.frame.height/2
imageView.clipToBounds = true

How to get substring from string in c#?

string newString = str.Substring(0,10)

will give you the first 10 characters (from position 0 to position 9).

See here.

How to save a BufferedImage as a File

As a one liner:

ImageIO.write(Scalr.resize(ImageIO.read(...), 150));

SQL SELECT everything after a certain character

For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:

   CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

How can I remove an element from a list?

I would like to add that if it's a named list you can simply use within.

l <- list(a = 1, b = 2)    
> within(l, rm(a))
$b
[1] 2

So you can overwrite the original list

l <- within(l, rm(a)) 

to remove element named a from list l.

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

Just my two cents for future visitors who have this problem.

This is the correct syntax for PHP 5.3, for example if you call static method from the class name:

MyClassName::getConfig($key);

If you previously assign the ClassName to the $cnf variable, you can call the static method from it (we are talking about PHP 5.3):

$cnf = MyClassName;
$cnf::getConfig($key);

However, this sintax doesn't work on PHP 5.2 or lower, and you need to use the following:

$cnf = MyClassName;
call_user_func(array($cnf, "getConfig", $key, ...otherposibleadditionalparameters... ));

Hope this helps people having this error in 5.2 version (don't know if this was openfrog's version).

Chosen Jquery Plugin - getting selected values

Like from any regular input/select/etc...:

$("form.my-form .chosen-select").val()

How to select the first element of a set with JSTL?

Since i have have just one element in my Set the order is not important So I can access to the first element like this :

${ attachments.iterator().next().id }

How can I increase a scrollbar's width using CSS?

You can stablish specific toolbar for div

div::-webkit-scrollbar {
width: 12px;
}

div::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}

see demo in jsfiddle.net

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

The following should be the most correct today. Note, junit 4.11 depends on hamcrest-core, so you shouldn't need to specify that at all, mockito-all cannot be used since it includes (not depends on) hamcrest 1.1

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.8</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

How to write a simple Html.DropDownListFor()?

See this MSDN article and an example usage here on Stack Overflow.

Let's say that you have the following Linq/POCO class:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
}

And let's say that you have the following model:

public class PageModel 
{
   public int MyColorId { get; set; }
}

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId, 
                         new SelectList(Colors, "ColorId", "Name")) %>

Windows equivalent to UNIX pwd

cd without any parameters is equivalent to pwd on Unix/Linux.

From the console output of typing cd /?:

Displays the name of or changes the current directory.

[...]

Type CD without parameters to display the current drive and directory.

Update R using RStudio

I found that for me the best permanent solution to stay up-to-date under Linux was to install the R-patched project. This will keep your R installation up-to-date, and you needn't even move your packages between installations (which is described in RyanStochastic's answer).

For openSUSE, see the instructions here.

How to disable input conditionally in vue.js

To toggle the input's disabled attribute was surprisingly complex. The issue for me was twofold:

(1) Remember: the input's "disabled" attribute is NOT a Boolean attribute.
The mere presence of the attribute means that the input is disabled.

However, the Vue.js creators have prepared this... https://vuejs.org/v2/guide/syntax.html#Attributes

(Thanks to @connexo for this... How to add disabled attribute in input text in vuejs?)

(2) In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.

Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"

From Vue.js docs: https://vuejs.org/v2/guide/reactivity.html

The solution was to use:

this.$nextTick(()=>{
    this.disableInputBool = true
})

Fuller example workflow:

<div @click="allowInputOverwrite">
    <input
        type="text"
        :disabled="disableInputBool">
</div>

<button @click="disallowInputOverwrite">
    press me (do stuff in method, then disable input bool again)
</button>

<script>

export default {
  data() {
    return {
      disableInputBool: true
    }
  },
  methods: {
    allowInputOverwrite(){
      this.disableInputBool = false
    },
    disallowInputOverwrite(){
      // accomplish other stuff here.
      this.$nextTick(()=>{
        this.disableInputBool = true
      })
    }
  }

}
</script>

How to change status bar color in Flutter?

Change status bar color when you are not using AppBar

First Import this

import 'package:flutter/services.dart';

Now use below code to change status bar color in your application when you are not using the AppBar

SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(

    statusBarColor: AppColors.statusBarColor,/* set Status bar color in Android devices. */
    
    statusBarIconBrightness: Brightness.dark,/* set Status bar icons color in Android devices.*/
    
    statusBarBrightness: Brightness.dark)/* set Status bar icon color in iOS. */
); 

To change the status bar color in iOS when you are using SafeArea

Scaffold(
  body: Container(
    color: Colors.red, /* Set your status bar color here */
    child: SafeArea(child: Container(
      /* Add your Widget here */
    )),
  ),
); 

How do I make a simple crawler in PHP?

I came up with the following spider code. I adapted it a bit from the following: PHP - Is the there a safe way to perform deep recursion? it seems fairly rapid....

    <?php
function  spider( $base_url , $search_urls=array() ) {
    $queue[] = $base_url;
    $done           =   array();
    $found_urls     =   array();
    while($queue) {
            $link = array_shift($queue);
            if(!is_array($link)) {
                $done[] = $link;
                foreach( $search_urls as $s) { if (strstr( $link , $s )) { $found_urls[] = $link; } }
                if( empty($search_urls)) { $found_urls[] = $link; }
                if(!empty($link )) {
echo 'LINK:::'.$link;
                      $content =    file_get_contents( $link );
//echo 'P:::'.$content;
                    preg_match_all('~<a.*?href="(.*?)".*?>~', $content, $sublink);
                    if (!in_array($sublink , $done) && !in_array($sublink , $queue)  ) {
                           $queue[] = $sublink;
                    }
                }
            } else {
                    $result=array();
                    $return = array();
                    // flatten multi dimensional array of URLs to one dimensional.
                    while(count($link)) {
                         $value = array_shift($link);
                         if(is_array($value))
                             foreach($value as $sub)
                                $link[] = $sub;
                         else
                               $return[] = $value;
                     }
                     // now loop over one dimensional array.
                     foreach($return as $link) {
                                // echo 'L::'.$link;
                                // url may be in form <a href.. so extract what's in the href bit.
                                preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $link, $result);
                                if ( isset( $result['href'][0] )) { $link = $result['href'][0]; }
                                // add the new URL to the queue.
                                if( (!strstr( $link , "http")) && (!in_array($base_url.$link , $done)) && (!in_array($base_url.$link , $queue)) ) {
                                     $queue[]=$base_url.$link;
                                } else {
                                    if ( (strstr( $link , $base_url  ))  && (!in_array($base_url.$link , $done)) && (!in_array($base_url.$link , $queue)) ) {
                                         $queue[] = $link;
                                    }
                                }
                      }
            }
    }


    return $found_urls;
}    


    $base_url       =   'https://www.houseofcheese.co.uk/';
    $search_urls    =   array(  $base_url.'acatalog/' );
    $done = spider( $base_url  , $search_urls  );

    //
    // RESULT
    //
    //
    echo '<br /><br />';
    echo 'RESULT:::';
    foreach(  $done as $r )  {
        echo 'URL:::'.$r.'<br />';
    }

PHP and MySQL Select a Single Value

try this

session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
      $_SESSION['myid'] = $row['id'];
}