Programs & Examples On #Mashup

A mashup, in web development, is a web page, or web application, that uses and combines data, presentation or functionality from two or more sources to create new services. The term implies easy, fast integration, frequently using open application programming interfaces (API) and data sources to produce enriched results that were not necessarily the original reason for producing the raw source data

RESTful Authentication via Spring

You might consider Digest Access Authentication. Essentially the protocol is as follows:

  1. Request is made from client
  2. Server responds with a unique nonce string
  3. Client supplies a username and password (and some other values) md5 hashed with the nonce; this hash is known as HA1
  4. Server is then able to verify client's identity and serve up the requested materials
  5. Communication with the nonce can continue until the server supplies a new nonce (a counter is used to eliminate replay attacks)

All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.

Digest Access Authentication is supported by Spring Security. Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.

Openstreetmap: embedding map in webpage (like Google Maps)

Simple OSM Slippy Map Demo/Example

Click on "Run code snippet" to see an embedded OpenStreetMap slippy map with a marker on it. This was created with Leaflet.

Code

_x000D_
_x000D_
// Where you want to render the map.
var element = document.getElementById('osm-map');

// Height has to be set. You can do this in CSS too.
element.style = 'height:300px;';

// Create Leaflet map on map element.
var map = L.map(element);

// Add OSM tile leayer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// Target's GPS coordinates.
var target = L.latLng('47.50737', '19.04611');

// Set map's center to target with zoom 14.
map.setView(target, 14);

// Place a marker on the same location.
L.marker(target).addTo(map);
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>
<div id="osm-map"></div>
_x000D_
_x000D_
_x000D_

Specs

  • Uses OpenStreetMaps.
  • Centers the map to the target GPS.
  • Places a marker on the target GPS.
  • Only uses Leaflet as a dependency.

Note:

I used the CDN version of Leaflet here, but you can download the files so you can serve and include them from your own host.

Replace HTML page with contents retrieved via AJAX

I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:

<html>
<head>
   <script src="jquery.js" type="text/javascript"></script>
</head>
<body>
   content
</body>
<script type="text/javascript">
   $("body").load(url);
</script>
</html>

Change the Bootstrap Modal effect

Here is pure Bootstrap 4 with CSS 3 solution.

<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>
.fade2 {
    transform: scale(0.9);
    opacity: 0;
    transition: all .2s linear;
    display: block !important;
}

.fade2.show {
    opacity: 1;
    transform: scale(1);
}
$('#exampleModal').modal();

function afterModalTransition(e) {
  e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
    setTimeout( () => afterModalTransition(this), 200);
})

Full example here.

Maybe it will help someone.

--

Thank you @DavidDomain too.

Finding and removing non ascii characters from an Oracle Varchar2

I had a similar issue and blogged about it here. I started with the regular expression for alpha numerics, then added in the few basic punctuation characters I liked:

select dump(a,1016), a, b
from
 (select regexp_replace(COLUMN,'[[:alnum:]/''%()> -.:=;[]','') a,
         COLUMN b
  from TABLE)
where a is not null
order by a;

I used dump with the 1016 variant to give out the hex characters I wanted to replace which I could then user in a utl_raw.cast_to_varchar2.

Setting up redirect in web.config file

In case that you need to add the http redirect in many sites, you could use it as a c# console program:

   class Program
{
    static int Main(string[] args)
    {
        if (args.Length < 3)
        {
            Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
            return 1;
        }

        if (args.Length == 3)
        {
            if (args[0].ToLower() == "-insert-redirect")
            {
                var path = args[1];
                var value = args[2];

                if (InsertRedirect(path, value))
                    Console.WriteLine("Redirect added.");
                return 0;
            }
        }

        Console.WriteLine("Wrong parameters.");
        return 1;

    }

    static bool InsertRedirect(string path, string value)
    {
        try
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(path);

            // This should find the appSettings node (should be only one):
            XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");

            var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
            if (existNode != null)
                return false;

            // Create new <add> node
            XmlNode nodeNewKey = doc.CreateElement("httpRedirect");

            XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
            XmlAttribute attributeDestination = doc.CreateAttribute("destination");
            //XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");

            // Assign values to both - the key and the value attributes:

            attributeEnable.Value = "true";
            attributeDestination.Value = value;
            //attributeResponseStatus.Value = "Permanent";

            // Add both attributes to the newly created node:
            nodeNewKey.Attributes.Append(attributeEnable);
            nodeNewKey.Attributes.Append(attributeDestination);
            //nodeNewKey.Attributes.Append(attributeResponseStatus);

            // Add the node under the 
            nodeAppSettings.AppendChild(nodeNewKey);
            doc.Save(path);

            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Exception adding redirect: {e.Message}");
            return false;
        }
    }
}

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

What is the difference between “int” and “uint” / “long” and “ulong”?

It's been a while since I C++'d but these answers are off a bit.

As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.

So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.

It's never polite to discuss the size of your bits in public.

When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.

So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.

Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder

A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html

use int if you really don't care how large your bits are; it can change.

Use size_t and ssize_t if you want to know how large something is.

If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.

I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.

It's crappy coding when you mix int.

use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).

StringIO in Python3

when i write import StringIO it says there is no such module.

From What’s New In Python 3.0:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

.


A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):

try:
    from StringIO import StringIO ## for Python 2
except ImportError:
    from io import StringIO ## for Python 3

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

Postgres: SQL to list table foreign keys

check the ff post for your solution and don't forget to mark this when you fine this helpful

http://errorbank.blogspot.com/2011/03/list-all-foreign-keys-references-for.html

SELECT
  o.conname AS constraint_name,
  (SELECT nspname FROM pg_namespace WHERE oid=m.relnamespace) AS source_schema,
  m.relname AS source_table,
  (SELECT a.attname FROM pg_attribute a WHERE a.attrelid = m.oid AND a.attnum = o.conkey[1] AND a.attisdropped = false) AS source_column,
  (SELECT nspname FROM pg_namespace WHERE oid=f.relnamespace) AS target_schema,
  f.relname AS target_table,
  (SELECT a.attname FROM pg_attribute a WHERE a.attrelid = f.oid AND a.attnum = o.confkey[1] AND a.attisdropped = false) AS target_column
FROM
  pg_constraint o LEFT JOIN pg_class f ON f.oid = o.confrelid LEFT JOIN pg_class m ON m.oid = o.conrelid
WHERE
  o.contype = 'f' AND o.conrelid IN (SELECT oid FROM pg_class c WHERE c.relkind = 'r');

Escape double quote character in XML

Here are the common characters which need to be escaped in XML, starting with double quotes:

  1. double quotes (") are escaped to &quot;
  2. ampersand (&) is escaped to &amp;
  3. single quotes (') are escaped to &apos;
  4. less than (<) is escaped to &lt;
  5. greater than (>) is escaped to &gt;

How to download a file from a URL in C#?

using (var client = new WebClient())
{
    client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}

How do I create a view controller file after creating a new view controller?

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

How do you set your pythonpath in an already-created virtualenv?

  1. Initialize your virtualenv
cd venv

source bin/activate
  1. Just set or change your python path by entering command following:
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
  1. for checking python path enter in python:
   python

      \>\> import sys

      \>\> sys.path

How do I iterate and modify Java Sets?

Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.

It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet implementation of java.util.Set interface satisfies your rather special requirements.

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html

ImportError: No module named xlsxwriter

Even if it looks like the module is installed, as far as Python is concerned it isn't since it throws that exception.

Try installing the module again using one of the installation methods shown in the XlsxWriter docs and look out for any installation errors.

If there are none then run a sample program like the following:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Hello world')

workbook.close()

How to use cURL to get jSON data and decode the data?

You can Use this for Curl:

function fakeip()  
{  
    return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );   
}  

function getdata($url,$args=false) 
{ 
    global $session; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip())); 
    if($args) 
    { 
        curl_setopt($ch, CURLOPT_POST, 1); 
        curl_setopt($ch, CURLOPT_POSTFIELDS,$args); 
    } 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888"); 
    $result = curl_exec ($ch); 
    curl_close ($ch); 
    return $result; 
} 

Then To Read Json:

$result=getdata("https://example.com");

Then :

///Deocde Json
$data = json_decode($result,true);
///Count
             $total=count($data);
             $Str='<h1>Total : '.$total.'';
             echo $Str;
//You Can Also Make In Table:
             foreach ($data as $key => $value)
              {
          echo '  <td><font  face="calibri"color="red">'.$value[type].'   </font></td><td><font  face="calibri"color="blue">'.$value[category].'   </font></td><td><font  face="calibri"color="green">'.$value[amount].'   </font></tr><tr>';

           }
           echo "</tr></table>";
           }

You Can Also Use This:

echo '<p>Name : '.$data['result']['name'].'</p>
      <img src="'.$data['result']['pic'].'"><br>';

Hope this helped.

Getting next element while cycling through a list

The simple solution is to remove IndexError by incorporating the condition:

if(index<(len(li)-1))

The error 'index out of range' will not occur now as the last index will not be reached. The idea is to access the next element while iterating. On reaching the penultimate element, you can access the last element.

Use enumerate method to add index or counter to an iterable(list, tuple, etc.). Now using the index+1, we can access the next element while iterating through the list.

li = [0, 1, 2, 3]

running = True
while running:
    for index, elem in enumerate(li):
        if(index<(len(li)-1)):
            thiselem = elem
            nextelem = li[index+1]

Why use the 'ref' keyword when passing an object?

ref mimics (or behaves) as a global area just for two scopes:

  • Caller
  • Callee.

Should I use SVN or Git?

There is an interesting Video on YouTube about this. Its from Linus Torwalds himself: Goolge Tech Talk: Linus Torvalds on git

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/

this the simple way to use it while validate atleast 1 uppercase 1 lowercase and 1 number

and this is the example while I use in express validation

check('password')
    .notEmpty()
    .withMessage('Password cannot be null')
    .bail()
    .isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters')
    .bail()
    .matches(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/)
    .withMessage(
      'Must have atleast 1 uppercase, 1 lowercase letter and 1 number'
    ),

Finding the average of an array using JS

It can simply be done with a single reduce operation as follows;

_x000D_
_x000D_
var avg = [1,2,3,4].reduce((p,c,_,a) => p + c/a.length,0);_x000D_
console.log(avg)
_x000D_
_x000D_
_x000D_

CSS rotation cross browser with jquery.animate()

jQuery transit will probably make your life easier if you are dealing with CSS3 animations through jQuery.

EDIT March 2014 (because my advice has constantly been up and down voted since I posted it)

Let me explain why I was initially hinting towards the plugin above:

Updating the DOM on each step (i.e. $.animate ) is not ideal in terms of performance. It works, but will most probably be slower than pure CSS3 transitions or CSS3 animations.

This is mainly because the browser gets a chance to think ahead if you indicate what the transition is going to look like from start to end.

To do so, you can for example create a CSS class for each state of the transition and only use jQuery to toggle the animation state.

This is generally quite neat as you can tweak you animations alongside the rest of your CSS instead of mixing it up with your business logic:

// initial state
.eye {
   -webkit-transform: rotate(45deg);
   -moz-transform: rotate(45deg);
   transform: rotate(45deg);
   // etc.

   // transition settings
   -webkit-transition: -webkit-transform 1s linear 0.2s;
   -moz-transition: -moz-transform 1s linear 0.2s;
   transition: transform 1s linear 0.2s;
   // etc.
}

// open state    
.eye.open {

   transform: rotate(90deg);
}

// Javascript
$('.eye').on('click', function () { $(this).addClass('open'); });

If any of the transform parameters is dynamic you can of course use the style attribute instead:

$('.eye').on('click', function () { 
    $(this).css({ 
        -webkit-transition: '-webkit-transform 1s ease-in',
        -moz-transition: '-moz-transform 1s ease-in',
        // ...

        // note that jQuery will vendor prefix the transform property automatically
        transform: 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)'
    }); 
});

A lot more detailed information on CSS3 transitions on MDN.

HOWEVER There are a few other things to keep in mind and all this can get a bit tricky if you have complex animations, chaining etc. and jQuery Transit just does all the tricky bits under the hood:

$('.eye').transit({ rotate: '90deg'}); // easy huh ?

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

How do you create a hidden div that doesn't create a line break or horizontal space?

Since the release of HTML5 one can now simply do:

<div hidden>This div is hidden</div>

Note: This is not supported by some old browsers, most notably IE < 11.

Hidden Attribute Documentation (MDN,W3C)

Initialize/reset struct to zero/null

Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.

For example:

static const struct x EmptyStruct;

Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.

Then, each time round the loop you can write:

myStructVariable = EmptyStruct;

What do parentheses surrounding an object/function/class declaration mean?

Andy Hume pretty much gave the answer, I just want to add a few more details.

With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.

The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.

I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:

var add_gen = function(n) {
  return function(x) {
    return n + x;
  };
};
var add2 = add_gen(2);
add2(3); // result is 5

What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.

The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.

With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:

for(var i=0; i<5; i++) {
  setTimeout(function(){alert(i)}, 10);
}

The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.

You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)

for(var i=0; i<5; i++) {
  setTimeout(
     (function(j) {
       return function(){alert(j)};
     })(i), 10);
}

With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.

I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

Quick unix command to display specific lines in the middle of a file?

If your line number is 100 to read

head -100 filename | tail -1

Converting dictionary to JSON

json.dumps() is used to decode JSON data

  • json.loads take a string as input and returns a dictionary as output.
  • json.dumps take a dictionary as input and returns a string as output.
import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

Environment Specific application.properties file in Spring Boot application

Spring Boot already has support for profile based properties.

Simply add an application-[profile].properties file and specify the profiles to use using the spring.profiles.active property.

-Dspring.profiles.active=local

This will load the application.properties and the application-local.properties with the latter overriding properties from the first.

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

Is there an Eclipse plugin to run system shell in the Console?

You can also use the Termial view to ssh/telnet to your local machine. Doesn't have that funny input box for commands.

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

How to add leading zeros?

str_pad from the stringr package is an alternative.

anim = 25499:25504
str_pad(anim, width=6, pad="0")

Vertically aligning a checkbox

_x000D_
_x000D_
Add CSS:_x000D_
_x000D_
_x000D_
li {_x000D_
  display: table-row;_x000D_
 _x000D_
 }_x000D_
li div {_x000D_
   display: table-cell;_x000D_
   vertical-align: middle;_x000D_
_x000D_
  }_x000D_
.check{_x000D_
  width:20px;_x000D_
_x000D_
  }_x000D_
ul{_x000D_
   list-style: none;_x000D_
  }_x000D_
  
_x000D_
 <ul>_x000D_
       <li>_x000D_
_x000D_
           <div><label for="myid1">Subject1</label></div>_x000D_
            <div class="check"><input type="checkbox" value="1"name="subject" class="subject-list" id="myid1"></div>_x000D_
       </li>_x000D_
       <li>_x000D_
_x000D_
           <div><label for="myid2">Subject2</label></div>_x000D_
              <div class="check" ><input type="checkbox" value="2"  class="subject-list" name="subjct" id="myid2"></div>_x000D_
       </li>_x000D_
   </ul>
_x000D_
_x000D_
_x000D_

How To change the column order of An Existing Table in SQL Server 2008

This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).

Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.

The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:

a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns

OR

b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along

The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.

I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue

Sample database for exercise

You want huge?

Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));

insert into foo(crap) values ('');

-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;

run it twenty more times, you have over a million rows to play with.

Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)

Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".

Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.

Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.

Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.

For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.

Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.

By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.

C# Get/Set Syntax Usage

By the way, in C# 3.5 you can instantiate your object's properties like so:

Person TOM=new Person 
{ 
   title = "My title", ID = 1 
};

But again, properties must be public.

Where does npm install packages?

From the docs:

Packages are dropped into the node_modules folder under the prefix. When installing locally, this means that you can require("packagename") to load its main module, or require("packagename/lib/path/to/sub/module") to load other modules.

Global installs on Unix systems go to {prefix}/lib/node_modules. Global installs on Windows go to {prefix}/node_modules (that is, no lib folder.)

Scoped packages are installed the same way, except they are grouped together in a sub-folder of the relevant node_modules folder with the name of that scope prefix by the @ symbol, e.g. npm install @myorg/package would place the package in {prefix}/node_modules/@myorg/package. See scope for more details.

If you wish to require() a package, then install it locally.

You can get your {prefix} with npm config get prefix. (Useful when you installed node with nvm).

Read about locally.
Read about globally.

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

The fields of your object have in turn their fields, some of which do not implement Serializable. In your case the offending class is TransformGroup. How to solve it?

  • if the class is yours, make it Serializable
  • if the class is 3rd party, but you don't need it in the serialized form, mark the field as transient
  • if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

If you use Java and spring MVC you just need to add the following annotation to your method returning your page :

@CrossOrigin(origins = "*")

"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.

Replacing last character in a String with java

Already @Abubakkar Rangara answered easy way to handle your problem

Alternative is :

String[] result = null;
if(fieldName.endsWith(",")) {                           
String[] result = fieldName.split(",");
    for(int i = 1; i < result.length - 1; i++) {
        result[0] = result[0].concat(result[i]);
    }
}

javascript, is there an isObject function like isArray?

In jQuery there is $.isPlainObject() method for that:

Description: Check to see if an object is a plain object (created using "{}" or "new Object").

How to take MySQL database backup using MySQL Workbench?

Sever > Data Export

enter image description here

Select database, and start export

enter image description here

How to run a script as root on Mac OS X?

As in any unix-based environment, you can use the sudo command:

$ sudo script-name

It will ask for your password (your own, not a separate root password).

How to find top three highest salary in emp table in oracle?

Limit The Query To Display Only The Top 3 Highest Paid Employees. : Query « Oracle PL / SQL

create table employee(
         emp_no                 integer         primary key
        ,lastname               varchar2(20)    not null
        ,salary                 number(3)
);

insert into employee(emp_no,lastname,salary)
              values(1,'Tomy',2);

insert into employee(emp_no,lastname,salary)
              values(2,'Jacky',3);

insert into employee(emp_no,lastname,salary)
              values(3,'Joey',4);

insert into employee(emp_no,lastname,salary)
              values(4,'Janey',5);


select lastname,  salary
from (SELECT lastname, salary FROM employee ORDER BY salary DESC)
where rownum <= 3 ;

OUTPUT

LASTNAME                 SALARY

-------------------- ----------
Janey                         5

Joey                          4

Jacky                         3

drop table employee;

How to print the value of a Tensor object in TensorFlow?

Question: How to print the value of a Tensor object in TensorFlow?

Answer:

import tensorflow as tf

# Variable
x = tf.Variable([[1,2,3]])

# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())

# Create a session
sess = tf.Session()

# run the session
sess.run(init)

# print the value
sess.run(x)

Difference between using Throwable and Exception in a try catch

Thowable catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop() method. So by catching Throwable you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError and InternalError or StackOverflowError.

Catching Throwable is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.

How do I 'svn add' all unversioned files to SVN?

svn add --force .

This will add any unversioned file in the current directory and all versioned child directories.

How do you properly use WideCharToMultiByte

Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>

/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";

int main() 
{

    size_t wcsChars = wcslen( wcsString);

    size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, 
                                               NULL, 0,  NULL, NULL);

    printf( "Wide chars in wcsString: %u\n", wcsChars);
    printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);

    sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                        NULL, 0,  NULL, NULL);
    printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);
}

And the output:

Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18

Get week of year in JavaScript like in PHP

now = new Date();
today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
firstOfYear = new Date(now.getFullYear(), 0, 1);
numOfWeek = Math.ceil((((today - firstOfYear) / 86400000)-1)/7);

Reading a plain text file in Java

The buffered stream classes are much more performant in practice, so much so that the NIO.2 API includes methods that specifically return these stream classes, in part to encourage you always to use buffered streams in your application.

Here is an example:

Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
    // Read from the stream
    String currentLine = null;
    while ((currentLine = reader.readLine()) != null)
        //do your code here
} catch (IOException e) {
    // Handle file I/O exception...
}

You can replace this code

BufferedReader reader = Files.newBufferedReader(path);

with

BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));

I recommend this article to learn the main uses of Java NIO and IO.

throw checked Exceptions from mocks with Mockito

A workaround is to use a willAnswer() method.

For example the following works (and doesn't throw a MockitoException but actually throws a checked Exception as required here) using BDDMockito:

given(someObj.someMethod(stringArg1)).willAnswer( invocation -> { throw new Exception("abc msg"); });

The equivalent for plain Mockito would to use the doAnswer method

Why doesn't [01-12] range work as expected?

This also works:

^([1-9]|[0-1][0-2])$

[1-9] matches single digits between 1 and 9

[0-1][0-2] matches double digits between 10 and 12

There are some good examples here

How do I get a file's directory using the File object?

File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
    dir=filePath.getAbsolutePath();
}
else
{
    dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}

In PHP, how do you change the key of an array element?

There is an alternative way to change the key of an array element when working with a full array - without changing the order of the array. It's simply to copy the array into a new array.

For instance, I was working with a mixed, multi-dimensional array that contained indexed and associative keys - and I wanted to replace the integer keys with their values, without breaking the order.

I did so by switching key/value for all numeric array entries - here: ['0'=>'foo']. Note that the order is intact.

<?php
$arr = [
    'foo',
    'bar'=>'alfa',
    'baz'=>['a'=>'hello', 'b'=>'world'],
];

foreach($arr as $k=>$v) {
    $kk = is_numeric($k) ? $v : $k;
    $vv = is_numeric($k) ? null : $v;
    $arr2[$kk] = $vv;
}

print_r($arr2);

Output:

Array (
    [foo] => 
    [bar] => alfa
    [baz] => Array (
            [a] => hello
            [b] => world
        )
)

javascript functions to show and hide divs

I usually do this with classes, that seems to force the browsers to reassess all the styling.

.hiddendiv {display:none;}
.visiblediv {display:block;}

then use;

<script>  
function show() {  
    document.getElementById('benefits').className='visiblediv';  
}  
function close() {  
    document.getElementById('benefits').className='hiddendiv';  
}    
</script>

Note the casing of "className" that trips me up a lot

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

Virtual/pure virtual explained

Pure Virtual Function

try this code

#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{

public:

    virtual void sayHellow()=0;

};

class anotherClass:aClassWithPureVirtualFunction
{

public:

    void sayHellow()
    {

        cout<<"hellow World";
    }

};
int main()
{
    //aClassWithPureVirtualFunction virtualObject;
    /*
     This not possible to create object of a class that contain pure virtual function
    */
    anotherClass object;
    object.sayHellow();
}

In class anotherClass remove the function sayHellow and run the code. you will get error!Because when a class contain a pure virtual function, no object can be created from that class and it is inherited then its derived class must implement that function.

Virtual function

try another code

#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{

public:

    virtual void sayHellow()
    {
        cout<<"from base\n";
    }

};

class anotherClass:public aClassWithPureVirtualFunction
{

public:

    void sayHellow()
    {

        cout<<"from derived \n";
    }

};
int main()
{
    aClassWithPureVirtualFunction *baseObject=new aClassWithPureVirtualFunction;
    baseObject->sayHellow();///call base one

    baseObject=new anotherClass;
    baseObject->sayHellow();////call the derived one!

}

Here the sayHellow function is marked as virtual in base class.It say the compiler that try searching the function in derived class and implement the function.If not found then execute the base one.Thanks

bootstrap datepicker setDate format dd/mm/yyyy

I have some problems with jquery mobile 1.4.5. For example it seems accepting format change only passing from "option". And there are some refresh problem with the calendar using "option". For all that have the same problems I can suggest this code:

$( "#mydatepicker" ).datepicker( "option", "dateFormat", "dd/mm/yy" );
$( "#mydatepicker" ).datepicker( "setDate", new Date());    
$('.ui-datepicker-calendar').hide();

Facebook share link without JavaScript

Adding to @rybo111's solution, here's what a LinkedIn share would be:

<a href="http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}" target="_blank" class="share-popup">Share on LinkedIn</a>

and add this to your Javascript:

case "www.linkedin.com":
    window_size = "width=570,height=494";
    break;

As per the LinkedIn documentation: https://developer.linkedin.com/docs/share-on-linkedin (See "Customized Url" section)

For anyone who's interested, I used this in a Rails app with a LinkedIn logo, so here's my code if it might help:

<%= link_to image_tag('linkedin.png', size: "50x50"), "http://www.linkedin.com/shareArticle?mini=true&url=#{job_url(@job)}&title=#{full_title(@job.title).html_safe}&summary=#{strip_tags(@job.description)}&source=SOURCE_URL", class: "share-popup" %>

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

How to find pg_config path

path of pg_config in my case (MacOS)

/Library/PostgreSQL/13/bin

Execute the following in the terminal:

PATH="/Library/PostgreSQL/13/bin:$PATH"

Then

pip install psycopg2

Bootstrap dropdown sub menu missing

I make another solution for dropdown. Hope this is helpfull Just add this js script

<script type="text/javascript"> jQuery("document").ready(function() {
  jQuery("ul.dropdown-menu > .dropdown.parent").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    if (jQuery(this).hasClass('open2'))
      jQuery(this).removeClass('open2');
    else {
      jQuery(this).addClass('open2');
    }

  });
}); < /script>

<style type="text/css">.open2{display:block; position:relative;}</style>

How can one use multi threading in PHP applications

You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.

I can't quite remember the php CLI syntax, but you'd want something like:

exec("/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'");

I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.

Javascript - Open a given URL in a new tab by clicking a button

In javascript you can do:

window.open(url, "_blank");

Java better way to delete file if exists

Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.

File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block

Should I use JSLint or JSHint JavaScript validation?

There is an another mature and actively developed "player" on the javascript linting front - ESLint:

ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions:

  • ESLint uses Esprima for JavaScript parsing.
  • ESLint uses an AST to evaluate patterns in code.
  • ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime.

What really matters here is that it is extendable via custom plugins/rules. There are already multiple plugins written for different purposes. Among others, there are:

And, of course, you can use your build tool of choice to run ESLint:

AngularJS check if form is valid in controller

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >{{ formValid = myForm.$valid}}</span>

Here is the full working example:

_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
  $scope.userType = 'guest';_x000D_
  $scope.formValid = false;_x000D_
  console.info('Ctrl init, no form.');_x000D_
  _x000D_
  $scope.$watch('myForm', function() {_x000D_
    console.info('myForm watch');_x000D_
    console.log($scope.formValid);_x000D_
  });_x000D_
  _x000D_
  $scope.isFormValid = function() {_x000D_
    //test the new scope variable_x000D_
    console.log('form valid?: ', $scope.formValid);_x000D_
  };_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
  userType: <input name="input" ng-model="userType" required>_x000D_
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
  <tt>userType = {{userType}}</tt><br>_x000D_
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
  _x000D_
  _x000D_
  /*-- Hidden Variable formValid to use in your controller --*/_x000D_
  <span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
  _x000D_
  _x000D_
  <br/>_x000D_
  <button ng-click="isFormValid()">Check Valid</button>_x000D_
 </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Precision String Format Specifier In Swift

A version of Vincent Guerci's ruby / python % operator, updated for Swift 2.1:

func %(format:String, args:[CVarArgType]) -> String {
  return String(format:format, arguments:args)
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]

RegEx: Grabbing values between quotation marks

Lets see two efficient ways that deal with escaped quotes. These patterns are not designed to be concise nor aesthetic, but to be efficient.

These ways use the first character discrimination to quickly find quotes in the string without the cost of an alternation. (The idea is to discard quickly characters that are not quotes without to test the two branches of the alternation.)

Content between quotes is described with an unrolled loop (instead of a repeated alternation) to be more efficient too: [^"\\]*(?:\\.[^"\\]*)*

Obviously to deal with strings that haven't balanced quotes, you can use possessive quantifiers instead: [^"\\]*+(?:\\.[^"\\]*)*+ or a workaround to emulate them, to prevent too much backtracking. You can choose too that a quoted part can be an opening quote until the next (non-escaped) quote or the end of the string. In this case there is no need to use possessive quantifiers, you only need to make the last quote optional.

Notice: sometimes quotes are not escaped with a backslash but by repeating the quote. In this case the content subpattern looks like this: [^"]*(?:""[^"]*)*

The patterns avoid the use of a capture group and a backreference (I mean something like (["']).....\1) and use a simple alternation but with ["'] at the beginning, in factor.

Perl like:

["'](?:(?<=")[^"\\]*(?s:\\.[^"\\]*)*"|(?<=')[^'\\]*(?s:\\.[^'\\]*)*')

(note that (?s:...) is a syntactic sugar to switch on the dotall/singleline mode inside the non-capturing group. If this syntax is not supported you can easily switch this mode on for all the pattern or replace the dot with [\s\S])

(The way this pattern is written is totally "hand-driven" and doesn't take account of eventual engine internal optimizations)

ECMA script:

(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')

POSIX extended:

"[^"\\]*(\\(.|\n)[^"\\]*)*"|'[^'\\]*(\\(.|\n)[^'\\]*)*'

or simply:

"([^"\\]|\\.|\\\n)*"|'([^'\\]|\\.|\\\n)*'

ReactJS: setTimeout() not working?

Your code scope (this) will be your window object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000) will crash this way.

That comes from javascript not React, it is js closure


So, in order to bind your current react component scope, do this:

setTimeout(function(){this.setState({position: 1})}.bind(this), 3000);

Or if your browser supports es6 or your projs has support to compile es6 to es5, try arrow function as well, as arrow func is to fix 'this' issue:

setTimeout(()=>this.setState({position: 1}), 3000);

How to bundle vendor scripts separately and require them as needed with Webpack?

in my webpack.config.js (Version 1,2,3) file, I have

function isExternal(module) {
  var context = module.context;

  if (typeof context !== 'string') {
    return false;
  }

  return context.indexOf('node_modules') !== -1;
}

in my plugins array

plugins: [
  new CommonsChunkPlugin({
    name: 'vendors',
    minChunks: function(module) {
      return isExternal(module);
    }
  }),
  // Other plugins
]

Now I have a file that only adds 3rd party libs to one file as required.

If you want get more granular where you separate your vendors and entry point files:

plugins: [
  new CommonsChunkPlugin({
    name: 'common',
    minChunks: function(module, count) {
      return !isExternal(module) && count >= 2; // adjustable
    }
  }),
  new CommonsChunkPlugin({
    name: 'vendors',
    chunks: ['common'],
    // or if you have an key value object for your entries
    // chunks: Object.keys(entry).concat('common')
    minChunks: function(module) {
      return isExternal(module);
    }
  })
]

Note that the order of the plugins matters a lot.

Also, this is going to change in version 4. When that's official, I update this answer.

Update: indexOf search change for windows users

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

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.

How to prevent long words from breaking my div?

Re the regex in this comment, it's good, but it adds the shy hyphen only between groups of 5 non-whitespace-or-hyphen chars. That allows the last group be much longer than intended, since there's no matching group after it.

For instance, this:

'abcde12345678901234'.replace(/([^\s-]{5})([^\s-]{5})/g, '$1&shy;$2')

...results in this:

abcde&shy;12345678901234

Here's a version using positive lookahead to avoid that problem:

.replace(/([^\s-]{5})(?=[^\s-])/g, '$1&shy;')

...with this result:

abcde&shy;12345&shy;67890&shy;1234

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Calling performSelector with an NSNumber or other NSValue will not work. Instead of using the value of the NSValue/NSNumber, it will effectively cast the pointer to an int, float, or whatever and use that.

But the solution is simple and obvious. Create the NSInvocation and call

[invocation performSelector:@selector(invoke) withObject:nil afterDelay:delay]

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

Two dimensional array list

A 2d array is simply an array of arrays. The analog for lists is simply a List of Lists.

ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();

I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

I realize that this question is quite old, but I had a similar problem, except my string had spaces included in it. For those that need to know how to separate a string with more than just commas:

string str = "Tom, Scott, Bob";
  IList<string> names = str.Split(new string[] {","," "},
  StringSplitOptions.RemoveEmptyEntries);

The StringSplitOptions removes the records that would only be a space char...

How to align 3 divs (left/center/right) inside another div?

There are several tricks available for aligning the elements.

01. Using Table Trick

_x000D_
_x000D_
.container{_x000D_
  display:table;_x000D_
 }_x000D_
_x000D_
.left{_x000D_
  background:green;_x000D_
  display:table-cell;_x000D_
  width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
  background:gold;_x000D_
  display:table-cell;_x000D_
  width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
  background:gray;_x000D_
  display:table-cell;_x000D_
  width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left">_x000D_
    Left_x000D_
  </div>_x000D_
  <div class="center">_x000D_
    Center_x000D_
  </div>_x000D_
  <div class="right">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

02. Using Flex Trick

_x000D_
_x000D_
.container{_x000D_
  display:flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
   }_x000D_
_x000D_
.left{_x000D_
  background:green;_x000D_
  width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
  background:gold;_x000D_
   width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
  background:gray;_x000D_
   width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left">_x000D_
    Left_x000D_
  </div>_x000D_
  <div class="center">_x000D_
    Center_x000D_
  </div>_x000D_
  <div class="right">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

03. Using Float Trick

_x000D_
_x000D_
.left{_x000D_
  background:green;_x000D_
  width:100px;_x000D_
  float:left;_x000D_
}_x000D_
_x000D_
.center{_x000D_
   background:gold;_x000D_
   width:100px;_x000D_
   float:left;_x000D_
}_x000D_
_x000D_
.right{_x000D_
   background:gray;_x000D_
   width:100px;_x000D_
   float:left;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left">_x000D_
    Left_x000D_
  </div>_x000D_
  <div class="center">_x000D_
    Center_x000D_
  </div>_x000D_
  <div class="right">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery: How to get the HTTP status code from within the $.ajax.error method?

An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.

function checkHttpStatus(url) {     
    $.ajax({
        type: "GET",
        data: {},
        url: url,
        error: function(response) {
            alert(url + " returns a " + response.status);
        }, success() {
            alert(url + " Good link");
        }
    });
}

Firebase onMessageReceived not called when app in background

When message is received and your app is in background the notification is sent to the extras intent of the main activity.

You can check the extra value in the oncreate() or onresume() function of the main activity.

You can check for the fields like data, table etc ( the one specified in the notification)

for example I sent using data as the key

public void onResume(){
    super.onResume();
    if (getIntent().getStringExtra("data")!=null){
            fromnotification=true;
            Intent i = new Intent(MainActivity.this, Activity2.class);
            i.putExtra("notification","notification");
            startActivity(i);
        }

}

How can I create a simple message box in Python?

ctype module with threading

i was using the tkinter messagebox but it would crash my code. i didn't want to find out why so i used the ctypes module instead.

for example:

import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)

i got that code from Arkelis


i liked that it didn't crash the code so i worked on it and added a threading so the code after would run.

example for my code

import ctypes
import threading


def MessageboxThread(buttonstyle, title, text, icon):
    threading.Thread(
        target=lambda: ctypes.windll.user32.MessageBoxW(buttonstyle, text, title, icon)
    ).start()

messagebox(0, "Your title", "Your text", 1)

for button styles and icon numbers:

## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue

## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle

How to pass multiple values to single parameter in stored procedure

I spent time finding a proper way. This may be useful for others.

Create a UDF and refer in the query -

http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm

Angular 2: Get Values of Multiple Checked Checkboxes

  1. I have just simplified little bit for those whose are using list of value Object. XYZ.Comonent.html

    <div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="let option of xyzlist">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option.Id}}"
    
                           (change)="onClicked(option, $event)"/>
                    {{option.Id}}-- {{option.checked}}
                </label>
            </div>
            <button type="submit">Submit</button>
        </div> 
    

    ** XYZ.Component.ts**.

  2. create a list -- xyzlist.

  3. assign values, I am passing values from Java in this list.
  4. Values are Int-Id, boolean -checked (Can Pass in Component.ts).
  5. Now to get value in Componenet.ts.

    xyzlist;//Just created a list
    onClicked(option, event) {
        console.log("event  " + this.xyzlist.length);
        console.log("event  checked" + event.target.checked);
        console.log("event  checked" + event.target.value);
        for (var i = 0; i < this.xyzlist.length; i++) {
            console.log("test --- " + this.xyzlist[i].Id;
            if (this.xyzlist[i].Id == event.target.value) {
                this.xyzlist[i].checked = event.target.checked;
            }
            console.log("after update of checkbox" + this.xyzlist[i].checked);
    
        }
    

How to style a div to be a responsive square?

To achieve what you are looking for you can use the viewport-percentage length vw.

Here is a quick example I made on jsfiddle.

HTML:

<div class="square">
    <h1>This is a Square</h1>
</div>

CSS:

.square {
    background: #000;
    width: 50vw;
    height: 50vw;
}
.square h1 {
    color: #fff;
}

I am sure there are many other ways to do this but this way seemed the best to me.

Java sending and receiving file (byte[]) over sockets

Thanks for the help. I've managed to get it working now so thought I would post so that the others can use to help them.

Server:

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException ex) {
            System.out.println("Can't setup server on this port number. ");
        }

        Socket socket = null;
        InputStream in = null;
        OutputStream out = null;
        
        try {
            socket = serverSocket.accept();
        } catch (IOException ex) {
            System.out.println("Can't accept client connection. ");
        }
        
        try {
            in = socket.getInputStream();
        } catch (IOException ex) {
            System.out.println("Can't get socket input stream. ");
        }

        try {
            out = new FileOutputStream("M:\\test2.xml");
        } catch (FileNotFoundException ex) {
            System.out.println("File not found. ");
        }

        byte[] bytes = new byte[16*1024];

        int count;
        while ((count = in.read(bytes)) > 0) {
            out.write(bytes, 0, count);
        }

        out.close();
        in.close();
        socket.close();
        serverSocket.close();
    }
}

and the Client:

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = null;
        String host = "127.0.0.1";

        socket = new Socket(host, 4444);
        
        File file = new File("M:\\test.xml");
        // Get the size of the file
        long length = file.length();
        byte[] bytes = new byte[16 * 1024];
        InputStream in = new FileInputStream(file);
        OutputStream out = socket.getOutputStream();
        
        int count;
        while ((count = in.read(bytes)) > 0) {
            out.write(bytes, 0, count);
        }

        out.close();
        in.close();
        socket.close();
    }
}

Check status of one port on remote host

Use nc command,

nc -zv <hostname/ip> <port/port range>

For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017

You can also use telnet command

telnet <ip/host> port

How do we download a blob url video

There are a variety of ways to get the URL .m3u8 either by viewing the source of a page, looking at the Network tab in the Developer Tools in Chrome, or using a plugin such as HDL/HLS Video Downloader.

With the .m3u8 URL in hand you can then use ffmpeg to download the video to a file like so:

$ ffmpeg -i 'https://url/to/some/file.m3u8' -bsf:a aac_adtstoasc \
    -vcodec copy -c copy -crf 50 file.mp4

what is the use of xsi:schemaLocation?

If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

I had similar issues when trying to connect to Google's OAuth2 service.

I ended up writing the POST manually, not using WebRequest, like this:

TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");

{
    byte[] contentAsBytes = Encoding.ASCII.GetBytes(content.ToString());

    StringBuilder msg = new StringBuilder();
    msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
    msg.AppendLine("Host: accounts.google.com");
    msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
    msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
    msg.AppendLine("");
    Debug.WriteLine("Request");
    Debug.WriteLine(msg.ToString());
    Debug.WriteLine(content.ToString());

    byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
    sslStream.Write(headerAsBytes);
    sslStream.Write(contentAsBytes);
}

Debug.WriteLine("Response");

StreamReader reader = new StreamReader(sslStream);
while (true)
{  // Print the response line by line to the debug stream for inspection.
    string line = reader.ReadLine();
    if (line == null) break;
    Debug.WriteLine(line);
}

The response that gets written to the response stream contains the specific error text that you're after.

In particular, my problem was that I was putting endlines between url-encoded data pieces. When I took them out, everything worked. You might be able to use a similar technique to connect to your service and read the actual response error text.

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Find the folder containing the shared library libopencv_core.so.2.4 using the following command line.

sudo find / -name "libopencv_core.so.2.4*"

Then I got the result:

 /usr/local/lib/libopencv_core.so.2.4.

Create a file called /etc/ld.so.conf.d/opencv.conf and write to it the path to the folder where the binary is stored.For example, I wrote /usr/local/lib/ to my opencv.conf file. Run the command line as follows.

sudo ldconfig -v

Try to run the command again.

How to find out the number of CPUs using python

These give you the hyperthreaded CPU count

  1. multiprocessing.cpu_count()
  2. os.cpu_count()

These give you the virtual machine CPU count

  1. psutil.cpu_count()
  2. numexpr.detect_number_of_cores()

Only matters if you works on VMs.

How can I select the record with the 2nd highest salary in database Oracle?

You should use something like this:

SELECT *
FROM (select salary2.*, rownum rnum from
         (select * from salary ORDER BY salary_amount DESC) salary2
  where rownum <= 2 )
WHERE rnum >= 2;

Draw a line in a div

Its working for me

_x000D_
_x000D_
 .line{_x000D_
width: 112px;_x000D_
height: 47px;_x000D_
border-bottom: 1px solid black;_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="line"></div>
_x000D_
_x000D_
_x000D_

Simulate user input in bash script

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"

How can I change IIS Express port for a site

.Net Core

For those who got here looking for this configuration in .Net core this resides in the lauchSettings.json. Just edit the port in the property "applicationUrl".

The file should look something like this:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:53950/", //Here
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "environmentVariables": {
        "Hosting:Environment": "Development"
      },
    }
  }
}

Or you can use the GUI by double clicking in the "Properties" of your project.

Note: I had to reopen VS to make it work.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback

https://support.microsoft.com/en-us/help/148652/a-lnk2005-error-occurs-when-the-crt-library-and-mfc-libraries-are-linked-in-the-wrong-order-in-visual-c

https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h

https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html

https://msdn.microsoft.com/en-us/library/y23kc048.aspx

https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/

element not interactable exception in selenium web automation

I'm going to hedge this answer with this: I know it's crap.. and there's got to be a better way. (See above answers) But I tried all the suggestions here and still got nill. Ended up chasing errors, ripping the code to bits. Then I tried this:

import keyboard    
keyboard.press_and_release('tab')
keyboard.press_and_release('tab')
keyboard.press_and_release('tab') #repeat as needed
keyboard.press_and_release('space') 

It's pretty insufferable and you've got to make sure that you don't lose focus otherwise you'll just be tabbing and spacing on the wrong thing.

My assumption on why the other methods didn't work for me is that I'm trying to click on something the developers didn't want a bot clicking on. So I'm not clicking on it!

Insertion Sort vs. Selection Sort

Both algorithms generally works like this

Step 1: take the next unsorted element from the unsorted list then

Step 2: put it in the right place in the sorted list.

One of the steps is easier for one algorithm and vice versa.

Insertion sort: We take the first element of the unsorted list, put it in the sorted list, somewhere. We know where to take the next element (the first position in the unsorted list), but it requires some work to find where to put it (somewhere). Step 1 is easy.

Selection sort: We take the element somewhere from the unsorted list, then put it in the last position of the sorted list. We need to find the next element (it most likely is not in the first position of the unsorted list, but rather, somewhere) then put it right at the end of the sorted list. Step 2 is easy

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

I had the same problem and I solved it as follows:

  1. check the node-sass version used in the current project

  2. go to node-sass release: "https://github.com/sass/node-sass/releases/tag/v@.@.@" (put your node-sass version here)

  3. check the Supported Environment table and see if your Node version exist in it

  4. if it is not, downgrade your node version to the latest version existing in the table

I know it's not the perfect solution but I didn't find anything else in my case.

Adding custom HTTP headers using JavaScript

As already said, the easiest way is to use querystring.

But if you cannot, because of security reason, you should consider using cookies.

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

Apache won't run in xampp

In my case, it was something else. One day earlier I tried to install Magento using bitnami of xampp. And I deleted That Module

I opened the httpd.conf and found this line:

Include "C:/xampp/apps/magento/conf/httpd-prefix.conf"

I just commented it with #,

Now it's running fine. :)

Laravel Migration Change to Make a Column Nullable

Adding to Dmitri Chebotarev's answer, as for Laravel 5+.

After requiring the doctrine/dbal package:

composer require doctrine/dbal

You can then make a migration with nullable columns, like so:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        // change() tells the Schema builder that we are altering a table
        $table->integer('user_id')->unsigned()->nullable()->change();
    });
}

To revert the operation, do:

public function down()
{
    /* turn off foreign key checks for a moment */
    DB::statement('SET FOREIGN_KEY_CHECKS = 0');
    /* set null values to 0 first */
    DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
    /* alter table */
    DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
    /* finally turn foreign key checks back on */
    DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}

What causes a SIGSEGV

There are various causes of segmentation faults, but fundamentally, you are accessing memory incorrectly. This could be caused by dereferencing a null pointer, or by trying to modify readonly memory, or by using a pointer to somewhere that is not mapped into the memory space of your process (that probably means you are trying to use a number as a pointer, or you incremented a pointer too far). On some machines, it is possible for a misaligned access via a pointer to cause the problem too - if you have an odd address and try to read an even number of bytes from it, for example (that can generate SIGBUS, instead).

Setting max width for body using Bootstrap

I don't know if this was pointed out here. The settings for .container width have to be set on the Bootstrap website. I personally did not have to edit or touch anything within CSS files to tune my .container size which is 1600px. Under Customize tab, there are three sections responsible for media and the responsiveness of the web:

  • Media queries breakpoints
  • Grid system
  • Container sizes

Besides Media queries breakpoints, which I believe most people refer to, I've also changed @container-desktop to (1130px + @grid-gutter-width) and @container-large-desktop to (1530px + @grid-gutter-width). Now, the .container changes its width if my browser is scaled up to ~1600px and ~1200px. Hope it can help.

Hiding button using jQuery

It depends on the jQuery selector that you use. Since id should be unique within the DOM, the first one would be simple:

$('#Comanda').hide();

The second one might require something more, depending on the other elements and how to uniquely identify it. If the name of that particular input is unique, then this would work:

$('input[name="Vizualizeaza"]').hide();

How to send POST in angularjs with multiple params?

If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:

Api Controller:

public class ProductController : ApiController
{
    [HttpPost]
    public void Post(Newtonsoft.Json.Linq.JObject data)
    {
        System.Diagnostics.Debugger.Break();

        Product product = data["product"].ToObject<Product>();
        Product product2 = data["product2"].ToObject<Product>();

        int someRandomNumber = data["randomNumber"].ToObject<int>();
        string productName = product.ProductName;
        string product2Name = product2.ProductName;
    }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

View:

<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);
    myApp.controller('controller', function ($scope, $http) {

        $scope.AddProducts = function () {
            var product = {
                ProductID: 0,
                ProductName: "Orange",
            }

            var product2 = {
                ProductID: 1,
                ProductName: "Mango",
            }

            var data = {
                product: product,
                product2: product2,
                randomNumber:12345
            };

            $http.post("/api/Product", data).
            success(function (data, status, headers, config) {
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });
        }
    });
</script>
<div ng-app="app" ng-controller="controller">
    <input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

Custom Authentication in ASP.Net-Core

@Manish Jain, I suggest to implement the method with boolean return:

public class UserManager
{

    // Additional code here...            

    public async Task<bool> SignIn(HttpContext httpContext, UserDbModel user)
    {
        // Additional code here...            

        // Here the real authentication against a DB or Web Services or whatever 
        if (user.Email != null)
            return false;                    

        ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

        // This is for give the authentication cookie to the user when authentication condition was met
        await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        return true;
    }
}

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.

Greyscale Background Css Images

You don't need to use complicated coding really!

Greyscale Hover:

-webkit-filter: grayscale(100%);

Greyscale "Hover-out":

-webkit-filter: grayscale(0%);


I simply made my css class have a separate hover class and added in the second greyscale. It's really simple if you really don't like complexity.

Get response from PHP file using AJAX

in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)

e.g.

<?php
//plum or data...
$output = array("data","plum");

echo json_encode($output);

?>

in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:

 $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                success function(json_data){
                    var data_array = $.parseJSON(json_data);

                    //access your data like this:
                    var plum_or_whatever = data_array['output'];.
                    //continue from here...
                }
            });

CSS selector based on element text?

Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

The boto3 is looking for the credentials in the folder like

C:\ProgramData\Anaconda3\envs\tensorflow\Lib\site-packages\botocore\.aws

You should save two files in this folder credentials and config.

You may want to check out the general order in which boto3 searches for credentials in this link. Look under the Configuring Credentials sub heading.

How do you uninstall the package manager "pip", if installed from source?

If you installed pip like this:

 - sudo apt install python-pip
 - sudo apt install python3-pip

Uninstall them like this:

 - sudo apt remove python-pip
 - sudo apt remove python3-pip

How to SUM and SUBTRACT using SQL?

I'm not sure exactly what you want, but I think it's along the lines of:

SELECT `Item`, `qty`-`BAL_QTY` as `qty` FROM ((SELECT Item, SUM(`QTY`) as qty FROM `master_table` GROUP BY `ITEM`) as A NATURAL JOIN `stock_table`) as B

HttpClient - A task was cancelled?

Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.

SQL Server: Null VS Empty String

There's a nice article here which discusses this point. Key things to take away are that there is no difference in table size, however some users prefer to use an empty string as it can make queries easier as there is not a NULL check to do. You just check if the string is empty. Another thing to note is what NULL means in the context of a relational database. It means that the pointer to the character field is set to 0x00 in the row's header, therefore no data to access.

Update There's a detailed article here which talks about what is actually happening on a row basis

Each row has a null bitmap for columns that allow nulls. If the row in that column is null then a bit in the bitmap is 1 else it's 0.

For variable size datatypes the acctual size is 0 bytes.

For fixed size datatype the acctual size is the default datatype size in bytes set to default value (0 for numbers, '' for chars).

the result of DBCC PAGE shows that both NULL and empty strings both take up zero bytes.

JavaScript validation for empty input field

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  function validateForm() {_x000D_
    var a = document.forms["Form"]["answer_a"].value;_x000D_
    var b = document.forms["Form"]["answer_b"].value;_x000D_
    var c = document.forms["Form"]["answer_c"].value;_x000D_
    var d = document.forms["Form"]["answer_d"].value;_x000D_
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
      alert("Please Fill All Required Field");_x000D_
      return false;_x000D_
    }_x000D_
  }_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Creating stored procedure and SQLite?

SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth

Source : Appropriate Uses For SQLite

When is layoutSubviews called?

Some of the points in BadPirate's answer are only partially true:

  1. For addSubView point

    addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.

    It depends on the view's (target view) autoresize mask. If it has autoresize mask ON, layoutSubview will be called on each addSubview. If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes.

    Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview.

    It is through this technique that the performance of the application also increases.

  2. For the device rotation point

    Rotating a device only calls layoutSubview on the parent view (the responding viewController's primary view)

    This can be true only when your VC is in the VC hierarchy (root at window.rootViewController), well this is most common case. In iOS 5, if you create a VC, but it is not added into any another VC, then this VC would not get any noticed when device rotate. Therefore its view would not get noticed by calling layoutSubviews.

Error in spring application context schema

What I did with spring-data-jpa-1.3 was adding a version to xsd and lowered it to 1.2. Then the error message disappears. Like this

<beans
        xmlns="http://www.springframework.org/schema/beans"
        ...
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    ...
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">

Seems like it was fixed for for 1.2 but then appears again in 1.3.

Cleaning up old remote git branches

This command will "dry run" delete all remote (origin) merged branches, apart from master. You can change that, or, add additional branches after master: grep -v for-example-your-branch-here |

git branch -r --merged | 
  grep origin | 
  grep -v '>' | 
  grep -v master | 
  xargs -L1 | 
  awk '{sub(/origin\//,"");print}'| 
  xargs git push origin --delete --dry-run

If it looks good, remove the --dry-run. Additionally, you may like to test this on a fork first.

Task vs Thread differences

The Thread class is used for creating and manipulating a thread in Windows.

A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

In the days of old (i.e. before TPL) it used to be that using the Thread class was one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool), however this was cumbersome and had several disadvantages, not least of which was the performance overhead of creating a whole new thread to perform a task in the background.

Nowadays using tasks and the TPL is a far better solution 90% of the time as it provides abstractions which allows far more efficient use of system resources. I imagine there are a few scenarios where you want explicit control over the thread on which you are running your code, however generally speaking if you want to run something asynchronously your first port of call should be the TPL.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

on windows I made the iis development certificate trusted by using MMC (start > run > mmc), then add the certificate snapin, choosing "local computer" and accepting the defaults. Once that certificate snapip is added expand the local computer certificate tree to look under Personal, select the localhost certificate, right click > all task > export. accept all defaults in the exporting wizard.

Once that file is saved, expand trusted certificates and begin to import the cert you just exported. https://localhost is now trusted in chrome having no security warnings.

I used this guide resolution #2 from the MSDN blog, the op also shared a link in his question about that also should using MMC but this worked for me. resolution #2

PySpark: withColumn() with two conditions and three outcomes

There are a few efficient ways to implement this. Let's start with required imports:

from pyspark.sql.functions import col, expr, when

You can use Hive IF function inside expr:

new_column_1 = expr(
    """IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)

or when + otherwise:

new_column_2 = when(
    col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)

Finally you could use following trick:

from pyspark.sql.functions import coalesce, lit

new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))

With example data:

df = sc.parallelize([
    ("orange", "apple"), ("kiwi", None), (None, "banana"), 
    ("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])

you can use this as follows:

(df
    .withColumn("new_column_1", new_column_1)
    .withColumn("new_column_2", new_column_2)
    .withColumn("new_column_3", new_column_3))

and the result is:

+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple|           0|           0|           0|
|  kiwi|  null|           3|           3|           3|
|  null|banana|           3|           3|           3|
| mango| mango|           1|           1|           1|
|  null|  null|           3|           3|           3|
+------+------+------------+------------+------------+

What is the difference between const and readonly in C#?

A const is a compile-time constant whereas readonly allows a value to be calculated at run-time and set in the constructor or field initializer. So, a 'const' is always constant but 'readonly' is read-only once it is assigned.

Eric Lippert of the C# team has more information on different types of immutability.

SQL query to select dates between two dates

Really all sql dates should be in yyyy-MM-dd format for the most accurate results.

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case, I was using example from https://hapijs.com/

To fix the problem I replaced

server.connection({ 
    host: 'localhost', 
    port: 8000 
});

with

server.connection({
    port: process.env.PORT || 3000 
});

Changing ViewPager to enable infinite page scrolling

infinite slider adapter skeleton based on previous samples

some critical issues:

  • remember original (relative) position in page view (tag used in sample), so we will look this position to define relative position of view. otherwise child order in pager is mixed
  • have to fill first time absolute view inside adapter. (the rest of times this fill will be invalid) found no way to force it fill from pager handler. the rest times absolute view will be overriden from pager handler with correct values.
  • when pages are slided quickly, side page (actually left) is not filled from pager handler. no workaround for the moment, just use empty view, it will be filled with actual values when drag is stopped. upd: quick workaround: disable adapter's destroyItem.

you may look at the logcat to understand whats happening in this sample

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/calendar_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:padding="5dp"
        android:layout_gravity="center_horizontal"
        android:text="Text Text Text"
    />

</RelativeLayout>

And then:

public class ActivityCalendar extends Activity
{
    public class CalendarAdapter extends PagerAdapter
    {
        @Override
        public int getCount()
        {
            return 3;
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == ((RelativeLayout) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            LayoutInflater inflater = (LayoutInflater)ActivityCalendar.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View viewLayout = inflater.inflate(R.layout.layout_calendar, container, false);
            viewLayout.setTag(new Integer(position));

            //TextView tv = (TextView) viewLayout.findViewById(R.id.calendar_text);
            //tv.setText(String.format("Text Text Text relative: %d", position));

            if (!ActivityCalendar.this.scrolledOnce)
            {
                // fill here only first time, the rest will be overriden in pager scroll handler
                switch (position)
                {
                    case 0:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition - 1);
                        break;
                    case 1:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition);
                        break;
                    case 2:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition + 1);
                        break;
                }
            }

            ((ViewPager) container).addView(viewLayout);

            //Log.i("instantiateItem", String.format("position = %d", position));

            return viewLayout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            ((ViewPager) container).removeView((RelativeLayout) object);

            //Log.i("destroyItem", String.format("position = %d", position));
        }
    }

    public void setPageContent(View viewLayout, int globalPosition)
    {
        if (viewLayout == null)
            return;
        TextView tv = (TextView) viewLayout.findViewById(R.id.calendar_text);
        tv.setText(String.format("Text Text Text global %d", globalPosition));
    }

    private boolean scrolledOnce = false;
    private int focusedPage = 0;
    private int globalPosition = 0;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);

        viewPager.setOnPageChangeListener(new OnPageChangeListener()
        {
            @Override
            public void onPageSelected(int position)
            {
                focusedPage = position;
                // actual page change only when position == 1
                if (position == 1)
                    setTitle(String.format("relative: %d, global: %d", position, globalPosition));
                Log.i("onPageSelected", String.format("focusedPage/position = %d, globalPosition = %d", position, globalPosition));
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {
                //Log.i("onPageScrolled", String.format("position = %d, positionOffset = %f", position, positionOffset));
            }

            @Override
            public void onPageScrollStateChanged(int state)
            {
                Log.i("onPageScrollStateChanged", String.format("state = %d, focusedPage = %d", state, focusedPage));
                if (state == ViewPager.SCROLL_STATE_IDLE)
                {
                    if (focusedPage == 0)
                        globalPosition--;
                    else if (focusedPage == 2)
                        globalPosition++;

                    scrolledOnce = true;

                    for (int i = 0; i < viewPager.getChildCount(); i++)
                    {
                        final View v = viewPager.getChildAt(i);
                        if (v == null)
                            continue;

                        // reveal correct child position
                        Integer tag = (Integer)v.getTag();
                        if (tag == null)
                            continue;

                        switch (tag.intValue())
                        {
                            case 0:
                                setPageContent(v, globalPosition - 1);
                                break;
                            case 1:
                                setPageContent(v, globalPosition);
                                break;
                            case 2:
                                setPageContent(v, globalPosition + 1);
                                break;
                        }
                    }

                    Log.i("onPageScrollStateChanged", String.format("globalPosition = %d", globalPosition));

                    viewPager.setCurrentItem(1, false);
                }
            }
        });

        CalendarAdapter calendarAdapter = this.new CalendarAdapter();
        viewPager.setAdapter(calendarAdapter);

        // center item
        viewPager.setCurrentItem(1, false);
    }
}

Javascript to display the current date and time

_x000D_
_x000D_
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Noon';
  } else {
    hour = 12;
    prepand = ' PM';
  }
}
if (hour === 0 && prepand === ' AM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Midnight';
  } else {
    hour = 12;
    prepand = ' AM';
  }
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
_x000D_
_x000D_
_x000D_

Proper way to declare custom exceptions in modern Python?

see how exceptions work by default if one vs more attributes are used (tracebacks omitted):

>>> raise Exception('bad thing happened')
Exception: bad thing happened

>>> raise Exception('bad thing happened', 'code is broken')
Exception: ('bad thing happened', 'code is broken')

so you might want to have a sort of "exception template", working as an exception itself, in a compatible way:

>>> nastyerr = NastyError('bad thing happened')
>>> raise nastyerr
NastyError: bad thing happened

>>> raise nastyerr()
NastyError: bad thing happened

>>> raise nastyerr('code is broken')
NastyError: ('bad thing happened', 'code is broken')

this can be done easily with this subclass

class ExceptionTemplate(Exception):
    def __call__(self, *args):
        return self.__class__(*(self.args + args))
# ...
class NastyError(ExceptionTemplate): pass

and if you don't like that default tuple-like representation, just add __str__ method to the ExceptionTemplate class, like:

    # ...
    def __str__(self):
        return ': '.join(self.args)

and you'll have

>>> raise nastyerr('code is broken')
NastyError: bad thing happened: code is broken

"getaddrinfo failed", what does that mean?

May be this will help some one. I have my proxy setup in python script but keep getting the error mentioned in the question.

Below is the piece of block which will take my username and password as a constant in the beginning.

   if (use_proxy):
        proxy = req.ProxyHandler({'https': proxy_url})
        auth = req.HTTPBasicAuthHandler()
        opener = req.build_opener(proxy, auth, req.HTTPHandler)
        req.install_opener(opener)

If you are using corporate laptop and if you did not connect to Direct Access or office VPN then the above block will throw error. All you need to do is to connect to your org VPN and then execute your python script.

Thanks

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Creating a jQuery object from a big HTML-string

I use the following for my HTML templates:

$(".main").empty();

var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");

$(".main").append(final.html());

Note: Assuming if you are using jQuery

Getting a list of files in a directory with a glob

Swift 5

This works for cocoa

        let bundleRoot = Bundle.main.bundlePath
        let manager = FileManager.default
        let dirEnum = manager.enumerator(atPath: bundleRoot)


        while let filename = dirEnum?.nextObject() as? String {
            if filename.hasSuffix(".data"){
                print("Files in resource folder: \(filename)")
            }
        }

How many threads can a Java VM support?

Maximum number of threads depends on following things:

  • Hardware Configuration like microprocessor, RAM.
  • Operating System like whether it is 32-bit or 64-bit
  • Code inside the run method. If code inside the run method is huge then single thread object will have more memory requirement
  • Execute Immediate within a stored procedure keeps giving insufficient priviliges error

    Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.

    How to install OpenJDK 11 on Windows?

    AdoptOpenJDK is a new website hosted by the java community. You can find .msi installers for OpenJDK 8 through 14 there, which will perform all the things listed in the question (Unpacking, registry keys, PATH variable updating (and JAVA_HOME), uninstaller...).

    Rounding numbers to 2 digits after comma

    EDIT 2:

    Use the Number object's toFixed method like this:

    var num = Number(0.005) // The Number() only visualizes the type and is not needed
    var roundedString = num.toFixed(2);
    var rounded = Number(roundedString); // toFixed() returns a string (often suitable for printing already)
    

    It rounds 42.0054321 to 42.01

    It rounds 0.005 to 0.01

    It rounds -0.005 to -0.01 (So the absolute value increases on rounding at .5 border)

    jsFiddle example

    Python: convert string to byte array

    Just use a bytearray() which is a list of bytes.

    Python2:

    s = "ABCD"
    b = bytearray()
    b.extend(s)
    

    Python3:

    s = "ABCD"
    b = bytearray()
    b.extend(map(ord, s))
    

    By the way, don't use str as a variable name since that is builtin.

    How do I put variables inside javascript strings?

    var user = "your name";
    var s = 'hello ' + user + ', how are you doing';
    

    Disable color change of anchor tag when visited

    Use:

    a:visited {
        text-decoration: none;
    }
    

    But it will only affect links that haven't been clicked on yet.

    Spring profiles and testing

    public class LoginTest extends BaseTest {
        @Test
        public void exampleTest( ){ 
            // Test
        }
    }
    

    Inherits from a base test class (this example is testng rather than jUnit, but the ActiveProfiles is the same):

    @ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
    @ActiveProfiles(resolver = MyActiveProfileResolver.class)
    public class BaseTest extends AbstractTestNGSpringContextTests { }
    

    MyActiveProfileResolver can contain any logic required to determine which profile to use:

    public class MyActiveProfileResolver implements ActiveProfilesResolver {
        @Override
        public String[] resolve(Class<?> aClass) {
            // This can contain any custom logic to determine which profiles to use
            return new String[] { "exampleProfile" };
        }
    }
    

    This sets the profile which is then used to resolve dependencies required by the test.

    Count distinct values

    You can use this:

    select count(customer) as count, pets
    from table
    group by pets
    

    Print directly from browser without print popup window

    This should work, I tried it by myself and it worked for me. If you pass True instead of false, the print dialog will appear.

    this.print(false);
    

    Write applications in C or C++ for Android?

    There is a plan to allow C/C++ libraries in the next SDK version of Android (Codename Eclair?)To date, it's not possible through the Android Java SDK. However, you can grab the HUGE open source project, roll your own libraries, and then flash your own device...but anyone who wants to use your library will have to flash your custom build as well.

    Remove all child nodes from a parent?

    You can use .empty(), like this:

    $("#foo").empty();
    

    From the docs:

    Remove all child nodes of the set of matched elements from the DOM.

    How to execute only one test spec with angular-cli

    Just small change need in test.ts file inside src folder:

    const context = require.context('./', true, /test-example\.spec\.ts$/);
    

    Here, test-example is the exact file name which we need to run

    In the same way, if you need to test the service file only you can replace the filename like "/test-example.service"

    Re-enabling window.alert in Chrome

    I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536

    Is it possible to ignore one single specific line with Pylint?

    I believe you're looking for...

    import config.logging_settings  # @UnusedImport
    

    Note the double space before the comment to avoid hitting other formatting warnings.

    Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport).

    Ansible playbook shell output

    Expanding on what leucos said in his answer, you can also print information with Ansible's humble debug module:

    - hosts: all
      gather_facts: no
      tasks:
        - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
          register: ps
    
        # Print the shell task's stdout.
        - debug: msg={{ ps.stdout }}
    
        # Print all contents of the shell task's output.
        - debug: var=ps
    

    "Cannot update paths and switch to branch at the same time"

    You could follow these steps when you stumble upon this issue:

    1. Run the following command to list the branches known for your local repository.

    git remote show origin

    which outputs this:

     remote origin
      Fetch URL: <your_git_path>
      Push  URL: <your_git_path>
      HEAD branch: development
      Remote branches:
        development                             tracked
        Feature2                                tracked
        master                                  tracked
        refs/remotes/origin/Feature1         stale (use 'git remote prune' to remove)
      Local branches configured for 'git pull':
        Feature2     merges with remote Feature2
        development  merges with remote development
        master       merges with remote master
      Local refs configured for 'git push':
        Feature2     pushes to Feature2     (up to date)
        development  pushes to development (up to date)
        master       pushes to master      (local out of date)
    
    1. After verifying the details like (fetch URL, etc), run this command to fetch any new branch(i.e. which you may want to checkout in your local repo) that exist in the remote but not in your local.
    » git remote update
    
    Fetching origin
    From gitlab.domain.local:ProjectGroupName/ProjectName
     * [new branch]      Feature3    -> Feature3
    

    As you can see the new branch has been fetched from remote.
    3. Finally, checkout the branch with this command

    » git checkout -b Feature3 origin/Feature3
    
    Branch Feature3 set up to track remote branch Feature3 from origin.
    Switched to a new branch 'Feature3'
    

    It is not necessary to explicitly tell Git to track(using --track) the branch with remote.

    The above command will set the local branch to track the remote branch from origin.

    LINQ equivalent of foreach for IEnumerable<T>

    Fredrik has provided the fix, but it may be worth considering why this isn't in the framework to start with. I believe the idea is that the LINQ query operators should be side-effect-free, fitting in with a reasonably functional way of looking at the world. Clearly ForEach is exactly the opposite - a purely side-effect-based construct.

    That's not to say this is a bad thing to do - just thinking about the philosophical reasons behind the decision.

    Module is not available, misspelled or forgot to load (but I didn't)

    I found this question when I got the same error for a different reason.

    My issue was that my Gulp hadn't picked up on the fact that I had declared a new module and I needed to manually re-run Gulp.

    WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

    In my case in the following environment:

    • Windows 10
    • Python 3.7.5
    • Google Chrome version 80 and corresponding ChromeDriver in the path C:\Windows
    • selenium 3.141.0

    I needed to add the arguments --no-sandbox and --remote-debugging-port=9222 to the ChromeOptions object and run the code as administrator user by lunching the Powershell/cmd as administrator.

    Here is the related piece of code:

    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('--disable-infobars')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--no-sandbox')
    options.add_argument('--remote-debugging-port=9222')
    driver = webdriver.Chrome(options=options)
    

    Which maven dependencies to include for spring 3.0?

    You can add spring-context dependency for spring jars. You will get the following jars along with it.

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    

    Spring context dependencies

    if you also want web components, you can use spring-webmvc dependency.

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    

    Spring webmvc dependencies

    You can use whatever version of that you want. I have used 5.0.5.RELEASE here.

    Looping through a Scripting.Dictionary using index/item number

    According to the documentation of the Item property:

    Sets or returns an item for a specified key in a Dictionary object.

    In your case, you don't have an item whose key is 1 so doing:

    s = d.Item(i)
    

    actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

    The Dictionary also has the Items method which allows looping over the indices:

    a = d.Items
    For i = 0 To d.Count - 1
        s = a(i)
    Next i
    

    AngularJS not detecting Access-Control-Allow-Origin header?

    I experienced this exact same issue. For me, the OPTIONS request would go through, but the POST request would say "aborted." This led me to believe that the browser was never making the POST request at all. Chrome said something like "Caution provisional headers are shown" in the request headers but no response headers were shown. In the end I turned to debugging on Firefox which led me to find out my server was responding with an error and no CORS headers were present on the response. Chrome was actually receiving the response, but not allowing the response to be shown in the network view.

    Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

    In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

    It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

    Open firewall port on CentOS 7

    If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.

    #firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent
    
    #firewall-cmd --reload
    
    
    And check the Port opened or not after reloading the firewall.
    
    
    #firewall-cmd --list-port
    
    
    For other configuration [Linuxwindo.com][1]
    

    android: stretch image in imageview to fit screen

    Trying using :

    imageview.setFitToScreen(true);
    imageview.setScaleType(ScaleType.FIT_CENTER);
    

    This will fit your imageview to the screen with the correct ratio.

    Round integers to the nearest 10

    About the round(..) function returning a float

    That float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)

    See the discussion here for details.

    Build tree array from flat array in javascript

    You can use npm package array-to-tree https://github.com/alferov/array-to-tree. It's convert a plain array of nodes (with pointers to parent nodes) to a nested data structure.

    Solves a problem with conversion of retrieved from a database sets of data to a nested data structure (i.e. navigation tree).

    Usage:

    var arrayToTree = require('array-to-tree');
    
    var dataOne = [
      {
        id: 1,
        name: 'Portfolio',
        parent_id: undefined
      },
      {
        id: 2,
        name: 'Web Development',
        parent_id: 1
      },
      {
        id: 3,
        name: 'Recent Works',
        parent_id: 2
      },
      {
        id: 4,
        name: 'About Me',
        parent_id: undefined
      }
    ];
    
    arrayToTree(dataOne);
    
    /*
     * Output:
     *
     * Portfolio
     *   Web Development
     *     Recent Works
     * About Me
     */
    

    what is this value means 1.845E-07 in excel?

    Highlight the cells, format cells, select Custom then select zero.

    stringstream, string, and char* conversion confusion

    The std::string object returned by ss.str() is a temporary object that will have a life time limited to the expression. So you cannot assign a pointer to a temporary object without getting trash.

    Now, there is one exception: if you use a const reference to get the temporary object, it is legal to use it for a wider life time. For example you should do:

    #include <string>
    #include <sstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        stringstream ss("this is a string\n");
    
        string str(ss.str());
    
        const char* cstr1 = str.c_str();
    
        const std::string& resultstr = ss.str();
        const char* cstr2 = resultstr.c_str();
    
        cout << cstr1       // Prints correctly
            << cstr2;       // No more error : cstr2 points to resultstr memory that is still alive as we used the const reference to keep it for a time.
    
        system("PAUSE");
    
        return 0;
    }
    

    That way you get the string for a longer time.

    Now, you have to know that there is a kind of optimisation called RVO that say that if the compiler see an initialization via a function call and that function return a temporary, it will not do the copy but just make the assigned value be the temporary. That way you don't need to actually use a reference, it's only if you want to be sure that it will not copy that it's necessary. So doing:

     std::string resultstr = ss.str();
     const char* cstr2 = resultstr.c_str();
    

    would be better and simpler.

    Use querystring variables in MVC controller

    I figured it out...finally found another article on it.

    string start = Request.QueryString["start"];
    
    string end = Request.QueryString["end"];
    

    Remove whitespaces inside a string in javascript

    You can use

    "Hello World ".replace(/\s+/g, '');
    

    trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.

    If you change the replacement empty string to '$', the difference becomes much clearer:

    var string= '  Q  W E   R TY ';
    console.log(string.replace(/\s/g, '$'));  // $$Q$$W$E$$$R$TY$
    console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#
    

    Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

    Understanding The Modulus Operator %

    Modulus operator gives you the result in 'reduced residue system'. For example for mod 5 there are 5 integers counted: 0,1,2,3,4. In fact 19=12=5=-2=-9 (mod 7). The main difference that the answer is given by programming languages by 'reduced residue system'.

    How to turn on front flash light programmatically in Android?

    Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.

    It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!

    To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.


    Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.

    Simplest way to wait some asynchronous tasks complete, in Javascript?

    With deferred (another promise/deferred implementation) you can do:

    // Setup 'pdrop', promise version of 'drop' method
    var deferred = require('deferred');
    mongoose.Collection.prototype.pdrop =
        deferred.promisify(mongoose.Collection.prototype.drop);
    
    // Drop collections:
    deferred.map(['aaa','bbb','ccc'], function(name){
        return conn.collection(name).pdrop()(function () {
          console.log("dropped");
        });
    }).end(function () {
        console.log("all dropped");
    }, null);
    

    C++ alignment when printing cout <<

    The ISO C++ standard way to do it is to #include <iomanip> and use io manipulators like std::setw. However, that said, those io manipulators are a real pain to use even for text, and are just about unusable for formatting numbers (I assume you want your dollar amounts to line up on the decimal, have the correct number of significant digits, etc.). Even for just plain text labels, the code will look something like this for the first part of your first line:

    // using standard iomanip facilities
    cout << setw(20) << "Artist"
         << setw(20) << "Title"
         << setw(8) << "Price";
    // ... not going to try to write the numeric formatting...
    

    If you are able to use the Boost libraries, run (don't walk) and use the Boost.Format library instead. It is fully compatible with the standard iostreams, and it gives you all the goodness for easy formatting with printf/Posix formatting string, but without losing any of the power and convenience of iostreams themselves. For example, the first parts of your first two lines would look something like:

    // using Boost.Format
    cout << format("%-20s %-20s %-8s\n")  % "Artist" % "Title" % "Price";
    cout << format("%-20s %-20s %8.2f\n") % "Merle" % "Blue" % 12.99;
    

    Best way to remove from NSMutableArray while iterating?

    this should do it:

        NSMutableArray* myArray = ....;
    
        int i;
        for(i=0; i<[myArray count]; i++) {
            id element = [myArray objectAtIndex:i];
            if(element == ...) {
                [myArray removeObjectAtIndex:i];
                i--;
            }
        }
    

    hope this helps...

    What does API level mean?

    API level is basically the Android version. Instead of using the Android version name (eg 2.0, 2.3, 3.0, etc) an integer number is used. This number is increased with each version. Android 1.6 is API Level 4, Android 2.0 is API Level 5, Android 2.0.1 is API Level 6, and so on.

    Hide html horizontal but not vertical scrollbar

    You can use css like this:

    overflow-y: scroll;
    overflow-x: hidden;
    

    Declaring variables in Excel Cells

    You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:

    = myvar*25
    

    How to pass variable from jade template file to a script file?

    #{} is for escaped string interpolation which automatically escapes the input and is thus more suitable for plain strings rather than JS objects:

    script var data = #{JSON.stringify(data)}
    
    <script>var data = {&quot;foo&quot;:&quot;bar&quot;} </script>
    

    !{} is for unescaped code interpolation, which is more suitable for objects:

    script var data = !{JSON.stringify(data)}
    
    <script>var data = {"foo":"bar"} </script>
    

    CAUTION: Unescaped code can be dangerous. You must be sure to sanitize any user inputs to avoid cross-site scripting (XSS).

    E.g.:

    { foo: 'bar </script><script> alert("xss") //' }
    

    will become:

    <script>var data = {"foo":"bar </script><script> alert("xss") //"}</script>
    

    Possible solution: Use .replace(/<\//g, '<\\/')

    script var data = !{JSON.stringify(data).replace(/<\//g, '<\\/')}
    
    <script>var data = {"foo":"bar<\/script><script>alert(\"xss\")//"}</script>
    

    The idea is to prevent the attacker to:

    1. Break out of the variable: JSON.stringify escapes the quotes
    2. Break out of the script tag: if the variable contents (which you might not be able to control if comes from the database for ex.) has a </script> string, the replace statement will take care of it

    https://github.com/pugjs/pug/blob/355d3dae/examples/dynamicscript.pug

    How to subtract 30 days from the current date using SQL Server

    TRY THIS:

    Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

    SELECT DATEADD(dd, -30, 
           CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
           AS DATETIME))
    

    How to serialize Object to JSON?

    The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library. This blog post gives a quick overview of using the library.

    What is a View in Oracle?

    If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
    See materialized views

    Filter Pyspark dataframe column with None value

    if column = None

    COLUMN_OLD_VALUE
    ----------------
    None
    1
    None
    100
    20
    ------------------
    

    Use create a temptable on data frame:

    sqlContext.sql("select * from tempTable where column_old_value='None' ").show()
    

    So use : column_old_value='None'

    How do I loop through a date range?

    DateTime begindate = Convert.ToDateTime("01/Jan/2018");
    DateTime enddate = Convert.ToDateTime("12 Feb 2018");
     while (begindate < enddate)
     {
        begindate= begindate.AddDays(1);
        Console.WriteLine(begindate + "  " + enddate);
     }
    

    How to read Excel cell having Date with Apache POI?

    Try this code.

    XSSFWorkbook workbook = new XSSFWorkbook(new File(result));
        XSSFSheet sheet = workbook.getSheetAt(0);
    
        // Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            // For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();
    
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    if (cell.getNumericCellValue() != 0) {
                        //Get date
                        Date date = row.getCell(0).getDateCellValue();
    
    
    
                        //Get datetime
                        cell.getDateCellValue()
    
    
                        System.out.println(date.getTime());
                    }
                    break;
                }
            }
        }
    

    Hope is help.

    Solving a "communications link failure" with JDBC and MySQL

    It is majorly because of weak connection between mysql client and remote mysql server.

    In my case it is because of flaky VPN connection.

    How to calculate the sentence similarity using word2vec model of gensim with python

    I have tried the methods provided by the previous answers. It works, but the main drawback of it is that the longer the sentences the larger similarity will be(to calculate the similarity I use the cosine score of the two mean embeddings of any two sentences) since the more the words the more positive semantic effects will be added to the sentence.

    I thought I should change my mind and use the sentence embedding instead as studied in this paper and this.

    How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

    Of course that works; when @item1 = N'', it IS NOT NULL.

    You can define @item1 as NULL by default at the top of your stored procedure, and then not pass in a parameter.

    Change the borderColor of the TextBox

    try this

    bool focus = false;
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        if (focus)
        {
            textBox1.BorderStyle = BorderStyle.None;
            Pen p = new Pen(Color.Red);
            Graphics g = e.Graphics;
            int variance = 3;
            g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height +variance ));
        }
        else
        {
            textBox1.BorderStyle = BorderStyle.FixedSingle;
        }
    }
    
    private void textBox1_Enter(object sender, EventArgs e)
    {
        focus = true;
        this.Refresh();
    }
    
    private void textBox1_Leave(object sender, EventArgs e)
    {
        focus = false;
        this.Refresh();
    }
    

    Eclipse java debugging: source not found

    I had the same issue with eclipse 2019-03 (4.11.0) and I was only able to solve this by doing the debugging via remote debugging instead of directly launching it in debug mode.

    Why would you use String.Equals over ==?

    There is practical difference between string.Equals and ==

    bool result = false;
    
    object obj = "String";    
    string str2 = "String";
    string str3 = typeof(string).Name;
    string str4 = "String";
    object obj2 = str3;
    
    // Comparision between object obj and string str2 -- Com 1
    result = string.Equals(obj, str2);// true
    result = String.ReferenceEquals(obj, str2); // true
    result = (obj == str2);// true
    
    // Comparision between object obj and string str3 -- Com 2
    result = string.Equals(obj, str3);// true
    result = String.ReferenceEquals(obj, str3); // false
    result = (obj == str3);// false
    
    // Comparision between object obj and string str4 -- Com 3
    result = string.Equals(obj, str4);// true
    result = String.ReferenceEquals(obj, str4); // true
    result = (obj == str4);// true
    
    // Comparision between string str2 and string str3 -- Com 4
    result = string.Equals(str2, str3);// true
    result = String.ReferenceEquals(str2, str3); // false
    result = (str2 == str3);// true
    
    // Comparision between string str2 and string str4 -- Com 5
    result = string.Equals(str2, str4);// true
    result = String.ReferenceEquals(str2, str4); // true
    result = (str2 == str4);// true
    
    // Comparision between string str3 and string str4 -- Com 6
    result = string.Equals(str3, str4);// true
    result = String.ReferenceEquals(str3, str4); // false
    result = (str3 == str4);// true
    
    // Comparision between object obj and object obj2 -- Com 7
    result = String.Equals(obj, obj2);// true
    result = String.ReferenceEquals(obj, obj2); // false
    result = (obj == obj2);// false
    

    Adding Watch

    obj     "String" {1#}   object {string}
    str2    "String" {1#}   string
    str3    "String" {5#}   string
    str4    "String" {1#}   string
    obj2    "String" {5#}   object {string}
    

    Now look at {1#} and {5#}

    obj, str2, str4 and obj2 references are same.

    obj and obj2 are object type and others are string type

    Conclusion:

    1. com1: result = (obj == str2);// true
      • compares object and string so performs a reference equality check
      • obj and str2 point to the same reference so the result is true
    2. com2: result = (obj == str3);// false
      • compares object and string so performs a reference equality check
      • obj and str3 point to the different references so the result is false
    3. com3: result = (obj == str4);// true
      • compares object and string so performs a reference equality check
      • obj and str4 point to the same reference so the result is true
    4. com4: result = (str2 == str3);// true
      • compares string and string so performs a string value check
      • str2 and str3 are both "String" so the result is true
    5. com5: result = (str2 == str4);// true
      • compares string and string so performs a string value check
      • str2 and str4 are both "String" so the result is true
    6. com6: result = (str3 == str4);// true
      • compares string and string so performs a string value check
      • str3 and str4 are both "String" so the result is true
    7. com7: result = (obj == obj2);// false  - compares object and object so performs a reference equality check      - obj and obj2 point to the different references so the result is false

    Remove carriage return in Unix

    Once more a solution... Because there's always one more:

    perl -i -pe 's/\r//' filename
    

    It's nice because it's in place and works in every flavor of unix/linux I've worked with.

    Forward host port to docker container

    If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.

    You do not need the -p option in order to expose ports from container to host. By default, all port are exposed. The -p option allows you to expose a port from the container to the outside of the host.

    So, my guess is that you do not need -p at all and it should be working fine :)

    How to select all the columns of a table except one column?

    1. Generate your select query with any good autocomplete editor of your database.
    2. copy and paste your select query in a reserved method (function) and return its ResultSet to your main program or do your stuff in the same method.
    3. call this method each time whenever you require

    Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

    Remember that you will need to connect to running docker container. So you probably want to use tcp instead of unix socket. Check output of docker ps command and look for running mysql containers. If you find one then use mysql command like this: mysql -h 127.0.0.1 -P <mysql_port> (you will find port in docker ps output). If you can't find any running mysql container in docker ps output then try docker images to find mysql image name and try something like this to run it: docker run -d -p 3306:3306 tutum/mysql where "tutum/mysql" is image name found in docker images.