Programs & Examples On #Code documentation

How do I configure different environments in Angular.js?

We could also do something like this.

(function(){
    'use strict';

    angular.module('app').service('env', function env() {

        var _environments = {
            local: {
                host: 'localhost:3000',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            dev: {
                host: 'dev.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            test: {
                host: 'test.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            stage: {
                host: 'stage.com',
                config: {
                apiroot: 'staging'
                }
            },
            prod: {
                host: 'production.com',
                config: {
                    apiroot: 'production'
                }
            }
        },
        _environment;

        return {
            getEnvironment: function(){
                var host = window.location.host;
                if(_environment){
                    return _environment;
                }

                for(var environment in _environments){
                    if(typeof _environments[environment].host && _environments[environment].host == host){
                        _environment = environment;
                        return _environment;
                    }
                }

                return null;
            },
            get: function(property){
                return _environments[this.getEnvironment()].config[property];
            }
        }

    });

})();

And in your controller/service, we can inject the dependency and call the get method with property to be accessed.

(function() {
    'use strict';

    angular.module('app').service('apiService', apiService);

    apiService.$inject = ['configurations', '$q', '$http', 'env'];

    function apiService(config, $q, $http, env) {

        var service = {};
        /* **********APIs **************** */
        service.get = function() {
            return $http.get(env.get('apiroot') + '/api/yourservice');
        };

        return service;
    }

})();

$http.get(env.get('apiroot') would return the url based on the host environment.

Key Shortcut for Eclipse Imports

Some other useful shortcuts:

  1. Alt + Shift + R : Rename
  2. Alt + Shift + Y : Word wrap
  3. Alt + Shift + V : Move the selected elements
  4. Alt + Shift + I : Inline refactoring
  5. Alt + Shift + M : Extract Method refactoring.
  6. Alt + Shift + L : Extract Local Variable
  7. Alt + Shift + A : Block selection mode
  8. Alt + Shift + Arrow Keys: selects enclosing elements
  9. Alt + Shift + F1: Focus on eclipse element to know plugin implementation details.
  10. Alt + Shift + F2: Plugin implementation details.
  11. F4 : Type Hierarchy
  12. Ctrl + Shift + T : Open Type
  13. Ctrl + Shift + H: Open Type in Hierarchy
  14. Ctrl + Alt + H: Call Hierarchy
  15. Ctrl + Shift + G: Reference in workspace
  16. Ctrl + Alt + G: Quick Search for selected text
  17. Ctrl + Shift + O: Organize imports
  18. Ctrl + Shift + M: Add import for currently selected.
  19. Ctrl + Shift + L: Shows you a List of your currently defined shortcut keys
  20. Ctrl + Shift + U: Occurrence in current file
  21. Ctrl + Shift + A: Open plug-in Artifact
  22. Ctrl + Shift + {: Two side by side editors with current file
  23. Ctrl + Shift + Space : Parameter Hints
  24. Ctrl + Shift + Mouse hover : To view javadoc
  25. Shift + Mouse hover : To view source code
  26. Ctrl + Space : Content Assist
  27. Ctrl + F3/O : Outline
  28. Ctrl + T: Type Hierarchy
  29. Ctrl + H : Open Search Dialog
  30. Ctrl + 1 : Quick Fix
  31. Ctrl+Shift+NUM_KEYPAD_DIVIDE : Collapse All code blocks
  32. Ctrl+Shift+NUM_KEYPAD_MULTIPLY : To open all code blocks
  33. Alt + left arrow : Open recently closed file

Ctrl+Shift+ any key :Direct actions (on text mostly)

Alt+Shift+ any key : Indirect actions


Ctrl It was originally used to send Control character to terminals. Ctrl commands are commonly used shortcuts. (In Mac Command)

Alt It enables alternate uses for other keys.


The above shortcuts are default, if we want to change shortcuts we can do. In eclipse -> Windows -> preferences -> keys. Where we can find all shortcuts with full details:
enter image description here

and
https://shortcutworld.com/IntelliJ-IDEA/win/IntelliJ_Shortcuts https://shortcutworld.com/Eclipse/win/Eclipse-Helios_Shortcuts https://www.jetbrains.com/help/idea/migrating-from-eclipse-to-intellij-idea.html#Shortcuts

Why do we have to normalize the input for an artificial neural network?

I believe the answer is dependent on the scenario.

Consider NN (neural network) as an operator F, so that F(input) = output. In the case where this relation is linear so that F(A * input) = A * output, then you might choose to either leave the input/output unnormalised in their raw forms, or normalise both to eliminate A. Obviously this linearity assumption is violated in classification tasks, or nearly any task that outputs a probability, where F(A * input) = 1 * output

In practice, normalisation allows non-fittable networks to be fittable, which is crucial to experimenters/programmers. Nevertheless, the precise impact of normalisation will depend not only on the network architecture/algorithm, but also on the statistical prior for the input and output.

What's more, NN is often implemented to solve very difficult problems in a black-box fashion, which means the underlying problem may have a very poor statistical formulation, making it hard to evaluate the impact of normalisation, causing the technical advantage (becoming fittable) to dominate over its impact on the statistics.

In statistical sense, normalisation removes variation that is believed to be non-causal in predicting the output, so as to prevent NN from learning this variation as a predictor (NN does not see this variation, hence cannot use it).

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

How I can print to stderr in C?

Do you know sprintf? It's basically the same thing with fprintf. The first argument is the destination (the file in the case of fprintf i.e. stderr), the second argument is the format string, and the rest are the arguments as usual.

I also recommend this printf (and family) reference.

sort json object in javascript

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

What's the difference between a proxy server and a reverse proxy server?

My understanding from an Apache perspective is that proxy means that if site x proxies for site y, then requests for x return y.

The reverse proxy means that the response from y is adjusted so that all references to y become x.

So that the user cannot tell that a proxy is involved...

How to set environment variables from within package.json?

Just use NPM package cross-env. Super easy. Works on Windows, Linux, and all environments. Notice that you don't use && to move to the next task. You just set the env and then start the next task. Credit to @mikekidder for the suggestion in one of the comments here.

From documentation:

{
  "scripts": {
    "build": "cross-env NODE_ENV=production OTHERFLAG=myValue webpack --config build/webpack.config.js"
  }
}

Notice that if you want to set multiple global vars, you just state them in succession, followed by your command to be executed.

Ultimately, the command that is executed (using spawn) is:

webpack --config build/webpack.config.js

The NODE_ENV environment variable will be set by cross-env

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

I had also similar problem where by I had to un-install JDK 1.8 and needed jdk 1.7. What i did was removed the symbolic links from the javapath and then imported the shortcuts of java, javaw, javaws from the bin directory to the javapath folder. However, I found some permission issues in the enterprise laptop where by I did not have the privilege to modify/ update this directory. I had given appropriate permission from the administrator and there by resolved it.

Setting a div's height in HTML with CSS

Give this a try:

_x000D_
_x000D_
html, body,_x000D_
#left, #right {_x000D_
  height: 100%_x000D_
}_x000D_
_x000D_
#left {_x000D_
  float: left;_x000D_
  width: 25%;_x000D_
}_x000D_
#right {_x000D_
  width: 75%;_x000D_
}
_x000D_
<html>_x000D_
  <body>_x000D_
    <div id="left">_x000D_
      Content_x000D_
    </div>_x000D_
    <div id="right">_x000D_
      Content_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Interview question: Check if one string is a rotation of other string

Here's one using regex just for fun:

boolean isRotation(String s1, String s2) {
   return (s1.length() == s2.length()) && (s1 + s2).matches("(.*)(.*)\\2\\1");
}

You can make it a bit simpler if you can use a special delimiter character guaranteed not to be in either strings.

boolean isRotation(String s1, String s2) {
   // neither string can contain "="
   return (s1 + "=" + s2).matches("(.*)(.*)=\\2\\1");
}

You can also use lookbehind with finite repetition instead:

boolean isRotation(String s1, String s2) {
   return (s1 + s2).matches(
      String.format("(.*)(.*)(?<=^.{%d})\\2\\1", s1.length())
   );
}

Exit single-user mode

use master

GO

select d.name, d.dbid, spid, login_time, nt_domain, nt_username, loginame from sysprocesses p inner join sysdatabases d on p.dbid = d.dbid where d.name = 'database name'

kill 568 -- kill spid

ALTER DATABASE database name'

SET MULTI_USER go

How do I set up Visual Studio Code to compile C++ code?

There's now a C/C++ language extension from Microsoft. You can install it by going to the "quick open" thing (Ctrl+p) and typing:

ext install cpptools

You can read about it here:

https://blogs.msdn.microsoft.com/vcblog/2016/03/31/cc-extension-for-visual-studio-code/

It's very basic, as of May 2016.

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

Quote from xlsxwriter module documentation:

This module cannot be used to modify or write to an existing Excel XLSX file.

If you want to modify existing xlsx workbook, consider using openpyxl module.

See also:

Get the selected value in a dropdown using jQuery.

Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.

var methodvalue = $("#method option:selected").val(); 

Send form data using ajax

I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
Following part of the function might be of interest:

  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }

It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.

Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:

function ajax_create_request_string(data, recursion) {
  var data_string = '';
  //Zpracovani formulare
  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        if(elem[i].className.indexOf("autoempty")!=-1) {
          data_string += elem[i].name+"=";
        }
        else
          data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }
  //Loop through array
  if(data instanceof Array) {
    for(var i=0; i<data.length; i++) {
      if(data_string!="")
        data_string+="&";
      data_string+=recursion+"["+i+"]="+data[i];
    }
    return data_string;
  }
  //Loop through object (like foreach)
  for(var i in data) {
    if(data_string!="")
      data_string+="&";
    if(typeof data[i]=="object") {
      if(recursion==null)
        data_string+= ajax_create_request_string(data[i], i);
      else
        data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
    }
    else if(recursion==null)
      data_string+=i+"="+data[i];
    else 
      data_string+=recursion+"["+i+"]="+data[i];
  }
  return data_string;
}

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Referencing assemblies that are not used during build is not the correct practice. You should augment your build file so it will copy the additional files. Either by using a post build event or by updating the property group.

Some examples can be found in other post

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

This is python code for the ping in range of the 192.168.0.0-192.168.0.100. You can change for loop as you comfort.

# -*- coding: utf-8 -*-
import socket
import os
import sys

up_ip =[] #list to store the ip-addresses of server online
for x in range(100):  #here range is 0-100. You can change the range according to your comfort

    server_ip = '192.168.0.'+ str(x)
    print "Trying ,server_ip,... \n"

    rep = os.system('ping -c 1 ' + server_ip)

    if rep == 0:
        up_ip.append(server_ip)
        print '******************* Server Is Up **************** \n'
    else:
        print 'server is down \n'

print up_ip

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

If you still haven't resolved this issue - like me - here is what caused this error for me. As @jkyoutsey suggested, I was indeed trying to create a modal component. I spent considerable time following his suggestions by moving my component to a service and injecting it into the page component. Also changing providedIn: 'root' to MyModule, which of course had to be moved at least one level up to avoid a circular reference. I'm not all together sure any of that actually was necessary.

What finally solved the 8-hour long puzzle was to NOT implement ngOnInit in my component. I had blindly implemented ngOnInit even though the function was empty. I tend to do that. It's probably a bad practice.

Anyway, if someone could shed light on why an empty ngOnInit would have caused this error, I'd love to read the comments.

The default XML namespace of the project must be the MSBuild XML namespace

The projects you are trying to open are in the new .NET Core csproj format. This means you need to use Visual Studio 2017 which supports this new format.

For a little bit of history, initially .NET Core used project.json instead of *.csproj. However, after some considerable internal deliberation at Microsoft, they decided to go back to csproj but with a much cleaner and updated format. However, this new format is only supported in VS2017.

If you want to open the projects but don't want to wait until March 7th for the official VS2017 release, you could use Visual Studio Code instead.

Remove duplicates in the list using linq

List<Employee> employees = new List<Employee>()
{
    new Employee{Id =1,Name="AAAAA"}
    , new Employee{Id =2,Name="BBBBB"}
    , new Employee{Id =3,Name="AAAAA"}
    , new Employee{Id =4,Name="CCCCC"}
    , new Employee{Id =5,Name="AAAAA"}
};

List<Employee> duplicateEmployees = employees.Except(employees.GroupBy(i => i.Name)
                                             .Select(ss => ss.FirstOrDefault()))
                                            .ToList();

Oracle PL Sql Developer cannot find my tnsnames.ora file

I recently had the problem of deleting the tnsnames.ora from the path where I had it, my solution was to create an environment variable called TNS_NAME with the value the path where the tnsnames.ora file is located and ready

How to ping ubuntu guest on VirtualBox

If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces still configured for eth0.

Diagnose:

ethtool -i eth0
Cannot get driver information: no such device

Find your interfaces:

ls /sys/class/net
eth1 eth2 lo

Fix it:

Edit /etc/networking/interfaces and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)

:%s/eth0/eth2/g

Rounding numbers to 2 digits after comma

This worked for me:

var new_number = float.toFixed(2);

Example:

var my_float = 0.6666

my_float.toFixed(3) # => 0.667

How to calculate distance between two locations using their longitude and latitude value

Here getting distance in miles (mi)

private double distance(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) 
                    * Math.sin(deg2rad(lat2))
                    + Math.cos(deg2rad(lat1))
                    * Math.cos(deg2rad(lat2))
                    * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

How do I calculate the normal vector of a line segment?

This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y') is perpendicular to the line connecting (x1,y1) and (x2,y2). This line has direction (x2-x1,y2-y1), or (dx,dy).
So,

(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0

The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx) or (-dy,dx)

Preventing console window from closing on Visual Studio C/C++ Console application

(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).

"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.

I ended with

int main() {
  ...
#if _DEBUG
  LOG_INFO("end, press key to close");
  getchar();
#endif // _DEBUG
  return 0;
}

Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.

How to write palindrome in JavaScript

Look at this:

function isPalindrome(word){
    if(word==null || word.length==0){
        // up to you if you want true or false here, don't comment saying you 
        // would put true, I put this check here because of 
        // the following i < Math.ceil(word.length/2) && i< word.length
        return false;
    }
    var lastIndex=Math.ceil(word.length/2);
    for (var i = 0; i < lastIndex  && i< word.length; i++) {
        if (word[i] != word[word.length-1-i]) {
            return false;
        }
     }
     return true;
} 

Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!

Since the string is an array of char no need to use charAt functions!!!

Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome

TypeError: 'list' object is not callable in python

For me it was a flask server returning some videos array (which I expected to be in json format..)

adding json.dumps(videos) fixed this issue

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

Create a asmx web service in C# using visual studio 2013

Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.

Deleting DataFrame row in Pandas based on column value

I compiled and run my code. This is accurate code. You can try it your own.

data = pd.read_excel('file.xlsx')

If you have any special character or space in column name you can write it in '' like in the given code:

data = data[data['expire/t'].notnull()]
print (date)

If there is just a single string column name without any space or special character you can directly access it.

data = data[data.expire ! = 0]
print (date)

How to use multiple LEFT JOINs in SQL?

You have two choices, depending on your table order

create table aa (sht int)
create table cc (sht int)
create table cd (sht int)
create table ab (sht int)

-- type 1    
select * from cd
inner join cc on cd.sht = cc.sht
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cc.sht

-- type 2
select * from cc
inner join cc on cd.sht = cc.sht
LEFT JOIN ab
LEFT JOIN aa
ON aa.sht = ab.sht
ON ab.sht = cd.sht

Concatenate two JSON objects

var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
    baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}

Error "library not found for" after putting application in AdMob

Easy solution. Here's how I'd fix the issue:

  1. Go to the directory platforms/ios
  2. Then, execute the command pod install

That's it. This should install the missing library.

CSS: Force float to do a whole new line

This is what I did. Seems to work in forcing a new line, but I'm not an html/css guru by any measure.

<p>&nbsp;</p>

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Remove element should clear out such errors. The reason behind this is the inherited settings. Your application will inherit some settings from its parent's config file and machine's (server) config files.
You can either remove such duplicates with the remove tag before adding them or make these tags non-inheritable in the upper level config files.

How to fix the height of a <div> element?

You can try max-height: 70px; See if that works.

Why is vertical-align: middle not working on my span or div?

This seems to be the best way - some time has passed since my original post and this is what should be done now: http://jsfiddle.net/m3ykdyds/200

/* CSS file */

.main {
    display: table;
}

.inner {
    border: 1px solid #000000;
    display: table-cell;
    vertical-align: middle;
}

/* HTML File */
<div class="main">
    <div class="inner"> This </div>
</div>

Converting a float to a string without rounding it

Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.

Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:

http://docs.python.org/library/decimal.html

Among other things you can explicitly specify the precision that you wish to obtain (from the docs):

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

A simple example from my prompt (python 2.6):

>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29

Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.

Hope this helps, Francesco

Sending the bearer token with axios

Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;

Edit, Thanks to Jason Norwood-Young.

Some API require bearer to be written as Bearer, so you can do:

axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}

Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

Groovy - How to compare the string?

In Groovy, null == null gets a true. At runtime, you won't know what happened. In Java, == is comparing two references.

This is a cause of big confusion in basic programming, Whether it is safe to use equals. At runtime, a null.equals will give an exception. You've got a chance to know what went wrong.

Especially, you get two values from keys not exist in map(s), == makes them equal.

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

@Autowired annotation is defined in the Spring framework.

@Inject annotation is a standard annotation, which is defined in the standard "Dependency Injection for Java" (JSR-330). Spring (since the version 3.0) supports the generalized model of dependency injection which is defined in the standard JSR-330. (Google Guice frameworks and Picocontainer framework also support this model).

With @Inject can be injected the reference to the implementation of the Provider interface, which allows injecting the deferred references.

Annotations @Inject and @Autowired- is almost complete analogies. As well as @Autowired annotation, @Inject annotation can be used for automatic binding properties, methods, and constructors.

In contrast to @Autowired annotation, @Inject annotation has no required attribute. Therefore, if the dependencies will not be found - will be thrown an exception.

There are also differences in the clarifications of the binding properties. If there is ambiguity in the choice of components for the injection the @Named qualifier should be added. In a similar situation for @Autowired annotation will be added @Qualifier qualifier (JSR-330 defines it's own @Qualifier annotation and via this qualifier annotation @Named is defined).

How do I declare class-level properties in Objective-C?

Starting from Xcode 8, you can use the class property attribute as answered by Berbie.

However, in the implementation, you need to define both class getter and setter for the class property using a static variable in lieu of an iVar.

Sample.h

@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end

Sample.m

@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
   if (_sharedSample==nil) {
      [Sample setSharedSample:_sharedSample];
   }
   return _sharedSample;
}

+ (void)setSharedSample:(Sample *)sample {
   _sharedSample = [[Sample alloc]init];
}
@end

HTML SELECT - Change selected option by VALUE using JavaScript

You can select the value using javascript:

document.getElementById('sel').value = 'bike';

DEMO

gdb: "No symbol table is loaded"

Whenever gcc on the compilation machine and gdb on the testing machine have differing versions, you may be facing debuginfo format incompatibility.

To fix that, try downgrading the debuginfo format:

gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...

Or match gdb to the gcc you're using.

URL rewriting with PHP

Although already answered, and author's intent is to create a front controller type app but I am posting literal rule for problem asked. if someone having the problem for same.

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([\d]+)$ $1?id=$3 [L]

Above should work for url picture.php/Some-text-goes-here/51. without using a index.php as a redirect app.

.NET Core vs Mono

In a nutshell:

Mono = Compiler for C#

Mono Develop = Compiler+IDE

.Net Core = ASP Compiler

Current case for .Net Core is web only as soon as it adopts some open winform standard and wider language adoption, it could finally be the Microsoft killer dev powerhouse. Considering Oracle's recent Java licensing move, Microsoft have a huge time to shine.

split string only on first instance of specified character

This solution worked for me

var str = "good_luck_buddy";
var index = str.indexOf('_');
var arr = [str.slice(0, index), str.slice(index + 1)];

//arr[0] = "good"
//arr[1] = "luck_buddy"

OR

var str = "good_luck_buddy";
var index = str.indexOf('_');
var [first, second] = [str.slice(0, index), str.slice(index + 1)];

//first = "good"
//second = "luck_buddy"

Show row number in row header of a DataGridView

Thanks @Gabriel-Perez and @Groo, great idea! In case others want it, here's a version in VB tested in Visual Studio 2012. In my case I wanted the numbers to appear top right aligned in the Row Header.

Private Sub MyDGV_RowPostPaint(sender As Object, _
    e As DataGridViewRowPostPaintEventArgs) Handles MyDataGridView.RowPostPaint

    ' Automatically maintains a Row Header Index Number 
    '   like the Excel row number, independent of sort order

    Dim grid As DataGridView = CType(sender, DataGridView)
    Dim rowIdx As String = (e.RowIndex + 1).ToString()
    Dim rowFont As New System.Drawing.Font("Tahoma", 8.0!, _
        System.Drawing.FontStyle.Bold, _
        System.Drawing.GraphicsUnit.Point, CType(0, Byte))

    Dim centerFormat = New StringFormat()
    centerFormat.Alignment = StringAlignment.Far
    centerFormat.LineAlignment = StringAlignment.Near

    Dim headerBounds As Rectangle = New Rectangle(_
        e.RowBounds.Left, e.RowBounds.Top, _
        grid.RowHeadersWidth, e.RowBounds.Height)
    e.Graphics.DrawString(rowIdx, rowFont, SystemBrushes.ControlText, _
        headerBounds, centerFormat)
End Sub

You can also get the default font, rowFont = grid.RowHeadersDefaultCellStyle.Font, but it might not look as good. The screenshot below is using the Tahoma font.

Example on windows 7

How to have multiple CSS transitions on an element?

Here's a LESS mixin for transitioning two properties at once:

.transition-two(@transition1, @transition1-duration, @transition2, @transition2-duration) {
 -webkit-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
    -moz-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
      -o-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
          transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
}

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Update Eclipse with Android development tools v. 23

If you install a new Eclipse version it will work. Here's what I did:

  1. Installed the new Eclipse version, Luna
  2. Made a backup of the current workspace.
  3. Ran the new Eclipse, Luna, and updated the workspace
  4. Installed the ADT plugin (Help -> Install New Software)
  5. Restarted Eclipse
  6. Done

href="javascript:" vs. href="javascript:void(0)"

When using javascript: in navigation the return value of the executed script, if there is one, becomes the content of a new document which is displayed in the browser. The void operator in JavaScript causes the return value of the expression following it to return undefined, which prevents this action from happening. You can try it yourself, copy the following into the address bar and press return:

javascript:"hello"

The result is a new page with only the word "hello". Now change it to:

javascript:void "hello"

...nothing happens.

When you write javascript: on its own there's no script being executed, so the result of that script execution is also undefined, so the browser does nothing. This makes the following more or less equivalent:

javascript:undefined;
javascript:void 0;
javascript:

With the exception that undefined can be overridden by declaring a variable with the same name. Use of void 0 is generally pointless, and it's basically been whittled down from void functionThatReturnsSomething().

As others have mentioned, it's better still to use return false; in the click handler than use the javascript: protocol.

Javascript seconds to minutes and seconds

Another but much more elegant solution for this is as follows:

/**
 * Convert number secs to display time
 *
 * 65 input becomes 01:05.
 *
 * @param Number inputSeconds Seconds input.
 */
export const toMMSS = inputSeconds => {
    const secs = parseInt( inputSeconds, 10 );
    let minutes = Math.floor( secs / 60 );
    let seconds = secs - minutes * 60;

    if ( 10 > minutes ) {
        minutes = '0' + minutes;
    }
    if ( 10 > seconds ) {
        seconds = '0' + seconds;
    }

    // Return display.
    return minutes + ':' + seconds;
};

jQuery addClass onClick

Using jQuery:

$('#Button').click(function(){
    $(this).addClass("active");
});

This way, you don't have to pollute your HTML markup with onclick handlers.

How to compare two dates in php

The date_diff() function returns the difference between two DateTime objects.

If the first date is before the second date a positive number of days will be returned; otherwise a negative number of days:

<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>

output will be "+272 days" ;

changing $date1 = "2014-03-15"

 <?php
    $date1=date_create("2014-03-15");
    $date2=date_create("2013-12-12");
    $diff=date_diff($date1,$date2);
    echo $diff->format("%R%a days");
    ?>

Output will be "-93 days"

PHP: Get key from array?

Use the array_search function.

Example from php.net

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

Automatically size JPanel inside JFrame

You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.

Simply adding the following line of code should fix your problems:

mainFrame.setLayout(new BorderLayout());

(Do this before adding components to the JFrame)

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

Try it: sudo mysql_secure_installation

Work's in Ubuntu 18.04

ToggleButton in C# WinForms

This is my simple codes I hope it can help you

private void button2_Click(object sender, EventArgs e)
    {
        if (button2.Text == "ON")
        {
            panel_light.BackColor = Color.Yellow; //symbolizes light turned on

            button2.Text = "OFF";
        }

        else if (button2.Text == "OFF")
        {
            panel_light.BackColor = Color.Black; //symbolizes light turned off

            button2.Text = "ON";
        }
    }

CSS @media print issues with background-color;

To enable background printing in Chrome:

body {
  -webkit-print-color-adjust: exact !important;
}

Facebook Android Generate Key Hash

UPDATED ANSWER (Generating through code) Simpler method :

In my experience, openssl always being troublesome, I tried the second method suggested by facebook. And it's wonderful. This is the best method to get the hash key.

Second option is to print out the key hash sent to Facebook and use that value. Make the following changes to the onCreate() method in your main activity:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.facebook.samples.loginhowto", 
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
        ...other operations

}//end of onCreate

Replace com.facebook.samples.loginhowto with your own package name ( package name in Manifest.xml).

Official link - https://developers.facebook.com/docs/android/login-with-facebook/ ( See the bottom of the page)

OLD ANSWER (Generating Keyhash using openssl )

  1. to generate signature you need openssl installed on your pc. If you don’t have one download openssl from here
  2. In C: , Create openssl folder
  3. extract the contents of downloaded openssl zip file into openssl folder in C:drive
  4. open Command prompt
  5. move to bin of openssl i.e C:\openssl\bin in command prompt
  6. run the following command to generate your keyhash. While generating hashkey it should ask you password.

    keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Anhsirk.android\debug.keystore" | openssl sha1 -binary | openssl base64

NOTE: in the above code note that , you need to give your path to user ( i.e in my case it is C:\Users\Anhsirk , you just need to change this for your user account.

Give password as android

. If it don’t ask for password your keystore path is incorrect.

If everything works fine, it should give you the hashkey below.

enter image description here

Simple prime number generator in Python

def is_prime(num):
    """Returns True if the number is prime
    else False."""
    if num == 0 or num == 1:
        return False
    for x in range(2, num):
        if num % x == 0:
            return False
    else:
        return True

>> filter(is_prime, range(1, 20))
  [2, 3, 5, 7, 11, 13, 17, 19]

We will get all the prime numbers upto 20 in a list. I could have used Sieve of Eratosthenes but you said you want something very simple. ;)

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

Styling the arrow on bootstrap tooltips

If you want to style only the colors of the tooltips do as follow:

.tooltip-inner { background-color: #000; color: #fff; }
.tooltip.top .tooltip-arrow { border-top-color: #000; }
.tooltip.right .tooltip-arrow { border-right-color: #000; }
.tooltip.bottom .tooltip-arrow { border-bottom-color: #000; }
.tooltip.left .tooltip-arrow { border-left-color: #000; }

How to put an image next to each other

Instead of using position:relative in #icons, you could just take that away and maybe add a z-index or something so the picture won't get covered up. Hope this helps.

Detect network connection type on Android

The answer from Emil Davtyan is good, but network types have been added that are not accounted for in his answer. So, isConnectionFast(int type, int subType) may return false when it should be true.

Here is a modified class which uses reflection to account for added network types in later APIs:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p>Utility methods to check the current network connection status.</p>
 *
 * <p>This requires the caller to hold the permission
 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.</p>
 */
public class NetworkUtils {

  /** The absence of a connection type. */
  public static final int TYPE_NONE = -1;

  /** Unknown network class. */
  public static final int NETWORK_CLASS_UNKNOWN = 0;
  /** Class of broadly defined "2G" networks. */
  public static final int NETWORK_CLASS_2_G = 1;
  /** Class of broadly defined "3G" networks. */
  public static final int NETWORK_CLASS_3_G = 2;
  /** Class of broadly defined "4G" networks. */
  public static final int NETWORK_CLASS_4_G = 3;

  /**
   * Returns details about the currently active default data network. When connected, this network
   * is the default route for outgoing connections. You should always check {@link
   * NetworkInfo#isConnected()} before initiating network traffic. This may return {@code null}
   * when there is no default network.
   *
   * @return a {@link NetworkInfo} object for the current default network or {@code null} if no
   * network default network is currently active
   *
   * This method requires the call to hold the permission
   * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
   * @see ConnectivityManager#getActiveNetworkInfo()
   */
  public static NetworkInfo getInfo(Context context) {
    return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
        .getActiveNetworkInfo();
  }

  /**
   * Reports the current network type.
   *
   * @return {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI} ,
   * {@link ConnectivityManager#TYPE_WIMAX}, {@link ConnectivityManager#TYPE_ETHERNET}, {@link
   * ConnectivityManager#TYPE_BLUETOOTH}, or other types defined by {@link ConnectivityManager}.
   * If there is no network connection then -1 is returned.
   * @see NetworkInfo#getType()
   */
  public static int getType(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return TYPE_NONE;
    }
    return info.getType();
  }

  /**
   * Return a network-type-specific integer describing the subtype of the network.
   *
   * @return the network subtype
   * @see NetworkInfo#getSubtype()
   */
  public static int getSubType(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return TYPE_NONE;
    }
    return info.getSubtype();
  }

  /** Returns the NETWORK_TYPE_xxxx for current data connection. */
  public static int getNetworkType(Context context) {
    return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
        .getNetworkType();
  }

  /** Check if there is any connectivity */
  public static boolean isConnected(Context context) {
    return getType(context) != TYPE_NONE;
  }

  /** Check if there is any connectivity to a Wifi network */
  public static boolean isWifiConnection(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_WIFI:
        return true;
      default:
        return false;
    }
  }

  /** Check if there is any connectivity to a mobile network */
  public static boolean isMobileConnection(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_MOBILE:
        return true;
      default:
        return false;
    }
  }

  /** Check if the current connection is fast. */
  public static boolean isConnectionFast(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_WIFI:
      case ConnectivityManager.TYPE_ETHERNET:
        return true;
      case ConnectivityManager.TYPE_MOBILE:
        int networkClass = getNetworkClass(getNetworkType(context));
        switch (networkClass) {
          case NETWORK_CLASS_UNKNOWN:
          case NETWORK_CLASS_2_G:
            return false;
          case NETWORK_CLASS_3_G:
          case NETWORK_CLASS_4_G:
            return true;
        }
      default:
        return false;
    }
  }

  private static int getNetworkClassReflect(int networkType)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Method getNetworkClass = TelephonyManager.class.getDeclaredMethod("getNetworkClass", int.class);
    if (!getNetworkClass.isAccessible()) {
      getNetworkClass.setAccessible(true);
    }
    return (int) getNetworkClass.invoke(null, networkType);
  }

  /**
   * Return general class of network type, such as "3G" or "4G". In cases where classification is
   * contentious, this method is conservative.
   */
  public static int getNetworkClass(int networkType) {
    try {
      return getNetworkClassReflect(networkType);
    } catch (Exception ignored) {
    }

    switch (networkType) {
      case TelephonyManager.NETWORK_TYPE_GPRS:
      case 16: // TelephonyManager.NETWORK_TYPE_GSM:
      case TelephonyManager.NETWORK_TYPE_EDGE:
      case TelephonyManager.NETWORK_TYPE_CDMA:
      case TelephonyManager.NETWORK_TYPE_1xRTT:
      case TelephonyManager.NETWORK_TYPE_IDEN:
        return NETWORK_CLASS_2_G;
      case TelephonyManager.NETWORK_TYPE_UMTS:
      case TelephonyManager.NETWORK_TYPE_EVDO_0:
      case TelephonyManager.NETWORK_TYPE_EVDO_A:
      case TelephonyManager.NETWORK_TYPE_HSDPA:
      case TelephonyManager.NETWORK_TYPE_HSUPA:
      case TelephonyManager.NETWORK_TYPE_HSPA:
      case TelephonyManager.NETWORK_TYPE_EVDO_B:
      case TelephonyManager.NETWORK_TYPE_EHRPD:
      case TelephonyManager.NETWORK_TYPE_HSPAP:
      case 17: // TelephonyManager.NETWORK_TYPE_TD_SCDMA:
        return NETWORK_CLASS_3_G;
      case TelephonyManager.NETWORK_TYPE_LTE:
      case 18: // TelephonyManager.NETWORK_TYPE_IWLAN:
        return NETWORK_CLASS_4_G;
      default:
        return NETWORK_CLASS_UNKNOWN;
    }
  }

  private NetworkUtils() {
    throw new AssertionError();
  }

}

How to build a query string for a URL in C#?

This is the identical to the accepted answer except slightly more compact:

private string ToQueryString(NameValueCollection nvc)
{
    return "?" + string.Join("&", nvc.AllKeys.Select(k => string.Format("{0}={1}", 
        HttpUtility.UrlEncode(k), 
        HttpUtility.UrlEncode(nvc[k]))));
}

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

In Eclipse Luna 4.4.0, you can chose to ignore this error in preferences

Window > Preferences > Maven > Errors/Warnings > Plugin execution not covered by lifecycle configuration. Select Ignore / Warning / Error as you wish.

Also, in the quick fix (Ctrl + 1) for this error, it gives an option to mark goal as ignored in Eclipse build in Eclipse preferences (experimental)

This is a cleaner way, as it doesn't modify your pom.xml.

You will need to do a Maven > Update project to fix the same error in any other project as well.


In STS(Spring-tool-suite), you can choose to ignore this error in preferences

Window > Preferences > Maven > Errors/Warnings > Plugin execution not covered by life-cycle configuration. Select Ignore / Warning / Error as your wish. Then. Right click the project click Maven and update the project then error will gone.

What is the difference between Sessions and Cookies in PHP?

Session

Session is used for maintaining a dialogue between server and user. It is more secure because it is stored on the server, we cannot easily access it. It embeds cookies on the user computer. It stores unlimited data.

Cookies

Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session. It stores limited amount of data, and is maintained for a limited time.

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
    doThis();
} else if (value == 2) {
    doThat();
} else {
    doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

What is @ModelAttribute in Spring MVC?

@ModelAttribute will create a attribute with the name specified by you (@ModelAttribute("Testing") Test test) as Testing in the given example ,Test being the bean test being the reference to the bean and Testing will be available in model so that you can further use it on jsp pages for retrieval of values that you stored in you ModelAttribute.

How to get html to print return value of javascript function?

if you really wanted to do that you could then do

<script type="text/javascript">
    document.write(produceMessage())
</script>

Wherever in the document you want the message.

Function inside a function.?

Not sure what the author of that code wanted to achieve. Definining a function inside another function does NOT mean that the inner function is only visible inside the outer function. After calling x() the first time, the y() function will be in global scope as well.

How to convert 1 to true or 0 to false upon model fetch

Assigning Comparison to property value

JavaScript

You could assign the comparison of the property to "1"

obj["isChecked"] = (obj["isChecked"]==="1");

This only evaluates for a String value of "1" though. Other variables evaulate to false like an actual typeof number would be false. (i.e. obj["isChecked"]=1)

If you wanted to be indiscrimate about "1" or 1, you could use:

obj["isChecked"] = (obj["isChecked"]=="1");

Example Outputs

console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false

PHP

Same concept in PHP

$obj["isChecked"] = ($obj["isChecked"] == "1");

The same operator limitations as stated above for JavaScript apply.

Double Not

The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:

JavaScript

!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false

PHP

echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

How to read data from java properties file using Spring Boot

You can use @PropertySource to externalize your configuration to a properties file. There is number of way to do get properties:

1. Assign the property values to fields by using @Value with PropertySourcesPlaceholderConfigurer to resolve ${} in @Value:

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Value("${gMapReportUrl}")
    private String gMapReportUrl;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

2. Get the property values by using Environment:

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Autowired
    private Environment env;

    public void foo() {
        env.getProperty("gMapReportUrl");
    }

}

Hope this can help

Cannot resolve symbol 'AppCompatActivity'

Try this. In Android Studio, after putting the dependency in build.gradle. Go to Build --> Clean Project.

It worked for me.

Terminal Commands: For loop with echo

By using jot:

jot -w "http://example.com/%d.jpg" 1000 1

Deprecated: mysql_connect()

This warning is displayed because a new extension has appeared. It suppouse that you still can use the old one but in some cases it´s impossible.

I show you how I do the connection with database. You need just change the values of the variables.

My connection file: connection.php

<?php    
 $host='IP or Server Name (usually "localhost") ';
 $user='Database user';
 $password='Database password';
 $db='Database name';

 //PHP 5.4 o earlier (DEPRECATED)
 $con = mysql_connect($host,$user,$password) or exit("Connection Error");
 $connection = mysql_select_db($db, $con);

 //PHP 5.5 (New method)
 $connection =  mysqli_connect($host,$user,$password,$db);
?>

The extension changes too when performing a query.

Query File: "example.php"

<?php
 //First I call for the connection
 require("connection.php");

 // ... Here code if you need do something ...

 $query = "Here the query you are going to perform";

 //QUERY PHP 5.4 o earlier (DEPRECATED)
 $result = mysql_query ($query) or exit("The query could not be performed");

 //QUERY PHP 5.5 (NEW EXTENSION)
 $result = mysqli_query ($query) or exit("The query could not be performed");    
?>

This way is using MySQL Improved Extension, but you can use PDO (PHP Data Objects).

First method can be used only with MySQL databases, but PDO can manage different types of databases.

I'm going to put an example but it´s necessary to say that I only use the first one, so please correct me if there is any error.

My PDO connection file: "PDOconnection.php"

<?php
 $hostDb='mysql:host= "Here IP or Server Name";dbname="Database name" ';
 $user='Database user';
 $password='Database password';

 $connection = new PDO($hostDb, $user, $password);
?>

Query File (PDO): "example.php"

<?php
 $query = "Here the query you are going to perform";
 $result=$connection->$query;
?>

To finish just say that of course you can hide the warning but it´s not a good idea because can help you in future save time if an error happens (all of us knows the theory but if you work a lot of hours sometimes... brain is not there ^^ ).

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

How to access List elements

Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

So i use list comprehension like this:

[i[0] for i in list] which return first element value for each list inside list.

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

You might be launching your application from a Product file which is not linked to the plugin file. Reset your workspace and launch using the MANIFEST.MF > Overview > Testing > Launch.

Check time difference in Javascript

In my case, I'm gonna store the time in milliseconds on chrome storage and try to find diff in hours later.

function timeDiffInHours(milliseconds){
    time_diff = (new Date).getTime() - milliseconds
    return parseInt((time_diff/(1000*60*60)) % 24)
}

// This is again sending current time and diff would be 0.
timeDiffInHours((new Date).getTime());  

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had this too and you can fix it by setting the tools version in your build definition.

This is very easy to do. Open your build definition and go to the "Process" page. Then under the "3. Advanced" group you have a property called "MSBuild Arguments". Place the parameter there with the following syntax

/p:VisualStudioVersion=12.0 

If you have more parameters, separate them with a space and not a comma.

Plotting histograms from grouped data in a pandas DataFrame

Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist() it's trying to make a histogram of both columns hence the str error.

This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.

df.reset_index().pivot('index','Letter','N').hist()

The reset_index() is just to shove the current index into a column called index. Then pivot will take your data frame, collect all of the values N for each Letter and make them a column. The resulting data frame as 400 rows (fills missing values with NaN) and three columns (A, B, C). hist() will then produce one histogram per column and you get format the plots as needed.

Annotation @Transactional. How to rollback?

or programatically

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Case-insensitive string comparison in C++

The trouble with boost is that you have to link with and depend on boost. Not easy in some cases (e.g. android).

And using char_traits means all your comparisons are case insensitive, which isn't usually what you want.

This should suffice. It should be reasonably efficient. Doesn't handle unicode or anything though.

bool iequals(const string& a, const string& b)
{
    unsigned int sz = a.size();
    if (b.size() != sz)
        return false;
    for (unsigned int i = 0; i < sz; ++i)
        if (tolower(a[i]) != tolower(b[i]))
            return false;
    return true;
}

Update: Bonus C++14 version (#include <algorithm>):

bool iequals(const string& a, const string& b)
{
    return std::equal(a.begin(), a.end(),
                      b.begin(), b.end(),
                      [](char a, char b) {
                          return tolower(a) == tolower(b);
                      });
}

What is the difference between a string and a byte string?

The Python languages includes str and bytes as standard "Built-in Types". In other words, they are both classes. I don't think it's worthwhile trying to rationalize why Python has been implemented this way.

Having said that, str and bytes are very similar to one another. Both share most of the same methods. The following methods are unique to the str class:

casefold
encode
format
format_map
isdecimal
isidentifier
isnumeric
isprintable

The following methods are unique to the bytes class:

decode
fromhex
hex

Sort columns of a dataframe by column name

An alternative option is to use str_sort() from library stringr, with the argument numeric = TRUE. This will correctly order column that include numbers not just alphabetically:

str_sort(c("V3", "V1", "V10"), numeric = TRUE)

# [1] V1 V3 V11

TypeError: object of type 'int' has no len() error assistance needed

Well, maybe an int does not posses the len attribute in Python like your error suggests?

Try:

len(str(numbers))

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

How can I divide two integers to get a double?

Convert one of them to a double first. This form works in many languages:

 real_result = (int_numerator + 0.0) / int_denominator

tSQL - Conversion from varchar to numeric works for all but integer

Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:

select cast ('7.0' as int)
select cast ('7.' as int)

will fail but both are fine for floats.

How to get file path in iPhone app

You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.

Extracting jar to specified directory

It's better to do this.

Navigate to the folder structure you require

Use the command

jar -xvf  'Path_to_ur_Jar_file'

how much memory can be accessed by a 32 bit machine?

Yes, on a 32bit machine the maximum amount of memory usable is around 4GB. Actually, depending on the OS it might be less due to parts of the address space being reserved: On Windows you can only use 3.5GB for example.

On 64bit you can indeed address 2^64 bytes of memory. Not that you'll ever have those - but then again, a long time ago the same thing was said about ever needing more than 640kb of memory...

How do I copy the contents of one ArrayList into another?

Straightforward way to make deep copy of original list is to add all element from one list to another list.

ArrayList<Object> originalList = new ArrayList<Object>();
ArrayList<Object> duplicateList = new ArrayList<Object>();

for(Object o : originalList) {
    duplicateList.add(o);
}

Now If you make any changes to originalList it will not impact duplicateList.

How do I use a PriorityQueue?

Use the constructor overload which takes a Comparator<? super E> comparator and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)

As has been said elsewhere: offer and add are just different interface method implementations. In the JDK source I've got, add calls offer. Although add and offer have potentially different behaviour in general due to the ability for offer to indicate that the value can't be added due to size limitations, this difference is irrelevant in PriorityQueue which is unbounded.

Here's an example of a priority queue sorting by string length:

// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class Test {
    public static void main(String[] args) {
        Comparator<String> comparator = new StringLengthComparator();
        PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
        queue.add("short");
        queue.add("very long indeed");
        queue.add("medium");
        while (queue.size() != 0) {
            System.out.println(queue.remove());
        }
    }
}

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator<String> {
    @Override
    public int compare(String x, String y) {
        // Assume neither string is null. Real code should
        // probably be more robust
        // You could also just return x.length() - y.length(),
        // which would be more efficient.
        if (x.length() < y.length()) {
            return -1;
        }
        if (x.length() > y.length()) {
            return 1;
        }
        return 0;
    }
}

Here is the output:

short

medium

very long indeed

Last Key in Python Dictionary

sorted(dict.keys())[-1]

Otherwise, the keys is just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.

Maybe you want to look into OrderedDict.

How do I check if a Sql server string is null or empty

Here's a solution, but I don't know if it's the best....

Select              
Coalesce(Case When Len(listing.Offer_Text) = 0 Then Null Else listing.Offer_Text End, company.Offer_Text, '') As Offer_Text,         
from tbl_directorylisting listing  
 Inner Join tbl_companymaster company            
  On listing.company_id= company.company_id

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

How can I disable HREF if onclick is executed?

This might help. No JQuery needed

<a href="../some-relative-link/file" 
onclick="this.href = 'https://docs.google.com/viewer?url='+this.href; this.onclick = '';" 
target="_blank">

This code does the following: Pass the relative link to Google Docs Viewer

  1. Get the full link version of the anchor by this.href
  2. open the link the the new window.

So in your case this might work:

<a href="../some-relative-link/file" 
onclick="this.href = 'javascript:'+console.log('something has stopped the link'); " 
target="_blank">

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

First you need to install cors by using below command :

npm install cors --save

Now add the following code to your app starting file like ( app.js or server.js)

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

require('./router/index')(app);

How do I convert a TimeSpan to a formatted string?

You can use the following code.

public static class TimeSpanExtensions
{
  public static String Verbose(this TimeSpan timeSpan)
  {
    var hours = timeSpan.Hours;
    var minutes = timeSpan.Minutes;

    if (hours > 0) return String.Format("{0} hours {1} minutes", hours, minutes);
    return String.Format("{0} minutes", minutes);
  }
}

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.

How can I implement rate limiting with Apache? (requests per second)

In Apache 2.4, there's a new stock module called mod_ratelimit. For emulating modem speeds, you can use mod_dialup. Though I don't see why you just couldn't use mod_ratelimit for everything.

How to limit the maximum value of a numeric field in a Django model?

from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

size = models.IntegerField(validators=[MinValueValidator(0),
                                       MaxValueValidator(5)])

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Small comparison table Java vs. JavaScript vs. PHP.

1. Java URLEncoder.encode (using UTF8 charset)
2. JavaScript encodeURIComponent
3. JavaScript escape
4. PHP urlencode
5. PHP rawurlencode

char   JAVA JavaScript --PHP---
[ ]     +    %20  %20  +    %20
[!]     %21  !    %21  %21  %21
[*]     *    *    *    %2A  %2A
[']     %27  '    %27  %27  %27 
[(]     %28  (    %28  %28  %28
[)]     %29  )    %29  %29  %29
[;]     %3B  %3B  %3B  %3B  %3B
[:]     %3A  %3A  %3A  %3A  %3A
[@]     %40  %40  @    %40  %40
[&]     %26  %26  %26  %26  %26
[=]     %3D  %3D  %3D  %3D  %3D
[+]     %2B  %2B  +    %2B  %2B
[$]     %24  %24  %24  %24  %24
[,]     %2C  %2C  %2C  %2C  %2C
[/]     %2F  %2F  /    %2F  %2F
[?]     %3F  %3F  %3F  %3F  %3F
[#]     %23  %23  %23  %23  %23
[[]     %5B  %5B  %5B  %5B  %5B
[]]     %5D  %5D  %5D  %5D  %5D
----------------------------------------
[~]     %7E  ~    %7E  %7E  ~
[-]     -    -    -    -    -
[_]     _    _    _    _    _
[%]     %25  %25  %25  %25  %25
[\]     %5C  %5C  %5C  %5C  %5C
----------------------------------------
char  -JAVA-  --JavaScript--  -----PHP------
[ä]   %C3%A4  %C3%A4  %E4     %C3%A4  %C3%A4
[?]   %D1%84  %D1%84  %u0444  %D1%84  %D1%84

HTML 5 Video "autoplay" not automatically starting in CHROME

This may not have been the case at the time the question was asked, but as of Chrome 66, autoplay is blocked.

http://bgr.com/2018/04/18/google-chrome-66-download-auto-playing-videos-block/

Wait till a Function with animations is finished until running another Function

Along with Yoshi's answer, I have found another very simple (callback type) solution for animations.

jQuery has an exposed variable (that for some reason isn't listed anywhere in the jQuery docs) called $.timers, which holds the array of animations currently taking place.

function animationsTest (callback) {
    // Test if ANY/ALL page animations are currently active

    var testAnimationInterval = setInterval(function () {
        if (! $.timers.length) { // any page animations finished
            clearInterval(testAnimationInterval);
            callback();
        }
    }, 25);
};

Basic useage:

functionOne(); // one with animations

animationsTest(functionTwo);

Hope this helps some people out!

Git - Ignore files during merge

I got over this issue by using git merge command with the --no-commit option and then explicitly removed the staged file and ignore the changes to the file. E.g.: say I want to ignore any changes to myfile.txt I proceed as follows:

git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"

You can put statements 2 & 3 in a for loop, if you have a list of files to skip.

Session timeout in ASP.NET

I don't know about web.config or IIS. But I believe that from C# code you can do it like

Session.Timeout = 60; // 60 is number of minutes

Bootstrap 3 only for mobile

I found a solution wich is to do:

<span class="visible-sm"> your code without col </span>
<span class="visible-xs"> your code with col </span>

It's not very optimized but it works. Did you find something better? It really miss a class like col-sm-0 to apply colons just to the xs size...

Searching for Text within Oracle Stored Procedures

If you use UPPER(text), the like '%lah%' will always return zero results. Use '%LAH%'.

How to use MySQLdb with Python and Django in OSX 10.6?

The error raised here is in importing the python module. This can be solved by adding the python site-packages folder to the environment variable $PYTHONPATH on OS X. So we can add the following command to the .bash_profile file:

export PYTHONPATH="$PYTHONPATH:/usr/local/lib/pythonx.x/site-packages/"

*replace x.x with the python version you are using

How to align text below an image in CSS?

Add a container div for the image and the caption:

<div class="item">
    <img src=""/>
    <span class="caption">Text below the image</span>
</div>

Then, with a bit of CSS, you can make an automatically wrapping image gallery:

div.item {
    vertical-align: top;
    display: inline-block;
    text-align: center;
    width: 120px;
}
img {
    width: 100px;
    height: 100px;
    background-color: grey;
}
.caption {
    display: block;
}

_x000D_
_x000D_
div.item {_x000D_
    /* To correctly align image, regardless of content height: */_x000D_
    vertical-align: top;_x000D_
    display: inline-block;_x000D_
    /* To horizontally center images and caption */_x000D_
    text-align: center;_x000D_
    /* The width of the container also implies margin around the images. */_x000D_
    width: 120px;_x000D_
}_x000D_
img {_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background-color: grey;_x000D_
}_x000D_
.caption {_x000D_
    /* Make the caption a block so it occupies its own line. */_x000D_
    display: block;_x000D_
}
_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">An even longer text below the image which should take up multiple lines.</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">Text below the image</span>_x000D_
</div>_x000D_
<div class="item">_x000D_
    <img src=""/>_x000D_
    <span class="caption">An even longer text below the image which should take up multiple lines.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/ZhLk4/1/

Updated answer

Instead of using 'anonymous' div and spans, you can also use the HTML5 figure and figcaption elements. The advantage is that these tags add to the semantic structure of the document. Visually there is no difference, but it may (positively) affect the usability and indexability of your pages.

The tags are different, but the structure of the code is exactly the same, as you can see in this updated snippet and fiddle:

<figure class="item">
    <img src=""/>
    <figcaption class="caption">Text below the image</figcaption>
</figure>

_x000D_
_x000D_
figure.item {_x000D_
    /* To correctly align image, regardless of content height: */_x000D_
    vertical-align: top;_x000D_
    display: inline-block;_x000D_
    /* To horizontally center images and caption */_x000D_
    text-align: center;_x000D_
    /* The width of the container also implies margin around the images. */_x000D_
    width: 120px;_x000D_
}_x000D_
img {_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background-color: grey;_x000D_
}_x000D_
.caption {_x000D_
    /* Make the caption a block so it occupies its own line. */_x000D_
    display: block;_x000D_
}
_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">An even longer text below the image which should take up multiple lines.</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">Text below the image</figcaption>_x000D_
</figure>_x000D_
<figure class="item">_x000D_
    <img src=""/>_x000D_
    <figcaption class="caption">An even longer text below the image which should take up multiple lines.</figcaption>_x000D_
</figure>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/ZhLk4/379/

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

Curly braces in string in PHP

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>

Connection to SQL Server Works Sometimes

To trace the "Connection Timeout expired" error, Please, make sure that:

For more details, Please check Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgment

How to apply !important using .css()?

If it is not so relevant and since you're dealing with one element which is #elem, you can change its id to something else and style it as you wish...

$('#elem').attr('id', 'cheaterId');

And in your CSS:

#cheaterId { width: 100px;}

Search for exact match of string in excel row using VBA Macro

This is not another code as you have already helped yourself; but for you to take a look at the performance when using Excel functions in VBA.

PS: **On a latter note, if you wish to do pattern matching then you may consider ScriptingObject **Regex.

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

How to create a dump with Oracle PL/SQL Developer?

Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?

Is there an equivalent of CSS max-width that works in HTML emails?

There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.

<!--[if gte mso 9]>
<style>
#tableForOutlook {
  width:800px;
}
</style>
<![endif]-->

<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
  <table id="tableForOutlook"><tr><td>
<![endif]-->
    <tr><td>
    [Your Content Goes Here]
    </td></tr>
<!--[if gte mso 9]>
  </td></tr></table>
<![endif]-->
<table>

Confirm deletion in modal / dialog using Twitter Bootstrap?

If you want to do it in the easiest shortcut, then u can do it with this plugin.


But this plugin is an alternate implementation using Bootstrap Modal. And real Bootstrap implementation is also very easy, so I don't like to use this plugin because it adds excess JS contents in the page, which will slow down the page loading time.


Idea

I like to implement it by myself by this way-

  1. If user clicks on a button to delete an item from the list, then a JS call will put Item ID (or any more essential data) in a form in the modal.
  2. Then in the pop-up, there will be 2 buttons for confirmation.

    • Yes will submit the form (with ajax or direct form submit)
    • No will just dismiss the modal

The code will be like this (using Bootstrap)-

_x000D_
_x000D_
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<script>_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("button").click(function()_x000D_
    {_x000D_
        //Say - $('p').get(0).id - this delete item id_x000D_
        $("#delete_item_id").val( $('p').get(0).id );_x000D_
        $('#delete_confirmation_modal').modal('show');_x000D_
    });_x000D_
});_x000D_
</script>_x000D_
_x000D_
<p id="1">This is a item to delete.</p>_x000D_
_x000D_
<button type="button" class="btn btn-danger">Delete</button>_x000D_
_x000D_
<!-- Delete Modal content-->_x000D_
_x000D_
<div class="modal fade" id="delete_confirmation_modal" role="dialog" style="display: none;">_x000D_
 <div class="modal-dialog" style="margin-top: 260.5px;">_x000D_
    <div class="modal-content">_x000D_
   <div class="modal-header">_x000D_
    <button type="button" class="close" data-dismiss="modal">×</button>_x000D_
    <h4 class="modal-title">Do you really want to delete this Category?</h4>_x000D_
   </div>_x000D_
   <form role="form" method="post" action="category_delete" id="delete_data">_x000D_
    <input type="hidden" id="delete_item_id" name="id" value="12">_x000D_
    <div class="modal-footer">_x000D_
     <button type="submit" class="btn btn-danger">Yes</button>_x000D_
     <button type="button" class="btn btn-primary" data-dismiss="modal">No</button>_x000D_
    </div>_x000D_
   </form>_x000D_
  </div>_x000D_
_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You should change the form action according to your requirement.

Happy coading :)

Replacing &nbsp; from javascript dom text node

I think when you define a function with "var foo = function() {...};", the function is only defined after that line. In other words, try this:

var replaceHtmlEntites = (function() {
  var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
  var translate = {
    "nbsp": " ",
    "amp" : "&",
    "quot": "\"",
    "lt"  : "<",
    "gt"  : ">"
  };
  return function(s) {
    return ( s.replace(translate_re, function(match, entity) {
      return translate[entity];
    }) );
  }
})();

var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);

Edit: Also, only use "var" the first time you declare a variable (you're using it twice on the cleanText variable).

Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

Add a border outside of a UIView (instead of inside)

For a Swift implementation, you can add this as a UIView extension.

extension UIView {

    struct Constants {
        static let ExternalBorderName = "externalBorder"
    }

    func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.whiteColor()) -> CALayer {
        let externalBorder = CALayer()
        externalBorder.frame = CGRectMake(-borderWidth, -borderWidth, frame.size.width + 2 * borderWidth, frame.size.height + 2 * borderWidth)
        externalBorder.borderColor = borderColor.CGColor
        externalBorder.borderWidth = borderWidth
        externalBorder.name = Constants.ExternalBorderName

        layer.insertSublayer(externalBorder, atIndex: 0)
        layer.masksToBounds = false

        return externalBorder
    }

    func removeExternalBorders() {
        layer.sublayers?.filter() { $0.name == Constants.ExternalBorderName }.forEach() {
            $0.removeFromSuperlayer()
        }
    }

    func removeExternalBorder(externalBorder: CALayer) {
        guard externalBorder.name == Constants.ExternalBorderName else { return }
        externalBorder.removeFromSuperlayer()
    }

}

Parse JSON String into List<string>

Wanted to post this as a comment as a side note to the accepted answer, but that got a bit unclear. So purely as a side note:

If you have no need for the objects themselves and you want to have your project clear of further unused classes, you can parse with something like:

var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList();

var firstNames = list.Select(p => p.FirstName).ToList();
var lastNames = list.Select(p => p.LastName).ToList();

Even when using a strongly typed person class, you can still skip the root object by creating a list with JObject.Parse(json)["People"].ToObject<List<Person>>() Of course, if you do need to reuse the objects, it's better to create them from the start. Just wanted to point out the alternative ;)

Is there a way to check which CSS styles are being used or not used on a web page?

I'm using CSS Dig. It is made for chrome, but I think it is a great tool!

Best practices for catching and re-throwing .NET exceptions

You should always use "throw;" to rethrow the exceptions in .NET,

Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx

Basically MSIL (CIL) has two instructions - "throw" and "rethrow":

  • C#'s "throw ex;" gets compiled into MSIL's "throw"
  • C#'s "throw;" - into MSIL "rethrow"!

Basically I can see the reason why "throw ex" overrides the stack trace.

How can I group by date time column without taking time into consideration

Cast/Convert the values to a Date type for your group by.

GROUP BY CAST(myDateTime AS DATE)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I just had this problem, and Google led me here, so just to add to the general solutions here, this is what worked for me:

# 'value' contains the problematic data
unic = u''
unic += value
value = unic

I had this idea after reading Ned's presentation.

I don't claim to fully understand why this works, though. So if anyone can edit this answer or put in a comment to explain, I'll appreciate it.

What is the correct way to start a mongod service on linux / OS X?

If you feel like having a simple gui to fix this (as I do), then I can recommend the mongodb pref-pane. Description: https://www.mongodb.com/blog/post/macosx-preferences-pane-for-mongodb

On github: https://github.com/remysaissy/mongodb-macosx-prefspane

MySQL - UPDATE multiple rows with different values in one query

You can use a CASE statement to handle multiple if/then scenarios:

UPDATE table_to_update 
SET  cod_user= CASE WHEN user_rol = 'student' THEN '622057'
                   WHEN user_rol = 'assistant' THEN '2913659'
                   WHEN user_rol = 'admin' THEN '6160230'
               END
    ,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
  AND cod_office = '17389551';

Binary Search Tree - Java Implementation

You can use a TreeMap data structure. TreeMap is implemented as a red black tree, which is a self-balancing binary search tree.

LoDash: Get an array of values from an array of object properties

In the new lodash release v4.0.0 _.pluck has removed in favor of _.map

Then you can use this:

_.map(users, 'id'); // [12, 14, 16, 18]

You can see in Github Changelog

Illegal Character when trying to compile java code

instead of getting Notepad++, You can simply Open the file with Wordpad and then Save As - Plain Text document

Git: can't undo local changes (error: path ... is unmerged)

You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.

Try this:

$ git reset foo/bar.txt
$ git checkout foo/bar.txt

nvarchar(max) vs NText

VARCHAR(MAX) is big enough to accommodate TEXT field. TEXT, NTEXT and IMAGE data types of SQL Server 2000 will be deprecated in future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommended to use new data types which are VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX).

compareTo() vs. equals()

Equals can be more efficient then compareTo.

If the length of the character sequences in String doesn't match there is no way the Strings are equal so rejection can be much faster.

Moreover if it is same object (identity equality rather then logical equality), it will also be more efficient.

If they also implemented hashCode caching it could be even faster to reject non-equals in case their hashCode's doesn't match.

Convert HTML + CSS to PDF

After some investigation and general hair-pulling the solution seems to be HTML2PDF. DOMPDF did a terrible job with tables, borders and even moderately complex layout and htmldoc seems reasonably robust but is almost completely CSS-ignorant and I don't want to go back to doing HTML layout without CSS just for that program.

HTML2PDF looked the most promising but I kept having this weird error about null reference arguments to node_type. I finally found the solution to this. Basically, PHP 5.1.x worked fine with regex replaces (preg_replace_*) on strings of any size. PHP 5.2.1 introduced a php.ini config directive called pcre.backtrack_limit. What this config parameter does is limits the string length for which matching is done. Why this was introduced I don't know. The default value was chosen as 100,000. Why such a low value? Again, no idea.

A bug was raised against PHP 5.2.1 for this, which is still open almost two years later.

What's horrifying about this is that when the limit is exceeded, the replace just silently fails. At least if an error had been raised and logged you'd have some indication of what happened, why and what to change to fix it. But no.

So I have a 70k HTML file to turn into PDF. It requires the following php.ini settings:

  • pcre.backtrack_limit = 2000000; # probably more than I need but that's OK
  • memory_limit = 1024M; # yes, one gigabyte; and
  • max_execution_time = 600; # yes, 10 minutes.

Now the astute reader may have noticed that my HTML file is smaller than 100k. The only reason I can guess as to why I hit this problem is that html2pdf does a conversion into xhtml as part of the process. Perhaps that took me over (although nearly 50% bloat seems odd). Whatever the case, the above worked.

Now, html2pdf is a resource hog. My 70k file takes approximately 5 minutes and at least 500-600M of RAM to create a 35 page PDF file. Not quick enough (by far) for a real-time download unfortunately and the memory usage puts the memory usage ratio in the order of 1000-to-1 (600M of RAM for a 70k file), which is utterly ridiculous.

Unfortunately, that's the best I've come up with.

How to implement swipe gestures for mobile devices?

Have you tried Hammerjs? It supports swipe gestures by using the velocity of the touch. http://eightmedia.github.com/hammer.js/

add string to String array

First, this code here,

string [] scripts = new String [] ("test3","test4","test5");

should be

String[] scripts = new String [] {"test3","test4","test5"};

Please read this tutorial on Arrays

Second,

Arrays are fixed size, so you can't add new Strings to above array. You may override existing values

scripts[0] = string1;

(or)

Create array with size then keep on adding elements till it is full.

If you want resizable arrays, consider using ArrayList.

Calculating the position of points in a circle

Based on the answer above from Daniel, here's my take using Python3.

import numpy


def circlepoints(points,radius,center):
    shape = []
    slice = 2 * 3.14 / points
    for i in range(points):
        angle = slice * i
        new_x = center[0] + radius*numpy.cos(angle)
        new_y = center[1] + radius*numpy.sin(angle)

        p = (new_x,new_y)
        shape.append(p)

    return shape

print(circlepoints(100,20,[0,0]))

Current date without time

it should be as simple as

DateTime.Today

How to auto generate migrations with Sequelize CLI from Sequelize models?

You cannot create migration scripts for existing models.

Resources:

If going the classic way, you'll have to recreate the models via the CLI:

sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text

It will generate these files:

models/myuser.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
  var MyUser = sequelize.define("MyUser", {_x000D_
    first_name: DataTypes.STRING,_x000D_
    last_name: DataTypes.STRING,_x000D_
    bio: DataTypes.TEXT_x000D_
  }, {_x000D_
    classMethods: {_x000D_
      associate: function(models) {_x000D_
        // associations can be defined here_x000D_
      }_x000D_
    }_x000D_
  });_x000D_
  return MyUser;_x000D_
};
_x000D_
_x000D_
_x000D_

migrations/20150210104840-create-my-user.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = {_x000D_
  up: function(migration, DataTypes, done) {_x000D_
    migration.createTable("MyUsers", {_x000D_
      id: {_x000D_
        allowNull: false,_x000D_
        autoIncrement: true,_x000D_
        primaryKey: true,_x000D_
        type: DataTypes.INTEGER_x000D_
      },_x000D_
      first_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      last_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      bio: {_x000D_
        type: DataTypes.TEXT_x000D_
      },_x000D_
      createdAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      },_x000D_
      updatedAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      }_x000D_
    }).done(done);_x000D_
  },_x000D_
  down: function(migration, DataTypes, done) {_x000D_
    migration.dropTable("MyUsers").done(done);_x000D_
  }_x000D_
};
_x000D_
_x000D_
_x000D_

How to validate phone numbers using regex

Note that stripping () characters does not work for a style of writing UK numbers that is common: +44 (0) 1234 567890 which means dial either the international number:
+441234567890
or in the UK dial 01234567890

http post - how to send Authorization header?

Ok. I found problem.

It was not on the Angular side. To be honest, there were no problem at all.

Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.

Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS

I implemented proper filter on my server-side app.

Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.

WCF ServiceHost access rights

please open your Visual Studio in Administration Mode then try it.

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

understanding private setters

With the introduction of C# 6.0 and the syntax for Auto-Property Initializers, private setters are no longer needed for properties that are only set upon initialization, either inline or within the constructor.

These new syntaxes now compile:

Inline initialized property

public class MyClass1 {
  public string MyProperty { get; } = "Aloha!"
}

Constructor initialized property

public class MyClass2 {
  public string MyProperty { get; }

  public MyClass2(string myProperty) {
    MyProperty = myProperty;
  }
}

Embedding VLC plugin on HTML page

test.html is will be helpful for how to use VLC WebAPI.

test.html is located in the directory where VLC was installed.

e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html

The following code is a quote from the test.html.

HTML:

<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
  <param name="MRL" value="" />
  <param name="ShowDisplay" value="True" />
  <param name="AutoLoop" value="False" />
  <param name="AutoPlay" value="False" />
  <param name="Volume" value="50" />
  <param name="toolbar" value="true" />
  <param name="StartTime" value="0" />
  <EMBED pluginspage="http://www.videolan.org"
    type="application/x-vlc-plugin"
    version="VideoLAN.VLCPlugin.2"
    width="640"
    height="360"
    toolbar="true"
    loop="false"
    text="Waiting for video"
    name="vlc">
  </EMBED>
</object>

JavaScript:

You can get vlc object from getVLC().
It works on IE 10 and Chrome.

function getVLC(name)
{
    if (window.document[name])
    {
        return window.document[name];
    }
    if (navigator.appName.indexOf("Microsoft Internet")==-1)
    {
        if (document.embeds && document.embeds[name])
            return document.embeds[name];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(name);
    }
}

var vlc = getVLC("vlc");

// do something.
// e.g. vlc.playlist.play();

How to make child element higher z-index than parent?

Give the parent z-index: -1, or opacity: 0.99

How to filter array when object key value is in array

Old way of doing it. Many might hate this way of doing but i still many time find this is still better in my perspective.

Input:

var records = [{
    "empid":1,
    "fname": "X",
    "lname": "Y"
},
{
    "empid":2,
    "fname": "A",
    "lname": "Y"
},
{
    "empid":3,
    "fname": "B",
    "lname": "Y"
},
{
    "empid":4,
    "fname": "C",
    "lname": "Y"
},
{
    "empid":5,
    "fname": "C",
    "lname": "Y"
}
]

var newArr = [1,4,5];

Code:

var newObj = [];
for(var a = 0 ; a < records.length ; a++){
 if(newArr.indexOf(records[a].empid) > -1){
  newObj.push(records[a]);
 }
}

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Output:

[{
    "empid": 1,
    "fname": "X",
    "lname": "Y"
}, {
    "empid": 4,
    "fname": "C",
    "lname": "Y"
}, {
    "empid": 5,
    "fname": "C",
    "lname": "Y"
}]

How to filter (key, value) with ng-repeat in AngularJs?

You can simply use angular.filter module, and then you can filter even by nested properties.
see: jsbin
2 Examples:

JS:

angular.module('app', ['angular.filter'])
  .controller('MainCtrl', function($scope) {
  //your example data
  $scope.items = { 
    'A2F0C7':{ secId:'12345', pos:'a20' },
    'C8B3D1':{ pos:'b10' }
  };
  //more advantage example
  $scope.nestedItems = { 
    'A2F0C7':{
      details: { secId:'12345', pos:'a20' }
    },
    'C8B3D1':{
      details: { pos:'a20' }
    },
    'F5B3R1': { secId:'12345', pos:'a20' }
  };
});

HTML:

  <b>Example1:</b>
  <p ng-repeat="item in items | toArray: true | pick: 'secId'">
    {{ item.$key }}, {{ item }}
  </p>

  <b>Example2:</b>
  <p ng-repeat="item in nestedItems | toArray: true | pick: 'secId || details.secId' ">
    {{ item.$key }}, {{ item }}
  </p> 

What does an exclamation mark mean in the Swift language?

In Short (!): After you have declare a variable and that you are certain the variable is holding a value.

let assumedString: String! = "Some message..."
let implicitString: String = assumedString

else you would have to do this on every after passing value...

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What MIME type should I use for CSV?

RFC 7111

There is an RFC which covers it and says to use text/csv.

This RFC updates RFC 4180.


Excel

Recently I discovered an explicit mimetype for Excel application/vnd.ms-excel. It was registered with IANA in '96. Note the concerns raised about being at the mercy of the sender and having your machine violated.

Media Type: application/vnd.ms-excel

Name Microsoft Excel (tm)

Required parameters: None

Optional parameters: name

Encoding considerations: base64 preferred

Security considerations: As with most application types this data is intended for interpretation by a program that understands the data on the recipient's system. Recipients need to understand that they are at the "mercy" of the sender, when receiving this type of data, since data will be executed on their system, and the security of their machines can be violated.

OID { org-id ms-files(4) ms-excel (3) }

Object type spreadsheet

Comments This Media Type/OID is used to identify Microsoft Excel generically (i.e., independent of version, subtype, or platform format).

I wasn't aware that vendor extensions were allowed. Check out this answer to find out more - thanks starbeamrainbowlabs for the reference.

Loop Through Each HTML Table Column and Get the Data using jQuery

try this

    $("#mprDetailDataTable tr:gt(0)").each(function () {
        var this_row = $(this);
        var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
        var product = $.trim(this_row.find('td:eq(1)').html())
        var Quantity = $.trim(this_row.find('td:eq(2)').html())
    });

String's Maximum length in Java - calling length() method

The Return type of the length() method of the String class is int.

public int length()

Refer http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()

So the maximum value of int is 2147483647.

String is considered as char array internally,So indexing is done within the maximum range. This means we cannot index the 2147483648th member.So the maximum length of String in java is 2147483647.

Primitive data type int is 4 bytes(32 bits) in java.As 1 bit (MSB) is used as a sign bit,The range is constrained within -2^31 to 2^31-1 (-2147483648 to 2147483647). We cannot use negative values for indexing.So obviously the range we can use is from 0 to 2147483647.

Java: export to an .jar file in eclipse

No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below. JAR Export Dialog

How do I do base64 encoding on iOS?

iOS has had built-in Base64 encoding and decoding methods (without using libresolv) since iOS 4. However, it was only declared in the iOS 7 SDK. Apple documentation states that you can use it when targeting iOS 4 and above.

NSData *myData = ... some data
NSString *base64String = [myData base64Encoding];
NSData *decodedData = [[NSData alloc] initWithBase64Encoding:base64String];

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

Type List vs type ArrayList in Java

I am wondering if anyone uses (2)?

Yes. But rarely for a sound reason (IMO).

And people get burned because they used ArrayList when they should have used List:

  • Utility methods like Collections.singletonList(...) or Arrays.asList(...) don't return an ArrayList.

  • Methods in the List API don't guarantee to return a list of the same type.

For example of someone getting burned, in https://stackoverflow.com/a/1481123/139985 the poster had problems with "slicing" because ArrayList.sublist(...) doesn't return an ArrayList ... and he had designed his code to use ArrayList as the type of all of his list variables. He ended up "solving" the problem by copying the sublist into a new ArrayList.

The argument that you need to know how the List behaves is largely addressed by using the RandomAccess marker interface. Yes, it is a bit clunky, but the alternative is worse.

Also, how often does the situation actually require using (1) over (2) (i.e. where (2) wouldn't suffice..aside 'coding to interfaces' and best practices etc.)

The "how often" part of the question is objectively unanswerable.

(and can I please get an example)

Occasionally, the application may require that you use methods in the ArrayList API that are not in the List API. For example, ensureCapacity(int), trimToSize() or removeRange(int, int). (And the last one will only arise if you have created a subtype of ArrayList that declares the method to be public.)

That is the only sound reason for coding to the class rather than the interface, IMO.

(It is theoretically possible that you will get a slight improvement in performance ... under certain circumstances ... on some platforms ... but unless you really need that last 0.05%, it is not worth doing this. This is not a sound reason, IMO.)


You can’t write efficient code if you don’t know whether random access is efficient or not.

That is a valid point. However, Java provides better ways to deal with that; e.g.

public <T extends List & RandomAccess> void test(T list) {
    // do stuff
}

If you call that with a list that does not implement RandomAccess you will get a compilation error.

You could also test dynamically ... using instanceof ... if static typing is too awkward. And you could even write your code to use different algorithms (dynamically) depending on whether or not a list supported random access.

Note that ArrayList is not the only list class that implements RandomAccess. Others include CopyOnWriteList, Stack and Vector.

I've seen people make the same argument about Serializable (because List doesn't implement it) ... but the approach above solves this problem too. (To the extent that it is solvable at all using runtime types. An ArrayList will fail serialization if any element is not serializable.)

How to display Wordpress search results?

I am using searchform.php and search.php files as already mentioned, but here I provide the actual code.

Creating a Search Page codex page helps here and #Creating_a_Search_Page_Template shows the search query.

In my case I pass the $search_query arguments to the WP_Query Class (which can determine if is search query!). I then run The Loop to display the post information I want to, which in my case is the the_permalink and the_title.

Search box form:

<form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
  <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
  <button type="submit" role="button" class="btn btn-default right"/><span class="glyphicon glyphicon-search white"></span></button>
</form>

search.php template file:

<?php
    global $query_string;
    $query_args = explode("&", $query_string);
    $search_query = array();

    foreach($query_args as $key => $string) {
      $query_split = explode("=", $string);
      $search_query[$query_split[0]] = urldecode($query_split[1]);
    } // foreach

    $the_query = new WP_Query($search_query);
    if ( $the_query->have_posts() ) : 
    ?>
    <!-- the loop -->

    <ul>    
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>   
    <?php endwhile; ?>
    </ul>
    <!-- end of the loop -->

    <?php wp_reset_postdata(); ?>

<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

How to get certain commit from GitHub project

The easiest way that I found to recover a lost commit (that only exists on github and not locally) is to create a new branch that includes this commit.

  1. Have the commit open (url like: github.com/org/repo/commit/long-commit-sha)
  2. Click "Browse Files" on the top right
  3. Click the dropdown "Tree: short-sha..." on the top left
  4. Type in a new branch name
  5. git pull the new branch down to local

Git add all files modified, deleted, and untracked?

The following answer only applies to Git version 1.x, but to Git version 2.x.

You want git add -A:

git add -A stages All;

git add . stages new and modified, without deleted;

git add -u stages modified and deleted, without new.

Why do we use Base64?

Encoding binary data in XML

Suppose you want to embed a couple images within an XML document. The images are binary data, while the XML document is text. But XML cannot handle embedded binary data. So how do you do it?

One option is to encode the images in base64, turning the binary data into text that XML can handle.

Instead of:

<images>
  <image name="Sally">{binary gibberish that breaks XML parsers}</image>
  <image name="Bobby">{binary gibberish that breaks XML parsers}</image>
</images>

you do:

<images>
  <image name="Sally" encoding="base64">j23894uaiAJSD3234kljasjkSD...</image>
  <image name="Bobby" encoding="base64">Ja3k23JKasil3452AsdfjlksKsasKD...</image>
</images>

And the XML parser will be able to parse the XML document correctly and extract the image data.

SQL count rows in a table

select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
 and index_id in (0,1)

is very fast but very rarely inaccurate.

ASP.NET set hiddenfield a value in Javascript

I will suggest you to use ClientID of HiddenField. first Register its client Id in any Javascript Variable from codebehind, then use it in clientside script. as:

.cs file code:

ClientScript.RegisterStartupScript(this.GetType(), "clientids", "var hdntxtbxTaksit=" + hdntxtbxTaksit.ClientID, true);

and then use following code in JS:

document.getElementById(hdntxtbxTaksit).value= ""; 

How to force Selenium WebDriver to click on element which is not currently visible?

I just solve this error while using capybara in ror project by adding:

Capybara.ignore_elements = true

to features/support/env.rb.

Maximum value for long integer

Direct answer to title question:

Integers are unlimited in size and have no maximum value in Python.

Answer which addresses stated underlying use case:

According to your comment of what you're trying to do, you are currently thinking something along the lines of

minval = MAXINT;
for (i = 1; i < num_elems; i++)
    if a[i] < a[i-1]
        minval = a[i];

That's not how to think in Python. A better translation to Python (but still not the best) would be

minval = a[0]  # Just use the first value
for i in range(1, len(a)):
    minval = min(a[i], a[i - 1])

Note that the above doesn't use MAXINT at all. That part of the solution applies to any programming language: You don't need to know the highest possible value just to find the smallest value in a collection.

But anyway, what you really do in Python is just

minval = min(a)

That is, you don't write a loop at all. The built-in min() function gets the minimum of the whole collection.

How to List All Redis Databases?

There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).

You can use the following command to know the number of databases:

CONFIG GET databases
1) "databases"
2) "16"

You can use the following command to list the databases for which some keys are defined:

INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.

For instance:

*2
$4
INFO
$8
keyspace

$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

You can find the description of the Redis protocol here: http://redis.io/topics/protocol

Redirecting unauthorized controller in ASP.NET MVC

In your Startup.Auth.cs file add this line:

LoginPath = new PathString("/Account/Login"),

Example:

// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30),
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

Remember to set the locale to en_US_POSIX as described in Technical Q&A1480. In Swift 3:

let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
print(formatter.string(from: date))

The issue is that if you're on a device which is using a non-Gregorian calendar, the year will not conform to RFC3339/ISO8601 unless you specify the locale as well as the timeZone and dateFormat string.

Or you can use ISO8601DateFormatter to get you out of the weeds of setting locale and timeZone yourself:

let date = Date()
let formatter = ISO8601DateFormatter()
formatter.formatOptions.insert(.withFractionalSeconds)  // this is only available effective iOS 11 and macOS 10.13
print(formatter.string(from: date))

For Swift 2 rendition, see previous revision of this answer.

Convert array of strings to List<string>

Just use this constructor of List<T>. It accepts any IEnumerable<T> as an argument.

string[] arr = ...
List<string> list = new List<string>(arr);

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You're not reading the file content:

my_file_contents = f.read()

See the docs for further infos

You could, without calling read() or readlines() loop over your file object:

f = open('goodlines.txt')
for line in f:
    print(line)

If you want a list out of it (without \n as you asked)

my_list = [line.rstrip('\n') for line in f]

the getSource() and getActionCommand()

Assuming you are talking about the ActionEvent class, then there is a big difference between the two methods.

getActionCommand() gives you a String representing the action command. The value is component specific; for a JButton you have the option to set the value with setActionCommand(String command) but for a JTextField if you don't set this, it will automatically give you the value of the text field. According to the javadoc this is for compatability with java.awt.TextField.

getSource() is specified by the EventObject class that ActionEvent is a child of (via java.awt.AWTEvent). This gives you a reference to the object that the event came from.

Edit:

Here is a example. There are two fields, one has an action command explicitly set, the other doesn't. Type some text into each then press enter.

public class Events implements ActionListener {

  private static JFrame frame; 

  public static void main(String[] args) {

    frame = new JFrame("JTextField events");
    frame.getContentPane().setLayout(new FlowLayout());

    JTextField field1 = new JTextField(10);
    field1.addActionListener(new Events());
    frame.getContentPane().add(new JLabel("Field with no action command set"));
    frame.getContentPane().add(field1);

    JTextField field2 = new JTextField(10);
    field2.addActionListener(new Events());
    field2.setActionCommand("my action command");
    frame.getContentPane().add(new JLabel("Field with an action command set"));
    frame.getContentPane().add(field2);


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(220, 150);
    frame.setResizable(false);
    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    String cmd = evt.getActionCommand();
    JOptionPane.showMessageDialog(frame, "Command: " + cmd);
  }

}

Change div height on button click

_x000D_
_x000D_
var ww1 = "";_x000D_
var ww2 = 0;_x000D_
var myVar1 ;_x000D_
var myVar2 ;_x000D_
function wm1(){_x000D_
  myVar1 =setInterval(w1, 15);_x000D_
}_x000D_
function wm2(){_x000D_
  myVar2 =setInterval(w2, 15);_x000D_
}_x000D_
function w1(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) <= 200){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)+5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar1);_x000D_
    }_x000D_
}_x000D_
function w2(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) >= 50){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)-5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar2);_x000D_
    }_x000D_
}
_x000D_
<html>_x000D_
  <head>    _x000D_
  </head>_x000D_
_x000D_
<body >_x000D_
    <button type="button" onClick = "wm1()">200px</button>_x000D_
    <button type="button" onClick = "wm2()">50px</button>_x000D_
    <div id="chartdiv" style="width: 100%; height: 50px; background-color:#ccc"></div>_x000D_
  _x000D_
  <div id="demo"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

SQL Server AS statement aliased column within WHERE statement

SQL Server is tuned to apply the filters before it applies aliases (because that usually produces faster results). You could do a nested select statement. Example:

SELECT Latitude FROM 
(
    SELECT Lat AS Latitude FROM poi_table
) A
WHERE Latitude < 500

I realize this may not be what you are looking for, because it makes your queries much more wordy. A more succinct approach would be to make a view that wraps your underlying table:

CREATE VIEW vPoi_Table AS 
SELECT Lat AS Latitude FROM poi_table

Then you could say:

SELECT Latitude FROM vPoi_Table WHERE Latitude < 500

How do I get the function name inside a function in PHP?

<?php

  class Test {
     function MethodA(){
         echo __FUNCTION__ ;
     }
 }
 $test = new Test;
 echo $test->MethodA();
?>

Result: "MethodA";

How can I determine browser window size on server side C#

So here is how you will do it.

Write a javascript function which fires whenever the window is resized.

window.onresize = function(event) {
    var height=$(window).height();
    var width=$(window).width();
    $.ajax({
     url: "/getwindowsize.ashx",
     type: "POST",
     data : { Height: height, 
              Width:width, 
              selectedValue:selectedValue },
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (response) { 
           // do stuff
     }

}

Codebehind of Handler:

 public class getwindowsize : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
     string Height = context.Request.QueryString["Height"]; 
     string Width = context.Request.QueryString["Width"]; 
    }

How do you check for permissions to write to a directory or file?

None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..

/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
    if (string.IsNullOrEmpty(DirectoryPath)) return false;

    try
    {
        AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        WindowsIdentity identity = WindowsIdentity.GetCurrent();

        foreach (FileSystemAccessRule rule in rules)
        {
            if (identity.Groups.Contains(rule.IdentityReference))
            {
                if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
                {
                    if (rule.AccessControlType == AccessControlType.Allow)
                        return true;
                }
            }
        }
    }
    catch {}
    return false;
}

"This operation requires IIS integrated pipeline mode."

I was having the same issue and I solved it doing the following:

  1. In Visual Studio, select "Project properties".

  2. Select the "Web" Tab.

  3. Select "Use Local IIS Web server".

  4. Check "Use IIS Express"

Dots in URL causes 404 with ASP.NET mvc and IIS

Just add this section to Web.config, and all requests to the route/{*pathInfo} will be handled by the specified handler, even when there are dots in pathInfo. (taken from ServiceStack MVC Host Web.config example and this answer https://stackoverflow.com/a/12151501/801189)

This should work for both IIS 6 & 7. You could assign specific handlers to different paths after the 'route' by modifying path="*" in 'add' elements

  <location path="route">
    <system.web>
      <httpHandlers>
        <add path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" />
      </httpHandlers>
    </system.web>
    <!-- Required for IIS 7.0 -->
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true" />
      <validation validateIntegratedModeConfiguration="false" />
      <handlers>
        <add name="ApiURIs-ISAPI-Integrated-4.0" path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" preCondition="integratedMode,runtimeVersionv4.0" />
      </handlers>
    </system.webServer>
  </location>

If file exists then delete the file

IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

SMTP connect() failed PHPmailer - PHP

Try adding this line to your script. This worked for me!

$mail->Mailer = “smtp”;

Check if the number is integer

In R, whether a number is numeric or integer can be determined by class function. Generally all numbers are stored as numeric and to explicitly define a number as integer we need to specify 'L' after the number.

Example:

x <- 1

class(x)

[1] "numeric"

x <- 1L

class(x)

[1] "integer"

I hope this is what was needed. Thanks :)