Programs & Examples On #Iphone web app

0

webpack is not recognized as a internal or external command,operable program or batch file

Webpack CLI is now in a separate package and must be installed globally in order to use the 'webpack' command:

npm install -g webpack-cli

EDIT: Much has changed. Webpack folks do not recommend installing the CLI globally (or separately for that matter). This issue should be fixed now but the proper install command is:

npm install --save-dev webpack

This answer was originally intended as a "work-around" for the OPs problem.

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

Invariant Violation: Objects are not valid as a React child

My issue was very particular: in my .env file, I put a comment in the line that had my api url:

API_URL=https://6ec1259f.ngrok.io #comment

I'd get the Invariant violation error when trying to log in/sign up, as the api url was wrong.

How to convert a char array to a string?

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

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

'Invalid update: invalid number of rows in section 0

You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:. So, your code should look like this:

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [currentCart removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

You can also simplify your code a little by using the array creation shortcut @[]:

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

How to Run a jQuery or JavaScript Before Page Start to Load

<head>
  <script>
    if(condition){
      window.location = "http://yournewlocation.com";
    }
  </script>
</head>
<body>
  ...
</body>

This will force the checking of condition and the change in url location before the page renders anything. It is worth noting that you will specifically want to do this before the call to the jQuery library so you can avoid all that library loading. Some might also argue that this would be better placed in a wrapper method and called so here is that method:

function redirectHandler(condition, url){
  if(condition){
    window.location = url;
  }else{
    return false;
  }
}

That would allow you to check multiple conditions and redirect to different locations based on it:

if(redirectHandler(nologgedin, "/login.php")||redirectHandler(adminuser, "/admin.php"));

or if you only need it to run once and only once, but you like having nothing in the global namespace:

(function(condition, url){
  if(condition)window.location=url;
})(!loggedin, "/login.asp");

jQuery Ajax Request inside Ajax Request

This is just an example. You may like to customize it as per your requirement.

 $.ajax({
      url: 'ajax/test1.html',
      success: function(data1) {
        alert('Request 1 was performed.');
        $.ajax({
            type: 'POST',
            url: url,
            data: data1, //pass data1 to second request
            success: successHandler, // handler if second request succeeds 
            dataType: dataType
        });
    }
});

For more details : see this

Convert from lowercase to uppercase all values in all character variables in dataframe

If you need to deal with data.frames that include factors you can use:

df = data.frame(v1=letters[1:5],v2=1:5,v3=letters[10:14],v4=as.factor(letters[1:5]),v5=runif(5),stringsAsFactors=FALSE)

df
    v1 v2 v3 v4        v5
    1  a  1  j  a 0.1774909
    2  b  2  k  b 0.4405019
    3  c  3  l  c 0.7042878
    4  d  4  m  d 0.8829965
    5  e  5  n  e 0.9702505


sapply(df,class)
         v1          v2          v3          v4          v5
"character"   "integer" "character"    "factor"   "numeric"

Use mutate_each_ to convert factors to character then convert all to uppercase

   upper_it = function(X){X %>% mutate_each_( funs(as.character(.)), names( .[sapply(., is.factor)] )) %>%
   mutate_each_( funs(toupper), names( .[sapply(., is.character)] ))}   # convert factor to character then uppercase

Gives

  upper_it(df)
      v1 v2 v3 v4
    1  A  1  J  A
    2  B  2  K  B
    3  C  3  L  C
    4  D  4  M  D
    5  E  5  N  E

While

sapply( upper_it(df),class)
         v1          v2          v3          v4          v5
"character"   "integer" "character" "character"   "numeric"

What’s the best way to reload / refresh an iframe?

A refinement on yajra's post ... I like the thought, but hate the idea of browser detection.

I rather take ppk's view of using object detection instead of browser detection, (http://www.quirksmode.org/js/support.html), because then you're actually testing the capabilities of the browser and acting accordingly, rather than what you think the browser is capable of at that time. Also doesn't require so much ugly browser ID string parsing, and doesn't exclude perfectly capable browsers of which you know nothing about.

So, instead of looking at navigator.AppName, why not do something like this, actually testing for the elements you use? (You could use try {} blocks if you want to get even fancier, but this worked for me.)

function reload_message_frame() {
    var frame_id = 'live_message_frame';
    if(window.document.getElementById(frame_id).location ) {  
        window.document.getElementById(frame_id).location.reload(true);
    } else if (window.document.getElementById(frame_id).contentWindow.location ) {
        window.document.getElementById(frame_id).contentWindow.location.reload(true);
    } else if (window.document.getElementById(frame_id).src){
        window.document.getElementById(frame_id).src = window.document.getElementById(frame_id).src;
    } else {
        // fail condition, respond as appropriate, or do nothing
        alert("Sorry, unable to reload that frame!");
    }
}

This way, you can go try as many different permutations as you like or is necessary, without causing javascript errors, and do something sensible if all else fails. It's a little more work to test for your objects before using them, but, IMO, makes for better and more failsafe code.

Worked for me in IE8, Firefox (15.0.1), Chrome (21.0.1180.89 m), and Opera (12.0.2) on Windows.

Maybe I could do even better by actually testing for the reload function, but that's enough for me right now. :)

How to loop over a Class attributes in Java?

While I agree with Jörn's answer if your class conforms to the JavaBeabs spec, here is a good alternative if it doesn't and you use Spring.

Spring has a class named ReflectionUtils that offers some very powerful functionality, including doWithFields(class, callback), a visitor-style method that lets you iterate over a classes fields using a callback object like this:

public void analyze(Object obj){
    ReflectionUtils.doWithFields(obj.getClass(), field -> {

        System.out.println("Field name: " + field.getName());
        field.setAccessible(true);
        System.out.println("Field value: "+ field.get(obj));

    });
}

But here's a warning: the class is labeled as "for internal use only", which is a pity if you ask me

Store JSON object in data attribute in HTML jQuery

For me it work like that, as I need to store it in template...

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

Iptables setting multiple multiports in one rule

As a workaround to this limitation, I use two rules to cover all the cases.

For example, if I want to allow or deny these 18 ports:

465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666

I use the below rules:

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT

The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.

Read binary file as string in Ruby

on os x these are the same for me... could this maybe be extra "\r" in windows?

in any case you may be better of with:

contents = File.read("e.tgz")
newFile = File.open("ee.tgz", "w")
newFile.write(contents)

Create a shortcut on Desktop

I Use simply for my app:

using IWshRuntimeLibrary; // > Ref > COM > Windows Script Host Object  
...   
private static void CreateShortcut()
    {
        string link = Environment.GetFolderPath( Environment.SpecialFolder.Desktop ) 
            + Path.DirectorySeparatorChar + Application.ProductName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut( link ) as IWshShortcut;
        shortcut.TargetPath = Application.ExecutablePath;
        shortcut.WorkingDirectory = Application.StartupPath;
        //shortcut...
        shortcut.Save();
    }

What's the difference between a Future and a Promise?

According to this discussion, Promise has finally been called CompletableFuture for inclusion in Java 8, and its javadoc explains:

A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.

An example is also given on the list:

f.then((s -> aStringFunction(s)).thenAsync(s -> ...);

Note that the final API is slightly different but allows similar asynchronous execution:

CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

Can Javascript read the source of any web page?

Despite many comments to the contrary I believe that it is possible to overcome the same origin requirement with simple JavaScript.

I am not claiming that the following is original because I believe I saw something similar elsewhere a while ago.

I have only tested this with Safari on a Mac.

The following demonstration fetches the page in the base tag and and moves its innerHTML to a new window. My script adds html tags but with most modern browsers this could be avoided by using outerHTML.

<html>
<head>
<base href='http://apod.nasa.gov/apod/'>
<title>test</title>
<style>
body { margin: 0 }
textarea { outline: none; padding: 2em; width: 100%; height: 100% }
</style>
</head>
<body onload="w=window.open('#'); x=document.getElementById('t'); a='<html>\n'; b='\n</html>'; setTimeout('x.innerHTML=a+w.document.documentElement.innerHTML+b; w.close()',2000)">
<textarea id=t></textarea>
</body>
</html>

Count number of tables in Oracle

Yeah sure your query will work just modify it a little. Look here for refrence : http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2105.htm#i1592091

Run this:

SELECT TABLE_NAME FROM DBA_TABLES;

to get list of tables.

and Run this:

SELECT Count(*) FROM DBA_TABLES;

to get the count of tables.

How to display list items as columns?

This can be done using CSS3 columns quite easily. Here's an example, HTML:

_x000D_
_x000D_
#limheight {_x000D_
    height: 300px; /*your fixed height*/_x000D_
    -webkit-column-count: 3;_x000D_
       -moz-column-count: 3;_x000D_
            column-count: 3; /*3 in those rules is just placeholder -- can be anything*/_x000D_
}_x000D_
_x000D_
#limheight li {_x000D_
    display: inline-block; /*necessary*/_x000D_
}
_x000D_
<ul id = "limheight">_x000D_
 <li><a href="">Glee is awesome 1</a></li>_x000D_
 <li><a href="">Glee is awesome 2</a></li>_x000D_
 <li><a href="">Glee is awesome 3</a></li>_x000D_
 <li><a href="">Glee is awesome 4</a></li>    _x000D_
 <li><a href="">Glee is awesome 5</a></li>_x000D_
 <li><a href="">Glee is awesome 6</a></li>_x000D_
 <li><a href="">Glee is awesome 7</a></li>_x000D_
 <li><a href="">Glee is awesome 8</a></li>_x000D_
 <li><a href="">Glee is awesome 9</a></li>_x000D_
 <li><a href="">Glee is awesome 10</a></li>_x000D_
 <li><a href="">Glee is awesome 11</a></li>_x000D_
 <li><a href="">Glee is awesome 12</a></li>    _x000D_
 <li><a href="">Glee is awesome 13</a></li>_x000D_
 <li><a href="">Glee is awesome 14</a></li>_x000D_
 <li><a href="">Glee is awesome 15</a></li>_x000D_
 <li><a href="">Glee is awesome 16</a></li>_x000D_
 <li><a href="">Glee is awesome 17</a></li>    _x000D_
 <li><a href="">Glee is awesome 18</a></li>_x000D_
 <li><a href="">Glee is awesome 19</a></li>_x000D_
 <li><a href="">Glee is awesome 20</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to get all selected values of a multiple select box?

No jQuery:

// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}

Quick example:

<select multiple>
  <option>opt 1 text
  <option value="opt 2 value">opt 2 text
</select>
<button onclick="
  var el = document.getElementsByTagName('select')[0];
  alert(getSelectValues(el));
">Show selected values</button>

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

If you don't want to use regex then you can use this function which will replace all in a string

Source Code:

function ReplaceAll(mystring, search_word, replace_with) 
{
    while (mystring.includes(search_word))
    {
        mystring = mystring.replace(search_word, replace_with);
    }

    return mystring;  
}

How to use:

var mystring = ReplaceAll("Test Test", "Test", "Hello"); 

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

This is very simple, you just need to add a background image to the select element and position it where you need to, but don't forget to add:

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

According to http://shouldiprefix.com/#appearance

Microsoft Edge and IE mobile support this property with the -webkit- prefix rather than -ms- for interop reasons.

I just made this fiddle http://jsfiddle.net/drjorgepolanco/uxxvayqe/

Maven Install on Mac OS X

% sudo port selfupdate; 
% sudo port upgrade outdated;
% sudo port install maven3;
% sudo port select --set maven maven3;

— add following to .zshenv -- start using zsh if you dont —
set -a
[[ -d /opt/local/share/java/maven3 ]] &&
    M3_HOME=/opt/local/share/java/maven3 &&
    M2_HOME=/opt/local/share/java/maven3 &&
    MAVEN_OPTS="-Xmx1024m" &&
    M2=${M2_HOME}/bin
set +a

How to search a specific value in all tables (PostgreSQL)?

Without storing a new procedure you can use a code block and execute to obtain a table of occurences. You can filter results by schema, table or column name.

DO $$
DECLARE
  value int := 0;
  sql text := 'The constructed select statement';
  rec1 record;
  rec2 record;
BEGIN
  DROP TABLE IF EXISTS _x;
  CREATE TEMPORARY TABLE _x (
    schema_name text, 
    table_name text, 
    column_name text,
    found text
  );
  FOR rec1 IN 
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns 
        WHERE table_name <> '_x'
                AND UPPER(column_name) LIKE UPPER('%%')                  
                AND table_schema <> 'pg_catalog'
                AND table_schema <> 'information_schema'
                AND data_type IN ('character varying', 'text', 'character', 'char', 'varchar')
        LOOP
    sql := concat('SELECT ', rec1."column_name", ' AS "found" FROM ',rec1."table_schema" , '.',rec1."table_name" , ' WHERE UPPER(',rec1."column_name" , ') LIKE UPPER(''','%my_substring_to_find_goes_here%' , ''')');
    RAISE NOTICE '%', sql;
    BEGIN
        FOR rec2 IN EXECUTE sql LOOP
            RAISE NOTICE '%', sql;
            INSERT INTO _x VALUES (rec1."table_schema", rec1."table_name", rec1."column_name", rec2."found");
        END LOOP;
    EXCEPTION WHEN OTHERS THEN
    END;
  END LOOP;
  END; $$;

SELECT * FROM _x;

Returning multiple values from a C++ function

I would just do it by reference if it's only a few return values but for more complex types you can also just do it like this :

static struct SomeReturnType {int a,b,c; string str;} SomeFunction()
{
  return {1,2,3,string("hello world")}; // make sure you return values in the right order!
}

use "static" to limit the scope of the return type to this compilation unit if it's only meant to be a temporary return type.

 SomeReturnType st = SomeFunction();
 cout << "a "   << st.a << endl;
 cout << "b "   << st.b << endl;
 cout << "c "   << st.c << endl;
 cout << "str " << st.str << endl;

This is definitely not the prettiest way to do it but it will work.

Mean Squared Error in Numpy?

Another alternative to the accepted answer that avoids any issues with matrix multiplication:

 def MSE(Y, YH):
     return np.square(Y - YH).mean()

From the documents for np.square: "Return the element-wise square of the input."

require_once :failed to open stream: no such file or directory

set_include_path(get_include_path() . $_SERVER["DOCUMENT_ROOT"] . "/mysite/php/includes/");

Also this can help.See set_include_path()

Python - Move and overwrite files and folders

This will go through the source directory, create any directories that do not already exist in destination directory, and move files from source to the destination directory:

import os
import shutil

root_src_dir = 'Src Directory\\'
root_dst_dir = 'Dst Directory\\'

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            # in case of the src and dst are the same file
            if os.path.samefile(src_file, dst_file):
                continue
            os.remove(dst_file)
        shutil.move(src_file, dst_dir)

Any pre-existing files will be removed first (via os.remove) before being replace by the corresponding source file. Any files or directories that already exist in the destination but not in the source will remain untouched.

How do I apply a perspective transform to a UIView?

You can get accurate Carousel effect using iCarousel SDK.

You can get an instant Cover Flow effect on iOS by using the marvelous and free iCarousel library. You can download it from https://github.com/nicklockwood/iCarousel and drop it into your Xcode project fairly easily by adding a bridging header (it's written in Objective-C).

If you haven't added Objective-C code to a Swift project before, follow these steps:

  • Download iCarousel and unzip it
  • Go into the folder you unzipped, open its iCarousel subfolder, then select iCarousel.h and iCarousel.m and drag them into your project navigation – that's the left pane in Xcode. Just below Info.plist is fine.
  • Check "Copy items if needed" then click Finish.
  • Xcode will prompt you with the message "Would you like to configure an Objective-C bridging header?" Click "Create Bridging Header" You should see a new file in your project, named YourProjectName-Bridging-Header.h.
  • Add this line to the file: #import "iCarousel.h"
  • Once you've added iCarousel to your project you can start using it.
  • Make sure you conform to both the iCarouselDelegate and iCarouselDataSource protocols.

Swift 3 Sample Code:

    override func viewDidLoad() {
      super.viewDidLoad()
      let carousel = iCarousel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
      carousel.dataSource = self
      carousel.type = .coverFlow
      view.addSubview(carousel) 
    }

   func numberOfItems(in carousel: iCarousel) -> Int {
        return 10
    }

    func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
        let imageView: UIImageView

        if view != nil {
            imageView = view as! UIImageView
        } else {
            imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128))
        }

        imageView.image = UIImage(named: "example")

        return imageView
    }

jQuery AJAX Call to PHP Script with JSON Return

Make it dataType instead of datatype.

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

When do you use POST and when do you use GET?

Well one major thing is anything you submit over GET is going to be exposed via the URL. Secondly as Ceejayoz says, there is a limit on characters for a URL.

Draw on HTML5 Canvas using a mouse

Here is a working sample.

_x000D_
_x000D_
 <html>_x000D_
    <script type="text/javascript">_x000D_
    var canvas, ctx, flag = false,_x000D_
        prevX = 0,_x000D_
        currX = 0,_x000D_
        prevY = 0,_x000D_
        currY = 0,_x000D_
        dot_flag = false;_x000D_
_x000D_
    var x = "black",_x000D_
        y = 2;_x000D_
    _x000D_
    function init() {_x000D_
        canvas = document.getElementById('can');_x000D_
        ctx = canvas.getContext("2d");_x000D_
        w = canvas.width;_x000D_
        h = canvas.height;_x000D_
    _x000D_
        canvas.addEventListener("mousemove", function (e) {_x000D_
            findxy('move', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mousedown", function (e) {_x000D_
            findxy('down', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mouseup", function (e) {_x000D_
            findxy('up', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mouseout", function (e) {_x000D_
            findxy('out', e)_x000D_
        }, false);_x000D_
    }_x000D_
    _x000D_
    function color(obj) {_x000D_
        switch (obj.id) {_x000D_
            case "green":_x000D_
                x = "green";_x000D_
                break;_x000D_
            case "blue":_x000D_
                x = "blue";_x000D_
                break;_x000D_
            case "red":_x000D_
                x = "red";_x000D_
                break;_x000D_
            case "yellow":_x000D_
                x = "yellow";_x000D_
                break;_x000D_
            case "orange":_x000D_
                x = "orange";_x000D_
                break;_x000D_
            case "black":_x000D_
                x = "black";_x000D_
                break;_x000D_
            case "white":_x000D_
                x = "white";_x000D_
                break;_x000D_
        }_x000D_
        if (x == "white") y = 14;_x000D_
        else y = 2;_x000D_
    _x000D_
    }_x000D_
    _x000D_
    function draw() {_x000D_
        ctx.beginPath();_x000D_
        ctx.moveTo(prevX, prevY);_x000D_
        ctx.lineTo(currX, currY);_x000D_
        ctx.strokeStyle = x;_x000D_
        ctx.lineWidth = y;_x000D_
        ctx.stroke();_x000D_
        ctx.closePath();_x000D_
    }_x000D_
    _x000D_
    function erase() {_x000D_
        var m = confirm("Want to clear");_x000D_
        if (m) {_x000D_
            ctx.clearRect(0, 0, w, h);_x000D_
            document.getElementById("canvasimg").style.display = "none";_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    function save() {_x000D_
        document.getElementById("canvasimg").style.border = "2px solid";_x000D_
        var dataURL = canvas.toDataURL();_x000D_
        document.getElementById("canvasimg").src = dataURL;_x000D_
        document.getElementById("canvasimg").style.display = "inline";_x000D_
    }_x000D_
    _x000D_
    function findxy(res, e) {_x000D_
        if (res == 'down') {_x000D_
            prevX = currX;_x000D_
            prevY = currY;_x000D_
            currX = e.clientX - canvas.offsetLeft;_x000D_
            currY = e.clientY - canvas.offsetTop;_x000D_
    _x000D_
            flag = true;_x000D_
            dot_flag = true;_x000D_
            if (dot_flag) {_x000D_
                ctx.beginPath();_x000D_
                ctx.fillStyle = x;_x000D_
                ctx.fillRect(currX, currY, 2, 2);_x000D_
                ctx.closePath();_x000D_
                dot_flag = false;_x000D_
            }_x000D_
        }_x000D_
        if (res == 'up' || res == "out") {_x000D_
            flag = false;_x000D_
        }_x000D_
        if (res == 'move') {_x000D_
            if (flag) {_x000D_
                prevX = currX;_x000D_
                prevY = currY;_x000D_
                currX = e.clientX - canvas.offsetLeft;_x000D_
                currY = e.clientY - canvas.offsetTop;_x000D_
                draw();_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
    </script>_x000D_
    <body onload="init()">_x000D_
        <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>_x000D_
        <div style="position:absolute;top:12%;left:43%;">Choose Color</div>_x000D_
        <div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:20%;left:43%;">Eraser</div>_x000D_
        <div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>_x000D_
        <img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">_x000D_
        <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">_x000D_
        <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

How to correctly set Http Request Header in Angular 2

This should be easily resolved by importing headers from Angular:

import { Http, Headers } from "@angular/http";

What is a segmentation fault?

A segmentation fault is caused by a request for a page that the process does not have listed in its descriptor table, or an invalid request for a page that it does have listed (e.g. a write request on a read-only page).

A dangling pointer is a pointer that may or may not point to a valid page, but does point to an "unexpected" segment of memory.

Android REST client, Sample?

"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.

The only reference implementation I know (please comment if you know more) is available at Datadroid (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.

The second link asks for the "best" REST framework, which is discussed heavily on stackoverflow. For me the application size is important, followed by the performance of the implementation.

  • Normally I use the plain org.json implemantation, which is part of Android since API level 1 and therefore does not increase application size.
  • For me very interesting was the information found on JSON parsers performance in the comments: as of Android 3.0 Honeycomb, GSON's streaming parser is included as android.util.JsonReader. Unfortunately, the comments aren't available any more.
  • Spring Android (which I use sometimes) supports Jackson and GSON. The Spring Android RestTemplate Module documentation points to a sample app.

Therefore I stick to org.json or GSON for complexer scenarios. For the architecture of an org.json implementation, I am using a static class which represents the server use cases (e.g. findPerson, getPerson). I call this functionality from a service and use utility classes which are doing the mapping (project specific) and the network IO (my own REST template for plain GET or POST). I try to avoid the usage of reflection.

How can I convert a .py to .exe for Python?

There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

GUI:

Auto Py to Exe

Output:

Output

Checking if a variable exists in javascript

if (variable) can be used if variable is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).

typeof variable == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property. This check will not throw and error is variable is not declared.

When is a CDATA section necessary within a script tag?

It to ensure that XHTML validation works correctly when you have JavaScript embedded in your page, rather than externally referenced.

XHTML requires that your page strictly conform to XML markup requirements. Since JavaScript may contain characters with special meaning, you must wrap it in CDATA to ensure that validation does not flag it as malformed.

With HTML pages on the web you can just include the required JavaScript between and tags. When you validate the HTML on your web page the JavaScript content is considered to be CDATA (character data) that is therefore ignored by the validator. The same is not true if you follow the more recent XHTML standards in setting up your web page. With XHTML the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator.

Because of this, you can't just include JavaScript between the script tags on your page without 'breaking' your web page (at least as far as the validator is concerned).

You can learn more about CDATA here, and more about XHTML here.

Simple 3x3 matrix inverse code (C++)

Don't try to do this yourself if you're serious about getting edge cases right. So while they many naive/simple methods are theoretically exact, they can have nasty numerical behavior for nearly singular matrices. In particular you can get cancelation/round-off errors that cause you to get arbitrarily bad results.

A "correct" way is Gaussian elimination with row and column pivoting so that you're always dividing by the largest remaining numerical value. (This is also stable for NxN matrices.). Note that row pivoting alone doesn't catch all the bad cases.

However IMO implementing this right and fast is not worth your time - use a well tested library and there are a heap of header only ones.

Fetch API with Cookie

This works for me:

import Cookies from 'universal-cookie';
const cookies = new Cookies();

function headers(set_cookie=false) {
  let headers = {
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
    headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}

Then build your call:

export function fetchTests(user_id) {
  return function (dispatch) {
   let data = {
    method:      'POST',
    credentials: 'same-origin',
    mode:        'same-origin',
    body:        JSON.stringify({
                     user_id: user_id
                }),
    headers:     headers(true)
   };
   return fetch('/api/v1/tests/listing/', data)
      .then(response => response.json())
      .then(json => dispatch(receiveTests(json)));
    };
  }

What is dtype('O'), in pandas?

It means "a python object", i.e. not one of the builtin scalar types supported by numpy.

np.array([object()]).dtype
=> dtype('O')

How to use an array list in Java?

Java 8 introduced default implementation of forEach() inside the Iterable interface , you can easily do it by declarative approach .

  List<String> values = Arrays.asList("Yasir","Shabbir","Choudhary");

  values.forEach( value -> System.out.println(value));

Here is the code of Iterable interface

  default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

Reference

How to return a specific status code and no contents from Controller?

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

How to replace multiple strings in a file using PowerShell

To get the post by George Howarth working properly with more than one replacement you need to remove the break, assign the output to a variable ($line) and then output the variable:

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'
}

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line = $line -replace $_.Key, $_.Value
        }
    }
   $line
} | Set-Content -Path $destination_file

Android Dialog: Removing title bar

use,

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //before     
dialog.setContentView(R.layout.logindialog);

C# Parsing JSON array of objects

string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";

                  string jsonData = jsonData1.Replace("\"", "");


                  DataSet ds = new DataSet();
                  DataTable dt = new DataTable();
       JArray array= JArray.Parse(jsonData);

couldnot parse , if the vaule is a string..

look at name : meals , if name : 1 then it will parse

Run php function on button click

Do this:

<input type="button" name="test" id="test" value="RUN" /><br/>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}
if(array_key_exists('test',$_POST)){
   testfun();
}
?>

pod install -bash: pod: command not found

The best solution for Big Sur is posted on Redit by _fgmx

Go into Xcode 12 preferences Click locations Select Xcode 12 for Developer tools/command line tools Install cocoapods for Xcode 12: sudo gem install cocoapods

How to override a JavaScript function

You can do it like this:

alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'

Check out a working example here: http://jsfiddle.net/LtjzW/1/

Postgres: SQL to list table foreign keys

This is what I'm currently using, it will list a table and it's fkey constraints [remove table clause and it will list all tables in current catalog]:

SELECT

    current_schema() AS "schema",
    current_catalog AS "database",
    "pg_constraint".conrelid::regclass::text AS "primary_table_name",
    "pg_constraint".confrelid::regclass::text AS "foreign_table_name",

    (
        string_to_array(
            (
                string_to_array(
                    pg_get_constraintdef("pg_constraint".oid),
                    '('
                )
            )[2],
            ')'
        )
    )[1] AS "foreign_column_name",

    "pg_constraint".conindid::regclass::text AS "constraint_name",

    TRIM((
        string_to_array(
            pg_get_constraintdef("pg_constraint".oid),
            '('
        )
    )[1]) AS "constraint_type",

    pg_get_constraintdef("pg_constraint".oid) AS "constraint_definition"

FROM pg_constraint AS "pg_constraint"

JOIN pg_namespace AS "pg_namespace" ON "pg_namespace".oid = "pg_constraint".connamespace

WHERE
    --fkey and pkey constraints
    "pg_constraint".contype IN ( 'f', 'p' )
    AND
    "pg_namespace".nspname = current_schema()
    AND
    "pg_constraint".conrelid::regclass::text IN ('whatever_table_name')

java.lang.OutOfMemoryError: Java heap space in Maven

I have solved this problem on my side by 2 ways:

  1. Adding this configuration in pom.xml

    <configuration><argLine>-Xmx1024m</argLine></configuration>
    
  2. Switch to used JDK 1.7 instead of 1.6

Regular Expression to match valid dates

I know this does not answer your question, but why don't you use a date handling routine to check if it's a valid date? Even if you modify the regexp with a negative lookahead assertion like (?!31/0?2) (ie, do not match 31/2 or 31/02) you'll still have the problem of accepting 29 02 on non leap years and about a single separator date format.

The problem is not easy if you want to really validate a date, check this forum thread.

For an example or a better way, in C#, check this link

If you are using another platform/language, let us know

possibly undefined macro: AC_MSG_ERROR

I had similar issues when trying to build amtk and utthpmock with jhbuild.

I needed to install the most recent version of autoconf-archive. Instructions are at https://github.com/autoconf-archive/autoconf-archive/blob/master/README-maint. I did an additional sudo make install at the end.

The last step was to update my ACLOCAL_PATH:

echo 'export ACLOCAL_PATH=$ACLOCAL_PATH:/usr/local/share/aclocal' >> ~/.bashrc

After a source ~/.bashrc, all the macros were finally found and the builds succeeded.

Jersey stopped working with InjectionManagerFactory not found

Here is the reason. Starting from Jersey 2.26, Jersey removed HK2 as a hard dependency. It created an SPI as a facade for the dependency injection provider, in the form of the InjectionManager and InjectionManagerFactory. So for Jersey to run, we need to have an implementation of the InjectionManagerFactory. There are two implementations of this, which are for HK2 and CDI. The HK2 dependency is the jersey-hk2 others are talking about.

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.26</version>
</dependency>

The CDI dependency is

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-cdi2-se</artifactId>
    <version>2.26</version>
</dependency>

This (jersey-cdi2-se) should only be used for SE environments and not EE environments.

Jersey made this change to allow others to provide their own dependency injection framework. They don't have any plans to implement any other InjectionManagers, though others have made attempts at implementing one for Guice.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.

Ternary:

$something = isset($_GET['something']) ? $_GET['something'] : "failed";

If-else:

if (isset($_GET['something'])) {
    $something = $_GET['something'];
} else {
    $something = "failed";
}

How do I write to the console from a Laravel Controller?

For better explain Dave Morrissey's answer I have made these steps for wrap with Console Output class in a laravel facade.

1) Create a Facade in your prefer folder (in my case app\Facades):

class ConsoleOutput extends Facade {

 protected static function getFacadeAccessor() { 
     return 'consoleOutput';
 }

}

2) Register a new Service Provider in app\Providers as follow:

class ConsoleOutputServiceProvider extends ServiceProvider
{

 public function register(){
    App::bind('consoleOutput', function(){
        return new \Symfony\Component\Console\Output\ConsoleOutput();
     });
 }

}

3) Add all this stuffs in config\app.php file, registering the provider and alias.

 'providers' => [
   //other providers
    App\Providers\ConsoleOutputServiceProvider::class
 ],
 'aliases' => [
  //other aliases
   'ConsoleOutput' => App\Facades\ConsoleOutput::class,
 ],

That's it, now in any place of your Laravel application, just call your method in this way:

ConsoleOutput::writeln('hello');

Hope this help you.

How to make lists contain only distinct element in Python?

The characteristics of sets in Python are that the data items in a set are unordered and duplicates are not allowed. If you try to add a data item to a set that already contains the data item, Python simply ignores it.

>>> l = ['a', 'a', 'bb', 'b', 'c', 'c', '10', '10', '8','8', 10, 10, 6, 10, 11.2, 11.2, 11, 11]
>>> distinct_l = set(l)
>>> print(distinct_l)
set(['a', '10', 'c', 'b', 6, 'bb', 10, 11, 11.2, '8'])

Remove items from one list in another

In my case I had two different lists, with a common identifier, kind of like a foreign key. The second solution cited by "nzrytmn":

var result =  list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();

Was the one that best fit in my situation. I needed to load a DropDownList without the records that had already been registered.

Thank you !!!

This is my code:

t1 = new T1();
t2 = new T2();

List<T1> list1 = t1.getList();
List<T2> list2 = t2.getList();

ddlT3.DataSource= list2.Where(s => !list1.Any(p => p.Id == s.ID)).ToList();
ddlT3.DataTextField = "AnyThing";
ddlT3.DataValueField = "IdAnyThing";
ddlT3.DataBind();

How to concatenate two strings to build a complete path

The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):

shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
  echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done

The output of which is:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir

The shopt -s extglob is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:

echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR

which would result in the less neat but still working:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

How can I pass command-line arguments to a Perl program?

If you just want some values, you can just use the @ARGV array. But if you are looking for something more powerful in order to do some command line options processing, you should use Getopt::Long.

How to open .dll files to see what is written inside?

I think you have downloaded the .NET Reflector & this FileGenerator plugin http://filegenreflector.codeplex.com/ , If you do,

  1. Open up the Reflector.exe,

  2. Go to View and click Add-Ins,

  3. In the Add-Ins window click Add...,

  4. Then find the dll you have downloaded

  5. FileGenerator.dll (witch came wth the FileGenerator plugin),

  6. Then close the Add-Ins window.

  7. Go to File and click Open and choose the dll that you want to decompile,

  8. After you have opend it, it will appear in the tree view,

  9. Go to Tools and click Generate Files(Crtl+Shift+G),

  10. select the output directory and select appropriate settings as your wish, Click generate files.

OR

use http://ilspy.net/

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

How to convert a normal Git repository to a bare one?

Simply read

Pro Git Book: 4.2 Git on the Server - Getting Git on a Server

which boild down to

$ git clone --bare my_project my_project.git
Cloning into bare repository 'my_project.git'...
done.

Then put my_project.git to the server

Which mainly is, what answer #42 tried to point out. Shurely one could reinvent the wheel ;-)

mysqldump exports only one table

try this. There are in general three ways to use mysqldump—

in order to dump a set of one or more tables,

shell> mysqldump [options] db_name [tbl_name ...]

a set of one or more complete databases

shell> mysqldump [options] --databases db_name ...

or an entire MySQL server—as shown here:

shell> mysqldump [options] --all-databases

mysqldump data only

This should work:

# To export to file (data only)
mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql

# To export to file (structure only)
mysqldump -u [user] -p[pass] --no-data mydb > mydb.sql

# To import to database
mysql -u [user] -p[pass] mydb < mydb.sql

NOTE: there's no space between -p & [pass]

Iterating through struct fieldnames in MATLAB

You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.

>> signal
signal = 
sin: {{1x1x25 cell}  {1x1x25 cell}}
cos: {{1x1x25 cell}  {1x1x25 cell}}

>> each(fieldnames(signal))
ans = 
CellIterator with properties:

NumberOfIterations: 2.0000e+000

Usage:

for bridge = each(fieldnames(signal))
   signal.(bridge) = rand(10);
end

I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.

In Python, is there an elegant way to print a list in a custom format without explicit looping?

l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])

What is the difference between AF_INET and PF_INET in socket programming?

I found in Linux kernel source code that PF_INET and AF_INET are the same. The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.

/* Protocol families, same as address families. */
...
#define PF_INET     AF_INET

How to convert map to url query string?

Another 'one class'/no dependency way of doing it, handling single/multiple:

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class UrlQueryString {
  private static final String DEFAULT_ENCODING = "UTF-8";

  public static String buildQueryString(final LinkedHashMap<String, Object> map) {
    try {
      final Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      while (it.hasNext()) {
        final Map.Entry<String, Object> entry = it.next();
        final String key = entry.getKey();
        if (key != null) {
          sb.append(URLEncoder.encode(key, DEFAULT_ENCODING));
          sb.append('=');
          final Object value = entry.getValue();
          final String valueAsString = value != null ? URLEncoder.encode(value.toString(), DEFAULT_ENCODING) : "";
          sb.append(valueAsString);
          if (it.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static String buildQueryStringMulti(final LinkedHashMap<String, List<Object>> map) {
    try {
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      for (final Iterator<Entry<String, List<Object>>> mapIterator = map.entrySet().iterator(); mapIterator.hasNext();) {
        final Entry<String, List<Object>> entry = mapIterator.next();
        final String key = entry.getKey();
        if (key != null) {
          final String keyEncoded = URLEncoder.encode(key, DEFAULT_ENCODING);
          final List<Object> values = entry.getValue();
          sb.append(keyEncoded);
          sb.append('=');
          if (values != null) {
            for (final Iterator<Object> listIt = values.iterator(); listIt.hasNext();) {
              final Object valueObject = listIt.next();
              sb.append(valueObject != null ? URLEncoder.encode(valueObject.toString(), DEFAULT_ENCODING) : "");
              if (listIt.hasNext()) {
                sb.append('&');
                sb.append(keyEncoded);
                sb.append('=');
              }
            }
          }
          if (mapIterator.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static void main(final String[] args) {
    // Examples: could be turned into unit tests ...
    {
      final LinkedHashMap<String, Object> queryItems = new LinkedHashMap<String, Object>();
      queryItems.put("brand", "C&A");
      queryItems.put("count", null);
      queryItems.put("misc", 42);
      final String buildQueryString = buildQueryString(queryItems);
      System.out.println(buildQueryString);
    }
    {
      final LinkedHashMap<String, List<Object>> queryItems = new LinkedHashMap<String, List<Object>>();
      queryItems.put("usernames", new ArrayList<Object>(Arrays.asList(new String[] { "bob", "john" })));
      queryItems.put("nullValue", null);
      queryItems.put("misc", new ArrayList<Object>(Arrays.asList(new Integer[] { 1, 2, 3 })));
      final String buildQueryString = buildQueryStringMulti(queryItems);
      System.out.println(buildQueryString);
    }
  }
}

You may use either simple (easier to write in most cases) or multiple when required. Note that both can be combined by adding an ampersand... If you find any problems let me know in the comments.

Rails - controller action name to string

I just did the same. I did it in helper controller, my code is:

def get_controller_name
  controller_name    
end


def get_action_name
  action_name   
end

These methods will return current contoller and action name. Hope it helps

How to stick text to the bottom of the page?

Try:

.bottom {
    position: fixed;
    bottom: 0;
}

spacing between form fields

  <form>     
            <div class="form-group">
                <label for="nameLabel">Name</label>
                <input id="name" name="name" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="PhoneLabel">Phone</label>
                <input id="phone" name="phone" class="form-control" type="text" /> 
            </div>
            <div class="form-group">
                <label for="yearLabel">Year</label>
                <input id="year" name="year" class="form-control" type="text" />
            </div>
        </form>

Slide right to left Android Animations

Have a read through this blog post with an example of transition animations, I've included the code below:

Calling Activity

package com.as400samplecode;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener{

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Button nextActivity = (Button) findViewById(R.id.nextActivity);
  nextActivity.setOnClickListener(this);

 }

 public void onClick(View v) {

  switch (v.getId()) {
  case R.id.nextActivity:
   Intent nextActivity = new Intent(this,NextActivity.class);
   startActivity(nextActivity);
   //push from bottom to top
   overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
   //slide from right to left
   //overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
   break;

   // More buttons go here (if any) ...

  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Layout Resource for the Calling Activity

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 android:layout_height="match_parent" tools:context=".MainActivity"
 android:background="@color/ivory"> 
 <Button android:id="@+id/nextActivity" android:layout_width="match_parent"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:layout_marginTop="15dp"
  android:text="Go to Next Activity" /> 
</RelativeLayout>

Called Activity

package com.as400samplecode;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NextActivity extends Activity implements OnClickListener{

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);

        Button previousActivity = (Button) findViewById(R.id.previousActivity);
        previousActivity.setOnClickListener(this);

    }

 public void onClick(View v) {

  switch (v.getId()) {
  case R.id.previousActivity:
   finish();
   //push from top to bottom
   overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
   //slide from left to right
   //overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
   break;

   // More buttons go here (if any) ...

  }
 }


}

Layout Resource for the Called Activity

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 android:layout_height="match_parent" tools:context=".NextActivity"
 android:background="@color/khaki">

 <Button android:id="@+id/previousActivity" android:layout_width="match_parent"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:layout_marginTop="15dp"
  android:text="Go to Previous Activity" />

</RelativeLayout>

Animation Resource - push_down_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="-100%p" android:toYDelta="0" android:duration="5000"/>
 <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>

Animation Resource - push_down_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="5000" />
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>

Animation Resource - push_up_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="5000"/>
 <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>

Animation Resource - push_up_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="5000"/>
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>

Animation Resource - slide_in_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="-100%" android:toXDelta="0%"/>
    <alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>

Animation Resource - slide_in_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="100%" android:toXDelta="0%" />
    <alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>

Animation Resource - slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="-100%"/>
    <alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>

Animation Resource - slide_out_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="100%"/>
    <alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>

How do I define global variables in CoffeeScript?

If you're a bad person (I'm a bad person.), you can get as simple as this: (->@)()

As in,

(->@)().im_a_terrible_programmer = yes
console.log im_a_terrible_programmer

This works, because when invoking a Reference to a Function ‘bare’ (that is, func(), instead of new func() or obj.func()), something commonly referred to as the ‘function-call invocation pattern’, always binds this to the global object for that execution context.

The CoffeeScript above simply compiles to (function(){ return this })(); so we're exercising that behavior to reliably access the global object.

eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

Split string into list in jinja?

If there are up to 10 strings then you should use a list in order to iterate through all values.

{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}

How to import other Python files?

the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.

this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.

How to get current user who's accessing an ASP.NET application?

Using System.Web.HttpContext.Current.User.Identity.Name should work. Please check the IIS Site settings on the server that is hosting your site by doing the following:

  1. Go to IIS ? Sites ? Your Site ? Authentication

    IIS Settings

  2. Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.

    Authentication

  3. Now System.Web.HttpContext.Current.User.Identity.Name should return something like this:

    domain\username

Generate insert script for selected records?

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLENAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''   -- where TableId = 5 or some value
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @TABLE_NAME VARCHAR(MAX),
        @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX),
        @FILTER VARCHAR(MAX) 

SET @TABLE_NAME=@TABLENAME

SELECT @FILTER=@FILTER_CONDITION

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END

How to make the window full screen with Javascript (stretching all over the screen)

You can use The fullscreen API You can see an example here

The fullscreen API provides an easy way for web content to be presented using the user's entire screen. This article provides information about using this API.

Android studio logcat nothing to show

Nothing from all of this helped, my logcat was disfunctional.

After a lot of angry searching I found a solution that seems to work:
1. Make sure logcat itself is working (use DDMS from Tools->Android) and if it does close DDMS window again
2. Now go to Tab 5 (Debug), there select Logcat (this is not the same logcat as in Window 6!)
3. The window is empty just like Window 6, but now start a debugging run.
For me logcat in the Debug window now started to show all the stuff again!
Also when normally running the application the Debug->logcat view is still functional while the Tool Window #6 "logcat" is disfunctional as before

This is a hack, however it leads to the normal logcat behaviour with highlighted lines and syntax you need for debugging and developing. Just from now on you need to access it through the debug Window.

pass post data with window.location.href

Using window.location.href it's not possible to send a POST request.

What you have to do is to set up a form tag with data fields in it, set the action attribute of the form to the URL and the method attribute to POST, then call the submit method on the form tag.

When to use IMG vs. CSS background-image?

I use image instead of background-image when i want to make them 100% stretchable which supported in most browsers.

jQuery fade out then fade in

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

logger configuration to log to file and print to stdout

Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.

Here's a quick example reusing the assumed values and LOGFILE from the question:

import logging
from logging.handlers import RotatingFileHandler
from logging import handlers
import sys

log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)

fh = handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
fh.setFormatter(format)
log.addHandler(fh)

When should I use a table variable vs temporary table in sql server?

Your question shows you have succumbed to some of the common misconceptions surrounding table variables and temporary tables.

I have written quite an extensive answer on the DBA site looking at the differences between the two object types. This also addresses your question about disk vs memory (I didn't see any significant difference in behaviour between the two).

Regarding the question in the title though as to when to use a table variable vs a local temporary table you don't always have a choice. In functions, for example, it is only possible to use a table variable and if you need to write to the table in a child scope then only a #temp table will do (table-valued parameters allow readonly access).

Where you do have a choice some suggestions are below (though the most reliable method is to simply test both with your specific workload).

  1. If you need an index that cannot be created on a table variable then you will of course need a #temporary table. The details of this are version dependant however. For SQL Server 2012 and below the only indexes that could be created on table variables were those implicitly created through a UNIQUE or PRIMARY KEY constraint. SQL Server 2014 introduced inline index syntax for a subset of the options available in CREATE INDEX. This has been extended since to allow filtered index conditions. Indexes with INCLUDE-d columns or columnstore indexes are still not possible to create on table variables however.

  2. If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary table. That supports TRUNCATE (which is more efficient than DELETE for large tables) and additionally subsequent inserts following a TRUNCATE can have better performance than those following a DELETE as illustrated here.

  3. If you will be deleting or updating a large number of rows then the temp table may well perform much better than a table variable - if it is able to use rowset sharing (see "Effects of rowset sharing" below for an example).
  4. If the optimal plan using the table will vary dependent on data then use a #temporary table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).
  5. If the optimal plan for the query using the table is unlikely to ever change then you may consider a table variable to skip the overhead of statistics creation and recompiles (would possibly require hints to fix the plan you want).
  6. If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  7. If you need the data in the table to survive a rollback of an outer user transaction then use a table variable. A possible use case for this might be logging the progress of different steps in a long SQL batch.
  8. When using a #temp table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables.
  9. Within stored routines, both table variables and temporary tables can be cached. The metadata maintenance for cached table variables is less than that for #temporary tables. Bob Ward points out in his tempdb presentation that this can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.

Effects of rowset sharing

DECLARE @T TABLE(id INT PRIMARY KEY, Flag BIT);

CREATE TABLE #T (id INT PRIMARY KEY, Flag BIT);

INSERT INTO @T 
output inserted.* into #T
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), 0
FROM master..spt_values v1, master..spt_values v2

SET STATISTICS TIME ON

/*CPU time = 7016 ms,  elapsed time = 7860 ms.*/
UPDATE @T SET Flag=1;

/*CPU time = 6234 ms,  elapsed time = 7236 ms.*/
DELETE FROM @T

/* CPU time = 828 ms,  elapsed time = 1120 ms.*/
UPDATE #T SET Flag=1;

/*CPU time = 672 ms,  elapsed time = 980 ms.*/
DELETE FROM #T

DROP TABLE #T

How to find the last field using 'cut'

I realized if we just ensure a trailing delimiter exists, it works. So in my case I have comma and whitespace delimiters. I add a space at the end;

$ ans="a, b"
$ ans+=" "; echo ${ans} | tr ',' ' ' | tr -s ' ' | cut -d' ' -f2
b

How to run SQL in shell script

#!/bin/ksh
variable1=$( 
echo "set feed off
set pages 0
select count(*) from table;
exit
"  | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"

Regex for Comma delimited list

This regex extracts an element from a comma separated list, regardless of contents:

(.+?)(?:,|$)

If you just replace the comma with something else, it should work for any delimiter.

How to re-create database for Entity Framework?

This worked for me:

  1. Delete database from SQL Server Object Explorer in Visual Studio. Right-click and select delete.
  2. Delete mdf and ldf files from file system - if they are still there.
  3. Rebuild Solution.
  4. Start Application - database will be re-created.

How to get the caller's method name in the called method?

#!/usr/bin/env python
import inspect

called=lambda: inspect.stack()[1][3]

def caller1():
    print "inside: ",called()

def caller2():
    print "inside: ",called()

if __name__=='__main__':
    caller1()
    caller2()
shahid@shahid-VirtualBox:~/Documents$ python test_func.py 
inside:  caller1
inside:  caller2
shahid@shahid-VirtualBox:~/Documents$

Python xml ElementTree from a string source?

You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I got the same exception when I locally tested. The problem was a URL schema in my request.

Change https:// to http:// in your client url.

Probably it helps.

package R does not exist

Below are some technics which you can use to remove this error:-

  1. Clean your project, Buidl->clean Project
  2. Rebuild project, Build -> Rebuild Project
  3. Open manifest and check is there any resource missing
  4. Check-in layout to particular id if missing add it
  5. If the above steps did not work then restart android studio with invalidating the cache

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 5

  @IBAction func buttonPressed(_ sender: Any) {
    let videoURL = course.introductionVideoURL
    let player = AVPlayer(url: videoURL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player

    present(playerViewController, animated: true, completion: {

        playerViewController.player!.play()
    })

// here the course includes a model file, inside it I have given the url, so I am calling the function from model using course function.

// also introductionVideoUrl is a URL which I declared inside model .

 var introductionVideoURL: URL

Also alternatively you can use the below code instead of calling the function from model

Replace this code

  let videoURL = course.introductionVideoURL

with

  guard let videoURL = URL(string: "https://something.mp4) else {
        return

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

Find multiple files and rename them in Linux

small script i wrote to replace all files with .txt extension to .cpp extension under /tmp and sub directories recursively

#!/bin/bash

for file in $(find /tmp -name '*.txt')
do
  mv $file $(echo "$file" | sed -r 's|.txt|.cpp|g')
done

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

How to store phone numbers on MySQL databases?

I would suggest a varchar for the phone number (since phone numbers are known to have leading 0s which are important to keep) and having the phone number in two fields:

Country Code and phone number i.e. for 004477789787 you could store CountryCode=44 and phone number=77789787

however it could be very application specific. If for example you will only store US numbers and want to keep the capability of quickly performing queries like "Get all the numbers from a specific area" then you can further split the phone number field (and drop the country code field as it would be redundant)

I don't think there is a general right and wrong way to do this. It really depends on the demands.

Ruby send JSON request

It's 2020 - nobody should be using Net::HTTP any more and all answers seem to be saying so, use a more high level gem such as Faraday - Github


That said, what I like to do is a wrapper around the HTTP api call,something that's called like

rv = Transporter::FaradayHttp[url, options]

because this allows me to fake HTTP calls without additional dependencies, ie:

  if InfoSig.env?(:test) && !(url.to_s =~ /localhost/)
    response_body = FakerForTests[url: url, options: options]

  else
    conn = Faraday::Connection.new url, connection_options

Where the faker looks something like this

I know there are HTTP mocking/stubbing frameworks, but at least when I researched last time they didn't allow me to validate requests efficiently and they were just for HTTP, not for example for raw TCP exchanges, this system allows me to have a unified framework for all API communication.


Assuming you just want to quick&dirty convert a hash to json, send the json to a remote host to test an API and parse response to ruby this is probably fastest way without involving additional gems:

JSON.load `curl -H 'Content-Type:application/json' -H 'Accept:application/json' -X POST localhost:3000/simple_api -d '#{message.to_json}'`

Hopefully this goes without saying, but don't use this in production.

A valid provisioning profile for this executable was not found... (again)

In my case it was just after a new Program Licence Agreement was released so we had to accept them and it was fine.

What does body-parser do with express?

Let’s try to keep this least technical.

Let’s say you are sending a html form data to node-js server i.e. you made a request to the server. The server file would receive your request under a request object. Now by logic, if you console log this request object in your server file you should see your form data some where in it, which could be extracted then, but whoa ! you actually don’t !

So, where is our data ? How will we extract it if its not only present in my request.

Simple explanation to this is http sends your form data in bits and pieces which are intended to get assembled as they reach their destination. So how would you extract your data.

But, why take this pain of every-time manually parsing your data for chunks and assembling it. Use something called “body-parser” which would do this for you.

body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need.

For example, let’s say you have a sign-up form at your frontend. You are filling it, and requesting server to save the details somewhere.

Extracting username and password from your request goes as simple as below if you use body-parser.

var loginDetails = {    
    username : request.body.username,    
    password : request.body.password    
};

So basically, body-parser parsed your incoming request, assembled the chunks containing your form data, then created this body object for you and filled it with your form data.

C compiler for Windows?

I personally have been looking into using MinGW (what Bloodshed uses) with the Code Blocks IDE.

I am also considering using the Digital Mars C/C++ compiler.

Both seem to be well regarded.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

To make it clear, in addition to @SLaks' answer, that meant you need to change this line :

List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);

to something like this :

RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

you can also user @RequestBody Map<String, String> params,then use params.get("key") to get the value of parameter

How to POST JSON data with Python Requests?

Works perfectly with python 3.5+

client:

import requests
data = {'sender':   'Alice',
    'receiver': 'Bob',
    'message':  'We did it!'}
r = requests.post("http://localhost:8080", json={'json_payload': data})

server:

class Root(object):

    def __init__(self, content):
        self.content = content
        print self.content  # this works

    exposed = True

    def GET(self):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return simplejson.dumps(self.content)

    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def POST(self):
        self.content = cherrypy.request.json
        return {'status': 'success', 'message': 'updated'}

Returning data from Axios API

axiosTest() is firing asynchronously and not being waited for.

A then() function needs to be hooked up afterwards in order to capture the response variable (axiosTestData).

See Promise for more info.

See Async to level up.

_x000D_
_x000D_
// Dummy Url._x000D_
const url = 'https://jsonplaceholder.typicode.com/posts/1'_x000D_
_x000D_
// Axios Test._x000D_
const axiosTest = axios.get_x000D_
_x000D_
// Axios Test Data._x000D_
axiosTest(url).then(function(axiosTestResult) {_x000D_
  console.log('response.JSON:', {_x000D_
    message: 'Request received',_x000D_
    data: axiosTestResult.data_x000D_
  })_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
_x000D_
_x000D_
_x000D_

Any way to clear python's IDLE window?

I got it with:

import console 
console.clear()

if you want to do it in your script, or if you are in the console just tap clear() and press enter. That works on Pyto on iPhone. It may depend on the console though.

How to use document.getElementByName and getElementByTag?

  • document.getElementById('frmMain').elements
    assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a name attribute in IE, please add ID to the element if you want to use getElementById



A great alternative is


In all of the above, the .elements can be replaced by for example .querySelectorAll("[type=text]") to get all text elements

What's the Kotlin equivalent of Java's String[]?

To create an empty Array of Strings in Kotlin you should use one of the following six approaches:

First approach:

val empty = arrayOf<String>()

Second approach:

val empty = arrayOf("","","")

Third approach:

val empty = Array<String?>(3) { null }

Fourth approach:

val empty = arrayOfNulls<String>(3)

Fifth approach:

val empty = Array<String>(3) { "it = $it" }

Sixth approach:

val empty = Array<String>(0, { _ -> "" })

jquery how to catch enter key and change event to tab

Here's a jQuery plugin I wrote that handles enter key as a callback or as a tab key (with an optional callback):

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#one').onEnter('tab');_x000D_
  $('#two').onEnter('tab');_x000D_
  $('#three').onEnter('tab');_x000D_
  $('#four').onEnter('tab');_x000D_
  $('#five').onEnter('tab');_x000D_
});_x000D_
_x000D_
/**_x000D_
 * jQuery.onEnter.js_x000D_
 * Written by: Jay Simons_x000D_
 * Cloudulus.Media (https://code.cloudulus.media)_x000D_
 */_x000D_
_x000D_
if (window.jQuery) {_x000D_
    (function ($) {_x000D_
        $.fn.onEnter = function (opt1, opt2, opt3) {_x000D_
            return this.on('keyup', function (e) {_x000D_
                var me = $(this);_x000D_
                var code = e.keyCode ? e.keyCode : e.which;_x000D_
                if (code == 13) {_x000D_
                    if (typeof opt1 == 'function')_x000D_
                    {_x000D_
                        opt1(me, opt2);_x000D_
                        return true;_x000D_
                    }else if (opt1 == 'tab')_x000D_
                    {_x000D_
                        var eles = $(document).find('input,select,textarea,button').filter(':visible:not(:disabled):not([readonly])');_x000D_
                        var foundMe = false;_x000D_
                        var next = null;_x000D_
                        eles.each(function(){_x000D_
                            if (!next){_x000D_
                                if (foundMe) next = $(this);_x000D_
                                if (JSON.stringify($(this)) == JSON.stringify(me)) foundMe = true;_x000D_
                            }_x000D_
                        });_x000D_
                        next.focus();_x000D_
                        if (typeof opt2 === 'function')_x000D_
                        {_x000D_
                            opt2(me, opt3);_x000D_
                        }_x000D_
                        return true;_x000D_
                    }_x000D_
                }_x000D_
            }).on('keydown', function(e){_x000D_
                var code = e.keyCode ? e.keyCode : e.which;_x000D_
                if (code == 13)_x000D_
                {_x000D_
                    e.preventDefault();_x000D_
                    e.stopPropagation();_x000D_
                    return false;_x000D_
                }_x000D_
            });_x000D_
        }_x000D_
    })(jQuery);_x000D_
} else {_x000D_
    console.log("onEnter.js: This class requies jQuery > v3!");_x000D_
}
_x000D_
input,_x000D_
select,_x000D_
textarea,_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input id="one" type="text" placeholder="Input 1" />_x000D_
  <input id="two" type="text" placeholder="Input 2" />_x000D_
_x000D_
  <select id="four">_x000D_
    <option selected>A Select Box</option>_x000D_
    <option>Opt 1</option>_x000D_
    <option>Opt 2</option>_x000D_
  </select>_x000D_
  <textarea id="five" placeholder="A textarea"></textarea>_x000D_
  <input id="three" type="text" placeholder="Input 3" />_x000D_
  <button>A Button</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Clear and refresh jQuery Chosen dropdown list

If in case trigger("chosen:updated"); doesn't works for you. You can try $('#ddl').trigger('change'); as in my case its work for me.

Use of contains in Java ArrayList<String>

Right...with strings...the moment you deviate from primitives or strings things change and you need to implement hashcode/equals to get the desired effect.

EDIT: Initialize your ArrayList<String> then attempt to add an item.

How to select a CRAN mirror in R

A drop down menu should pop up for you to select from (or you will get a bunch of numbers to choose from), whether you are using R in the terminal or an IDE such as RStudio. This is supported on Windows, Mac OS, and most Linux systems. However, it may require additional configuration or dependencies such as X-windows.

To enable X-windows when using remote access use the following -XY flags:

ssh -XY [email protected]

There is often a default repo but this can be specified if you have any issue, such as running scripts or Rmarkdown/knitr. You can use the repo opset the mirror or repository for CRAN each time you install with:

install.packages("package", repo="<your.nearest.mirror>")

It is advisable to use the nearest mirror to your location for faster downloads. For example:

install.packages("RMySQL", repos="https://cran.stat.auckland.ac.nz/")

You can also set the repos option in your session so you only need to it once per interactive session (or script). You can check whether repos is configured with:

options(repos)

If you get "Error in options(repos) : object 'repos' not found" then you can set the repository option. For example:

options(repos = "https://cran.stat.auckland.ac.nz/")

Then it should work to install packages like usual. For Example:

install.packages("RMySQL")

As mentioned by others, you can configure the repository in your .Rprofile file and have this work across all of your scripts. It's up to you whether your prefer these "global" options on your system or "local" options in your session or script. These "local" options take more time to use each session but have the benefit of making others able to use your scripts if they don't have your .Rprofile.

Detect Route Change with react-router

This is an old question and I don't quite understand the business need of listening for route changes to push a route change; seems roundabout.

BUT if you ended up here because all you wanted was to update the 'page_path' on a react-router route change for google analytics / global site tag / something similar, here's a hook you can now use. I wrote it based on the accepted answer:

useTracking.js

import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

export const useTracking = (trackingId) => {
  const { listen } = useHistory()

  useEffect(() => {
    const unlisten = listen((location) => {
      // if you pasted the google snippet on your index.html
      // you've declared this function in the global
      if (!window.gtag) return

      window.gtag('config', trackingId, { page_path: location.pathname })
    })

    // remember, hooks that add listeners
    // should have cleanup to remove them
    return unlisten
  }, [trackingId, listen])
}

You should use this hook once in your app, somewhere near the top but still inside a router. I have it on an App.js that looks like this:

App.js

import * as React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

import Home from './Home/Home'
import About from './About/About'
// this is the file above
import { useTracking } from './useTracking'

export const App = () => {
  useTracking('UA-USE-YOURS-HERE')

  return (
    <Switch>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  )
}

// I find it handy to have a named export of the App
// and then the default export which wraps it with
// all the providers I need.
// Mostly for testing purposes, but in this case,
// it allows us to use the hook above,
// since you may only use it when inside a Router
export default () => (
  <BrowserRouter>
    <App />
  </BrowserRouter>
)

How to delete all files older than 3 days when "Argument list too long"?

To delete all files and directories within the current directory:

find . -mtime +3 | xargs rm -Rf

Or alternatively, more in line with the OP's original command:

find . -mtime +3 -exec rm -Rf -- {} \;

Which is faster: multiple single INSERTs or one multiple-row INSERT?

Send as many inserts across the wire at one time as possible. The actual insert speed should be the same, but you will see performance gains from the reduction of network overhead.

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

In case someone is still struggling with this issue:

I faced similar issue where 2 requests were hitting the server at the same time. There was no situation like below:

T1:
    BEGIN TRANSACTION
    INSERT TABLE A
    INSERT TABLE B
    END TRANSACTION

T2:
    BEGIN TRANSACTION
    INSERT TABLE B
    INSERT TABLE A
    END TRANSACTION

So, I was puzzled why deadlock is happening.

Then I found that there was parent child relation ship between 2 tables because of foreign key. When I was inserting a record in child table, the transaction was acquiring a lock on parent table's row. Immediately after that I was trying to update the parent row which was triggering elevation of lock to EXCLUSIVE one. As 2nd concurrent transaction was already holding a SHARED lock, it was causing deadlock.

Refer to: https://blog.tekenlight.com/2019/02/21/database-deadlock-mysql.html

Bash foreach loop

Something like this would do:

xargs cat <filenames.txt

The xargs program reads its standard input, and for each line of input runs the cat program with the input lines as argument(s).

If you really want to do this in a loop, you can:

for fn in `cat filenames.txt`; do
    echo "the next file is $fn"
    cat $fn
done

How do I install jmeter on a Mac?

Once you got the ZIP from the download, extract it locally, and with your finder, go in bin directory.

Then double-click on ApacheJMeter.jar to launch the User Interface of JMeter.

This and the next steps are described in a blog entry.

Bash script plugin for Eclipse?

There exists now a dedicated bash script plugin called "Bash editor". It's available at eclipse market place:

Bash editor log

You can find it at https://marketplace.eclipse.org/content/bash-editor or by marketplace client when searching for "bash".

The plugin does also provide a debugger. Inisde official Bash Editor YouTube playlist you can find some tutorials about usage etc.

PS: I am the author of the mentioned plugin.

Best C++ IDE or Editor for Windows

The Zeus editor has support for C/C++ and it also has a form of intellisensing.

It does its intellisensing using the tags information produced by ctags:

alt text http://www.zeusedit.com/images/_lookmain.jpg

How can I see the size of files and directories in linux?

You can use ncdu disk usage analyzer here. It displays the size of the files and directories in an ncurses interface. You can navigate to each directory and see the files sizes from the same interface.

To install

$ sudo apt-get install ncdu

To analyze

$ ncdu <directory>

enter image description here

Copy a variable's value into another

newVariable = originalVariable.valueOf();

for objects you can use, b = Object.assign({},a);

lvalue required as left operand of assignment

if (strcmp("hello", "hello") = 0)

Is trying to assign 0 to function return value which isn't lvalue.

Function return values are not lvalue (no storage for it), so any attempt to assign value to something that is not lvalue result in error.

Best practice to avoid such mistakes in if conditions is to use constant value on left side of comparison, so even if you use "=" instead "==", constant being not lvalue will immediately give error and avoid accidental value assignment and causing false positive if condition.

Convert string in base64 to image and save on filesystem in Python

Starting with

img_data = b'iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQVR42uzBAQEAAACAkP6v7ggK\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAIcAeHkAAeLqlDIAAAAASUVORK5CYII='

Decoded the data using the base64 codec, and then write it to the filesystem.

# In Python 2.7
fh = open("imageToSave.png", "wb")
fh.write(img_data.decode('base64'))
fh.close()

# or, more concisely using with statement
with open("imageToSave.png", "wb") as fh:
    fh.write(img_data.decode('base64'))

Modernizing this example to Python 3, which removed arbitrary codec support from string/bytes .encode() and .decode() functions:

# For both Python 2.7 and Python 3.x
import base64
with open("imageToSave.png", "wb") as fh:
    fh.write(base64.decodebytes(img_data))

How can I pair socks from a pile efficiently?

As the architecture of the human brain is completely different than a modern CPU, this question makes no practical sense.

Humans can win over CPU algorithms using the fact that "finding a matching pair" can be one operation for a set that isn't too big.

My algorithm:

spread_all_socks_on_flat_surface();
while (socks_left_on_a_surface()) {
     // Thanks to human visual SIMD, this is one, quick operation.
     pair = notice_any_matching_pair();
     remove_socks_pair_from_surface(pair);
}

At least this is what I am using in real life, and I find it very efficient. The downside is it requires a flat surface, but it's usually abundant.

How much should a function trust another function

Such debugging is part of the development process and should not be the issue at runtime.

Methods don't trust other methods. They all trust you. That is the process of developing. Fix all bugs. Then methods don't have to "trust". There should be no doubt.

So, write it as it should be. Do not make methods check wether other methods are working correctly. That should be tested by the developer when they wrote that function. If you suspect a method to be not doing what you want, debug it.

Pull new updates from original GitHub repository into forked GitHub repository

Use:

git remote add upstream ORIGINAL_REPOSITORY_URL

This will set your upstream to the repository you forked from. Then do this:

git fetch upstream      

This will fetch all the branches including master from the original repository.

Merge this data in your local master branch:

git merge upstream/master

Push the changes to your forked repository i.e. to origin:

git push origin master

Voila! You are done with the syncing the original repository.

How to use Scanner to accept only valid int as input

Try this:

    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("^\\d+$");
        Scanner kb = new Scanner(System.in);
        int num1;
        int num2 = 0;
        String temp;
        Matcher numberMatcher;
        System.out.print("Enter number 1: ");
        try
        {
            num1 = kb.nextInt();
        }

        catch (java.util.InputMismatchException e)
        {
            System.out.println("Invalid Input");
            //
            return;
        }
        while(num2<num1)
        {
            System.out.print("Enter number 2: ");
            temp = kb.next();
            numberMatcher = p.matcher(temp);
            if (numberMatcher.matches())
            {
                num2 = Integer.parseInt(temp);
            }

            else
            {
                System.out.println("Invalid Number");
            }
        }
    }

You could try to parse the string into an int as well, but usually people try to avoid throwing exceptions.

What I have done is that I have defined a regular expression that defines a number, \d means a numeric digit. The + sign means that there has to be one or more numeric digits. The extra \ in front of the \d is because in java, the \ is a special character, so it has to be escaped.

How do I test a private function or a class that has private methods, fields or inner classes?

Groovy has a bug/feature, through which you can invoke private methods as if they were public. So if you're able to use Groovy in your project, it's an option you can use in lieu of reflection. Check out this page for an example.

Laravel view not found exception

check your blade syntax on the view that said not found i just fix mine

@if
@component
@endif 
@endcomponent

to

@if
@component
@endcomponent
@endif 

If statements for Checkboxes

In VB.Net

If Check1.checked and Not (Check2.checked) Then

ElseIf Check2.Checked and not Check1.Checked then

End If

What column type/length should I use for storing a Bcrypt hashed password in a Database?

If you are using PHP's password_hash() with the PASSWORD_DEFAULT algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash() might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).

From the manual page:

Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT to force password_hash() to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.

Simplest way to set image as JPanel background

Draw the image on the background of a JPanel that is added to the frame. Use a layout manager to normally add your buttons and other components to the panel. If you add other child panels, perhaps you want to set child.setOpaque(false).

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;

public class BackgroundImageApp {
    private JFrame frame;

    private BackgroundImageApp create() {
        frame = createFrame();
        frame.getContentPane().add(createContent());

        return this;
    }

    private JFrame createFrame() {
        JFrame frame = new JFrame(getClass().getName());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        return frame;
    }

    private void show() {
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private Component createContent() {
        final Image image = requestImage();

        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, 0, 0, null);
            }
        };

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        for (String label : new String[]{"One", "Dois", "Drei", "Quatro", "Peace"}) {
            JButton button = new JButton(label);
            button.setAlignmentX(Component.CENTER_ALIGNMENT);
            panel.add(Box.createRigidArea(new Dimension(15, 15)));
            panel.add(button);
        }

        panel.setPreferredSize(new Dimension(500, 500));

        return panel;
    }

    private Image requestImage() {
        Image image = null;

        try {
            image = ImageIO.read(new URL("http://www.johnlennon.com/wp-content/themes/jl/images/home-gallery/2.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new BackgroundImageApp().create().show();
            }
        });
    }
}

Interactive shell using Docker Compose

The canonical way to get an interactive shell with docker-compose is to use:

docker-compose run --rm myapp

You can set stdin_open: true, tty: true, however that won't actually give you a proper shell with up, because logs are being streamed from all the containers.

You can also use

docker exec -ti <container name> /bin/bash

to get a shell on a running container.

List(of String) or Array or ArrayList

List(Of String) will handle that, mostly - though you need to either use AddRange to add a collection of items, or Add to add one at a time:

lstOfString.Add(String1)
lstOfString.Add(String2)
lstOfString.Add(String3)
lstOfString.Add(String4)

If you're adding known values, as you show, a good option is to use something like:

Dim inputs() As String = { "some value", _
                              "some value2", _
                              "some value3", _
                              "some value4" }

Dim lstOfString as List(Of String) = new List(Of String)(inputs)

' ...
Dim s3 = lstOfStrings(3)

This will still allow you to add items later as desired, but also get your initial values in quickly.


Edit:

In your code, you need to fix the declaration. Change:

Dim lstWriteBits() As List(Of String) 

To:

Dim lstWriteBits As List(Of String) 

Currently, you're declaring an Array of List(Of String) objects.

How to execute only one test spec with angular-cli

This worked for me in every case:

ng test --include='**/dealer.service.spec.ts'

However, I usually got "TypeError: Cannot read property 'ngModule' of null" for this:

ng test --main src/app/services/dealer.service.spec.ts

Version of @angular/cli 10.0.4

How to center text vertically with a large font-awesome icon?

I would wrap the text in a so you can target it separately. Now if you float both and left, you can use line-height to control the vertical spacing of the . Setting it to the same height as the (30px) will middle align it. See here.

New Markup:

 <div>
    <i class='icon icon-2x icon-camera'></i>
    <span id="text">hello world</span>
</div>

New CSS:

div {
    border: 1px solid #ccc;
    height: 30px;
    margin: 60px;
    padding: 4px;
    vertical-align: middle;
}
i{
    float: left;
}
#text{
    line-height: 30px;
    float: left;
}

Executing Shell Scripts from the OS X Dock?

I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html

To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.

ASP.NET page life cycle explanation

This acronym might help you to remember the ASP.NET life cycle stages which I wrote about in the below blog post.

R-SIL-VP-RU

  1. Request
  2. Start
  3. Initialization
  4. Load
  5. Validation
  6. Post back handling
  7. Rendering
  8. Unload

From my blog: Understand ASP.NET Page life cycle and remember stages in easy way
18 May 2014

POSTing JsonObject With HttpClient From Web API

I don't have enough reputation to add a comment on the answer from pomber so I'm posting another answer. Using pomber's approach I kept receiving a "400 Bad Request" response from an API I was POSTing my JSON request to (Visual Studio 2017, .NET 4.6.2). Eventually the problem was traced to the "Content-Type" header produced by StringContent() being incorrect (see https://github.com/dotnet/corefx/issues/7864).

tl;dr

Use pomber's answer with an extra line to correctly set the header on the request:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;

Markdown to create pages and table of contents?

If using the Sublime Text editor, the MarkdownTOC plugin works beautifully! See:

  1. https://packagecontrol.io/packages/MarkdownTOC
  2. https://github.com/naokazuterada/MarkdownTOC

Once installed, go to Preferences --> Package Settings --> MarkdownTOC --> Settings -- User, to customize your settings. Here's the options you can choose: https://github.com/naokazuterada/MarkdownTOC#configuration.

I recommend the following:

{
  "defaults": {
    "autoanchor": true,
    "autolink": true,
    "bracket": "round",
    "levels": [1,2,3,4,5,6],
    "indent": "\t",
    "remove_image": true,
    "link_prefix": "",
    "bullets": ["-"],
    "lowercase": "only_ascii",
    "style": "ordered",
    "uri_encoding": true,
    "markdown_preview": ""
  },
  "id_replacements": [
    {
      "pattern": "\\s+",
      "replacement": "-"
    },
    {
      "pattern": "&lt;|&gt;|&amp;|&apos;|&quot;|&#60;|&#62;|&#38;|&#39;|&#34;|!|#|$|&|'|\\(|\\)|\\*|\\+|,|/|:|;|=|\\?|@|\\[|\\]|`|\"|\\.|\\\\|<|>|{|}|™|®|©|%",
      "replacement": ""
    }
  ],
  "logging": false
}

To insert a table of contents, simply click at the top of the document where you'd like to insert the table of contents, then go to Tools --> Markdown TOC --> Insert TOC.

It will insert something like this:

<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->

Note the <!-- --> HTML comments it inserts for you. These are special markers that help the program know where the ToC is so that it can automatically update it for you every time you save! So, leave these intact.

To get extra fancy, add some <details> and <summary> HTML tags around it to make the ToC collapsible/expandable, like this:

<details>
<summary><b>Table of Contents</b> (click to open)</summary>
<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->
</details>

Now, you get this super cool effect, as shown below. See it in action in my main eRCaGuy_dotfiles readme here, or in my Sublime_Text_editor readme here.

  1. Collapsed: enter image description here
  2. Expanded: enter image description here

For extra information about its usage and limitations, be sure to read my notes about the MarkdownTOC plugin in that readme too.

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

How to avoid Number Format Exception in java?

That depends on your environment. JSF for example would take the burden of manually checking and converting Strings <-> Numbers from you, Bean Validation is another option.

What you can do immediately in the snippet you provide:

  1. Extract method getAsInt(String param), in it:
  2. Use String.isEmpty() (Since Java 6),
  3. surround with try / catch

What you should definitely think about if you happen to write a lot of code like this:

public void myBusinessMethod(@ValidNumber String numberInput) {
// ...    
}

(This would be interceptor-based).

Last but not least: Save the work and try to switch to a framework which gives you support for these common tasks...

How to calculate cumulative normal distribution?

To build upon Unknown's example, the Python equivalent of the function normdist() implemented in a lot of libraries would be:

def normcdf(x, mu, sigma):
    t = x-mu;
    y = 0.5*erfcc(-t/(sigma*sqrt(2.0)));
    if y>1.0:
        y = 1.0;
    return y

def normpdf(x, mu, sigma):
    u = (x-mu)/abs(sigma)
    y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)
    return y

def normdist(x, mu, sigma, f):
    if f:
        y = normcdf(x,mu,sigma)
    else:
        y = normpdf(x,mu,sigma)
    return y

How to create a remote Git repository from a local one?

A remote repository is generally a bare repository — a Git repository that has no working directory. Because the repository is only used as a collaboration point, there is no reason to have a snapshot checked out on disk; it’s just the Git data. In the simplest terms, a bare repository is the contents of your project’s .git directory and nothing else.

You can make a bare git repository with the following code:

$ git clone --bare /path/to/project project.git

One options for having a remote git repository is using SSH protocol:

A common transport protocol for Git when self-hosting is over SSH. This is because SSH access to servers is already set up in most places — and if it isn’t, it’s easy to do. SSH is also an authenticated network protocol and, because it’s ubiquitous, it’s generally easy to set up and use.

To clone a Git repository over SSH, you can specify an ssh:// URL like this:

$ git clone ssh://[user@]server/project.git

Or you can use the shorter scp-like syntax for the SSH protocol:

$ git clone [user@]server:project.git

In both cases above, if you don’t specify the optional username, Git assumes the user you’re currently logged in as.

The Pros

The pros of using SSH are many. First, SSH is relatively easy to set up — SSH daemons are commonplace, many network admins have experience with them, and many OS distributions are set up with them or have tools to manage them. Next, access over SSH is secure — all data transfer is encrypted and authenticated. Last, like the HTTPS, Git and Local protocols, SSH is efficient, making the data as compact as possible before transferring it.

The Cons

The negative aspect of SSH is that it doesn’t support anonymous access to your Git repository. If you’re using SSH, people must have SSH access to your machine, even in a read-only capacity, which doesn’t make SSH conducive to open source projects for which people might simply want to clone your repository to examine it. If you’re using it only within your corporate network, SSH may be the only protocol you need to deal with. If you want to allow anonymous read-only access to your projects and also want to use SSH, you’ll have to set up SSH for you to push over but something else for others to fetch from.

For more information, check the reference: Git on the Server - The Protocols

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

Go to next item in ForEach-Object

You may want to use the Continue statement to continue with the innermost loop.

Excerpt from PowerShell help file:

In a script, the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:

  • for
  • foreach
  • while

Cross field validation with Hibernate Validator (JSR 303)

I don't have the reputation for commenting on the first answer but wanted to add that I have added unit tests for the winning answer and have the following observations:

  • If you get the first or field names wrong then you get a validation error as though the values don't match. Don't get tripped up by spelling mistakes e.g.

@FieldMatch(first="invalidFieldName1", second="validFieldName2")

  • The validator will accept equivalent data types i.e. these will all pass with FieldMatch:

private String stringField = "1";

private Integer integerField = new Integer(1)

private int intField = 1;

  • If the fields are of an object type which does not implement equals, the validation will fail.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Call one constructor from another

In case you need to run something before calling another constructor not after.

public class Sample
{
    static int preprocess(string theIntAsString)
    {
        return preprocess(int.Parse(theIntAsString));
    }

    static int preprocess(int theIntNeedRounding)
    {
        return theIntNeedRounding/100;
    }

    public Sample(string theIntAsString)
    {
        _intField = preprocess(theIntAsString)
    }

    public Sample(int theIntNeedRounding)
    {
        _intField = preprocess(theIntNeedRounding)
    }

    public int IntProperty  => _intField;

    private readonly int _intField;
}

And ValueTuple can be very helpful if you need to set more than one field.

How do I connect to a Websphere Datasource with a given JNDI name?

DNS for Services

JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.

What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.

Simple example.

javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");

Here is IBM's reference page.

If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE

Replace duplicate spaces with a single space in T-SQL

 DECLARE @str varchar(150)
SET @str='Hello    My   name  is Jiyaul   mustafa'
Select REPLACE(REPLACE(REPLACE(@str,' ','{}'),'}{',''),'{}',' ')

Python/Json:Expecting property name enclosed in double quotes

Use the eval function.

It takes care of the discrepancy between single and double quotes.

What is the best way to parse html in C#?

You could use TidyNet.Tidy to convert the HTML to XHTML, and then use an XML parser.

Another alternative would be to use the builtin engine mshtml:

using mshtml;
...
object[] oPageText = { html };
HTMLDocument doc = new HTMLDocumentClass();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(oPageText);

This allows you to use javascript-like functions like getElementById()

Richtextbox wpf binding

Create a UserControl which has a RichTextBox named RTB. Now add the following dependency property:

    public FlowDocument Document
    {
        get { return (FlowDocument)GetValue(DocumentProperty); }
        set { SetValue(DocumentProperty, value); }
    }

    public static readonly DependencyProperty DocumentProperty =
        DependencyProperty.Register("Document", typeof(FlowDocument), typeof(RichTextBoxControl), new PropertyMetadata(OnDocumentChanged));

    private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        RichTextBoxControl control = (RichTextBoxControl) d;
        FlowDocument document = e.NewValue as FlowDocument;
        if (document  == null)
        {
            control.RTB.Document = new FlowDocument(); //Document is not amused by null :)
        }
        else
        {
            control.RTB.Document = document;
        }
    }

This solution is probably that "proxy" solution you saw somewhere.. However.. RichTextBox simply does not have Document as DependencyProperty... So you have to do this in another way...

HTH

How to replace multiple substrings of a string?

In my case, I needed a simple replacing of unique keys with names, so I thought this up:

a = 'This is a test string.'
b = {'i': 'I', 's': 'S'}
for x,y in b.items():
    a = a.replace(x, y)
>>> a
'ThIS IS a teSt StrIng.'

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

Actually, it happen to me when I didn't store the object as reference variable. in Entity class. Like this code: ses.get(InsurancePolicy.class, 101); After that, I stored the object in entity's reference variable so problem solved for me. policy=(InsurancePolicy)ses.get(InsurancePolicy.class, 101); After that, I updated the object and it worked fine.

How to create loading dialogs in Android?

Today things have changed a little.

Now we avoid use ProgressDialog to show spinning progress:

enter image description here

If you want to put in your app a spinning progress you should use an Activity indicators:

http://developer.android.com/design/building-blocks/progress.html#activity

Multiline TextBox multiple newline

textBox1.Text = "Line1\r\r\Line2";
Solved the problem.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

How to return more than one value from a function in Python?

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly

Why does integer division in C# return an integer and not a float?

Since you don't use any suffix, the literals 13 and 4 are interpreted as integer:

Manual:

If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

Thus, since you declare 13 as integer, integer division will be performed:

Manual:

For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.

The predefined division operators are listed below. The operators all compute the quotient of x and y.

Integer division:

int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);

And so rounding down occurs:

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

If you do the following:

int x = 13f / 4f;

You'll receive a compiler error, since a floating-point division (the / operator of 13f) results in a float, which cannot be cast to int implicitly.

If you want the division to be a floating-point division, you'll have to make the result a float:

float x = 13 / 4;

Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0. To explicitly declare the operands as float, using the f suffix (13f, 4f).

How to detect if javascript files are loaded?

I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1) in a script tag after the script tags that define function1, etc., you should be good to go.

<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>

Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.

EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:

<script type='text/javascript'>
function fireWhenReady() {
    if (typeof function1 != 'undefined') {
        function1();
    }
    else {
        setTimeout(fireWhenReady, 100);
    }
}
$(document).ready(fireWhenReady);
</script>

...but you shouldn't have to do that if you get your script tag order correct.


Update: You can get load notifications for script elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:

function loadScript(path, callback) {

    var done = false;
    var scr = document.createElement('script');

    scr.onload = handleLoad;
    scr.onreadystatechange = handleReadyStateChange;
    scr.onerror = handleError;
    scr.src = path;
    document.body.appendChild(scr);

    function handleLoad() {
        if (!done) {
            done = true;
            callback(path, "ok");
        }
    }

    function handleReadyStateChange() {
        var state;

        if (!done) {
            state = scr.readyState;
            if (state === "complete") {
                handleLoad();
            }
        }
    }
    function handleError() {
        if (!done) {
            done = true;
            callback(path, "error");
        }
    }
}

In my experience, error notification (onerror) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done variable to avoid duplicate notifications.

How to get current route

I had the same problem using

this.router.url

I get the current route with query params. A workaround I did was using this instead:

this.router.url.split('?')[0]

Not a really nice solution, but helpful.

SVN Commit specific files

I make a (sub)folder named "hide", move the file I don't want committed to there. Then do my commit, ignoring complaint about the missing file. Then move the hidden file from hide back to ./

I know of no downside to this tactic.

Get the cartesian product of a series of lists?

Just to add a bit to what has already been said: if you use sympy, you can use symbols rather than strings which makes them mathematically useful.

import itertools
import sympy

x, y = sympy.symbols('x y')

somelist = [[x,y], [1,2,3], [4,5]]
somelist2 = [[1,2], [1,2,3], [4,5]]

for element in itertools.product(*somelist):
  print element

About sympy.

Populate dropdown select with array using jQuery

var qty = 5;
var option = '';
for (var i=1;i <= qty;i++){
   option += '<option value="'+ i + '">' + i + '</option>';
}
$('#items').append(option);

How do I convert an interval into a number of hours with postgres?

Probably the easiest way is:

SELECT EXTRACT(epoch FROM my_interval)/3600

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

These names refers to different ways to encode pixel image data (JPG and JPEG are the same thing, and TIFF may just enclose a jpeg with some additional metadata).

These image formats may use different compression algorithms, different color representations, different capability in carrying additional data other than the image itself, and so on.

For web applications, I'd say jpeg or gif is good enough. Jpeg is used more often due to its higher compression ratio, and gif is typically used for light weight animation where a flash (or something similar) is an over kill, or places where transparent background is desired. PNG can be used too, but I don't have much experience with that. BMP and TIFF probably are not good candidates for web applications.

Escaping special characters in Java Regular Expressions

Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.

Xampp localhost/dashboard

Try this solution:

Go to->

  1. xammp ->htdocs-> then open index.php from the htdocs folder
  2. you can modify the dashboard
  3. restart the server

Example Code index.php :

    <?php
    if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
        $uri = 'https://';
    } else {
        $uri = 'http://';
    }
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri.'/dashboard/');
    exit;
   ?>

How to set a value to a file input in HTML?

Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
       FormToMultipartPostData postData = 
            new FormToMultipartPostData(webBrowser1, form);
        postData.SetFile("fileField", @"C:\windows\win.ini");
        postData.Submit();
    }

Refer the below link for downloading and complete reference.

https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

How to get Time from DateTime format in SQL?

select substr(to_char(colUmn_name, 'DD/MM/RRRR HH:MM:SS'),11,19) from table_name;

Output: from

05:11:26
05:11:24
05:11:24

How to execute INSERT statement using JdbcTemplate class from Spring Framework

If you use spring-boot, you don't need to create a DataSource class, just specify the data url/username/password/driver in application.properties, then you can simply @Autowired it.

@Repository
public class JdbcRepository {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DynamicRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void insert() {
        jdbcTemplate.update("INSERT INTO BOOK (name, description) VALUES ('book name', 'book description')");
    }
}

Example of application.properties:

#Basic Spring Boot Config for Oracle
spring.datasource.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostIP)(PORT=YourPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=YourServiceName)))
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect

Then add the driver and connection pool dependencies in pom.xml

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1</version>
</dependency>

<!-- HikariCP connection pool -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>2.6.0</version>
</dependency>

See the official doc for more details.

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

Jenkins: Cannot define variable in pipeline stage

you can define the variable global , but when using this variable must to write in script block .

def foo="foo"
pipeline {
agent none
stages {
   stage("first") {
      script{
          sh "echo ${foo}"
      }
    }
  }
}

Laravel: Get base url

This:

echo url('/');

And this:

echo asset('/');

both displayed the home url in my case :)

Get a JSON object from a HTTP response

Do this to get the JSON

String json = EntityUtils.toString(response.getEntity());

More details here : get json from HttpResponse

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".

and install the package. it will resolve the issue for me.

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

One problem is the conflict between the Eclipse-64bit version and our Java installation being 32bit version. This doesn't get solved easily because the Java installation page doesn't give the option for 64bit - it assumes 32bit and downloads and installs the 32bit version. To overcome this issue, please follow the following steps:

  1. Download the 64bit version by going to Java SE Runtime Environment 7 (this link gives us the option to download a 64bit version of Java). Download and install this.
  2. Now, trying to install Eclipse will still throw an error. So, we copy the jre7 folder from C:/program files/Java/ and copy it in our Eclipse installation folder.
  3. Now, we rename it to jre.

Install Eclipse.

--launcher.appendVmargs -vm C:\Program Files\Java\jdk1.7.0_79\jre\bin\javaw.exe -vmargs

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

Does it matter what extension is used for SQLite database files?

SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite extension, just so there isn't any ambiguity when I'm looking at my files later.

Is floating point math broken?

2020 TypeScript Answer:

Why:

https://0.30000000000000004.com

Library:

I built an NPM library for these reasons, but here's the code. You can either import the library or copy the code below.

// TypeScript Type: Math Type
type MathType = 'Add' | 'Subtract' | 'Multiply' | 'Divide';

// Math Exact
export const mathExact = (mathType: MathType, numberOne:number , numberTwo: number) => {
  // Decimal Places
  let numberOneDecimalPlaces: number = 0;
  let numberTwoDecimalPlaces: number = 0;

  // Float: Number One
  if (numberOne.toString().indexOf('.') !== -1) {
    // Assign Decimal Places
    numberOneDecimalPlaces = numberOne.toString().length - 1 - numberOne.toString().indexOf('.');
  }

  // Float: Number Two
  if (numberTwo.toString().indexOf('.') !== -1) {
    // Assign Decimal Places
    numberTwoDecimalPlaces = numberTwo.toString().length - 1 - numberTwo.toString().indexOf('.');
  }

  // Decimal Places: Equal
  if (numberOneDecimalPlaces === numberTwoDecimalPlaces) {
    // Integers (Off By Decimal Places)
    const numberOneInteger: number = numberOne * Math.pow(10, numberOneDecimalPlaces);
    const numberTwoInteger: number = numberTwo * Math.pow(10, numberTwoDecimalPlaces);

    // Math Type: Add
    if (mathType === 'Add') {
      // Integer Total
      const integerTotal: number = numberOneInteger + numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberOneDecimalPlaces);
    }
    // Math Type: Subtract
    else if (mathType === 'Subtract') {
      // Integer Total
      const integerTotal: number = numberOneInteger - numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberOneDecimalPlaces);
    }
    // Math Type: Multiply
    else if (mathType === 'Multiply') {
      // Integer Total
      const integerTotal: number = numberOneInteger * numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberOneDecimalPlaces + numberTwoDecimalPlaces);
    }
    // Math Type: Divide
    else if (mathType === 'Divide') {
      return numberOneInteger / numberTwoInteger;
    }
  }
  // Decimal Places: Number One Has More
  else if (numberOneDecimalPlaces > numberTwoDecimalPlaces) {
    // Integers (Off By Decimal Places)
    const numberOneInteger: number = numberOne * Math.pow(10, numberOneDecimalPlaces);
    const numberTwoInteger: number = numberTwo * Math.pow(10, numberOneDecimalPlaces);

    // Math Type: Add
    if (mathType === 'Add') {
      // Integer Total
      const integerTotal: number = numberOneInteger + numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberOneDecimalPlaces);
    }
    // Math Type: Subtract
    else if (mathType === 'Subtract') {
      // Integer Total
      const integerTotal: number = numberOneInteger - numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberOneDecimalPlaces);
    }
    // Math Type: Multiply
    else if (mathType === 'Multiply') {
      // Integer Total
      const integerTotal: number = numberOneInteger * numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberOneDecimalPlaces + numberTwoDecimalPlaces + (numberOneDecimalPlaces - numberTwoDecimalPlaces));
    }
    // Math Type: Divide
    else if (mathType === 'Divide') {
      return numberOneInteger / numberTwoInteger;
    }
  }
  // Decimal Places: Number Two Has More
  else if (numberOneDecimalPlaces < numberTwoDecimalPlaces) {
    // Integers (Off By Decimal Places)
    const numberOneInteger: number = numberOne * Math.pow(10, numberTwoDecimalPlaces);
    const numberTwoInteger: number = numberTwo * Math.pow(10, numberTwoDecimalPlaces);

    // Math Type: Add
    if (mathType === 'Add') {
      // Integer Total
      const integerTotal: number = numberOneInteger + numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberTwoDecimalPlaces);
    }
    // Math Type: Subtract
    else if (mathType === 'Subtract') {
      // Integer Total
      const integerTotal: number = numberOneInteger - numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberTwoDecimalPlaces);
    }
    // Math Type: Multiply
    else if (mathType === 'Multiply') {
      // Integer Total
      const integerTotal: number = numberOneInteger * numberTwoInteger;

      // Decimal Total (Convert Back X Amount Of Decimal Places)
      return integerTotal / Math.pow(10, numberOneDecimalPlaces + numberTwoDecimalPlaces + (numberTwoDecimalPlaces - numberOneDecimalPlaces));
    }
    // Math Type: Divide
    else if (mathType === 'Divide') {
      return numberOneInteger / numberTwoInteger;
    }
  }
};

Add:

mathExact('Add', 1, 2); // 3
mathExact('Add', .1, .2);  // .3
mathExact('Add', 1.123, .2);  // 1.323
mathExact('Add', .02, 1.123); // 1.143

Subtract:

mathExact('Subtract', 1, 2): // -1
mathExact('Subtract', .1, .2);  // -.1
mathExact('Subtract', 1.123, .2);  // .923
mathExact('Subtract', .02, 1.123); // -1.103

Multiply:

mathExact('Multiply', 1, 2); // 2
mathExact('Multiply', .1, .2);  // .02
mathExact('Multiply', 1.123, .2);  // .2246
mathExact('Multiply', .02, 1.123); // .002246

Divide:

mathExact('Divide', 1, 2); // .5
mathExact('Divide', .1, .2);  // .5
mathExact('Divide', 1.123, .2);  // 5.615
mathExact('Divide', .02, 1.123); // .017809439002671415

How to mock static methods in c# using MOQ framework?

Moq cannot mock a static member of a class.

When designing code for testability it's important to avoid static members (and singletons). A design pattern that can help you refactoring your code for testability is Dependency Injection.

This means changing this:

public class Foo
{
    public Foo()
    {
        Bar = new Bar();
    }
}

to

public Foo(IBar bar)
{
    Bar = bar;
}

This allows you to use a mock from your unit tests. In production you use a Dependency Injection tool like Ninject or Unity wich can wire everything together.

I wrote a blog about this some time ago. It explains which patterns an be used for better testable code. Maybe it can help you: Unit Testing, hell or heaven?

Another solution could be to use the Microsoft Fakes Framework. This is not a replacement for writing good designed testable code but it can help you out. The Fakes framework allows you to mock static members and replace them at runtime with your own custom behavior.

Clearing <input type='file' /> using jQuery

I have managed to get this to work using the following...

function resetFileElement(ele) 
{
    ele.val(''); 
    ele.wrap('<form>').parent('form').trigger('reset');   
    ele.unwrap();
    ele.prop('files')[0] = null;
    ele.replaceWith(ele.clone());    
}

This has been tested in IE10, FF, Chrome & Opera.

There are two caveats...

  1. Still doesn't work properly in FF, if you refresh the page, the file element gets re-populated with the selected file. Where it is getting this info from is beyond me. What else related to a file input element could I possible try to clear?

  2. Remember to use delegation on any events you had attached to the file input element, so they still work when the clone is made.

What I don't understand is who on earth thought not allowing you to clear an input field from an invalid unacceptable file selection was a good idea?

OK, don't let me dynamically set it with a value so I can't leach files from a user's OS, but let me clear an invalid selection without resetting an entire form.

It's not like 'accept' does anything other than a filter anyhow and in IE10, it doesn't even understand MS Word mime types, it's a joke!

What is the difference between x86 and x64

x64 is a generic name for the 64-bit extensions to Intel's and AMD's 32-bit x86 instruction set architecture (ISA). AMD introduced the first version of x64, initially called x86-64 and later renamed AMD64. Intel named their implementation IA-32e and then EMT64.

Show history of a file?

Have you tried this:

gitk path/to/file

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

How to center a checkbox in a table cell?

My problem was that there was a parent style with position: absolute !important which I was not allowed to edit.

So I gave my specific checkbox position: relative !important and it fixed the vertical misalignment issue.