Programs & Examples On #Mixed authentication

Node.js global proxy setting

replace {userid} and {password} with your id and password in your organization or login to your machine.

npm config set proxy http://{userid}:{password}@proxyip:8080/
npm config set https-proxy http://{userid}:{password}@proxyip:8080/
npm config set http-proxy http://{userid}:{password}@proxyip:8080/
strict-ssl=false

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

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

What are enums and why are they useful?

Now why and what for should I used enum in day to day programming?

You can use an Enum to represent a smallish fixed set of constants or an internal class mode while increasing readability. Also, Enums can enforce a certain rigidity when used in method parameters. They offer the interesting possibility of passing information to a constructor like in the Planets example on Oracle's site and, as you've discovered, also allow a simple way to create a singleton pattern.

ex: Locale.setDefault(Locale.US) reads better than Locale.setDefault(1) and enforces the use of the fixed set of values shown in an IDE when you add the . separator instead of all integers.

Download data url file

If you also want to give a suggested name to the file (instead of the default 'download') you can use the following in Chrome, Firefox and some IE versions:

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}

And the following example shows it's use:

downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Difference between javacore, thread dump and heap dump in Websphere

A Thread dump is a dump of all threads's stack traces, i.e. as if each Thread suddenly threw an Exception and printStackTrace'ed that. This is so that you can see what each thread is doing at some specific point, and is for example very good to catch deadlocks.

A heap dump is a "binary dump" of the full memory the JVM is using, and is for example useful if you need to know why you are running out of memory - in the heap dump you could for example see that you have one billion User objects, even though you should only have a thousand, which points to a memory retention problem.

How can I hide the Android keyboard using JavaScript?

I made a jquery plugin out of the answer of QuickFix

(function ($) {
  $.fn.hideKeyboard = function() {
    var inputs = this.filter("input").attr('readonly', 'readonly'); // Force keyboard to hide on input field.
    var textareas = this.filter("textarea").attr('disabled', 'true'); // Force keyboard to hide on textarea field.
    setTimeout(function() {
      inputs.blur().removeAttr('readonly');  //actually close the keyboard and remove attributes
      textareas.blur().removeAttr('disabled');
    }, 100);
    return this;
  };
}( jQuery ));

Usage examples:

$('#myInput').hideKeyboard(); 
$('#myForm input,#myForm textarea').hideKeyboard(); 

Language Books/Tutorials for popular languages

Java

Java Notes - Very Neat for novice java programmer

Add JVM options in Tomcat

Set it in the JAVA_OPTS variable in [path to tomcat]/bin/catalina.sh. Under windows there is a console where you can set it up or you use the catalina.bat.

JAVA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5

Printing list elements on separated lines in Python

Sven Marnach's answer is pretty much it, but has one generality issue... It will fail if the list being printed doesn't just contain strings.

So, the more general answer to "How to print out a list with elements separated by newlines"...

print '\n'.join([ str(myelement) for myelement in mylist ])

Then again, the print function approach JBernardo points out is superior. If you can, using the print function instead of the print statement is almost always a good idea.

Parsing JSON Object in Java

I'm assuming you want to store the interestKeys in a list.

Using the org.json library:

JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("interestKey"));
}

Php $_POST method to get textarea value

Remove some of your textarea class like

<textarea name="Address" rows="3" class="input-text full-width" placeholder="Your Address" ></textarea>

To

<textarea name="Address" rows="3" class="full-width" placeholder="Your Address" ></textarea>

It's dependent on your template (Purchased Template). The developer has included some JavaScript to get the value from correct object on UI, but class like input-text just finds only $('input[type=text]'), that's why.

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

How to create a link to another PHP page

Use like this

<a href="index.php">Index Page</a>
<a href="page2.php">Page 2</a>

How to add image background to btn-default twitter-bootstrap button?

_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook_x000D_
  {_x000D_
    background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover_x000D_
  {_x000D_
    background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
<p>My current button got white background<br/>_x000D_
<input type="button" value="Sign In with Facebook" class="sign-in-facebook btn btn-secondary" style="margin-top:2px; margin-bottom:2px;" >_x000D_
</p>_x000D_
<p>I need the current btn-default style like below<br/>_x000D_
<input type="button" class="btn btn-default" value="Sign In with Facebook" />_x000D_
</p>_x000D_
<strong>NOTE:</strong> facebook icon at left side of the button.
_x000D_
_x000D_
_x000D_

How does one convert a grayscale image to RGB in OpenCV (Python)?

One you convert your image to gray-scale you cannot got back. You have gone from three channel to one, when you try to go back all three numbers will be the same. So the short answer is no you cannot go back. The reason your backtorgb function this throwing that error is because it needs to be in the format:

CvtColor(input, output, CV_GRAY2BGR)

OpenCV use BGR not RGB, so if you fix the ordering it should work, though your image will still be gray.

Switch/toggle div (jQuery)

You could write a simple jQuery plugin to do this. The plugin would look like:

(function($) {
    $.fn.expandcollapse = function() {
        return this.each(function() {
            obj = $(this);
            switch (obj.css("display")) {
                case "block":
                    displayValue = "none";
                    break;

                case "none":
                default:
                    displayValue = "block";
            }

            obj.css("display", displayValue);
        });
    };
} (jQuery));

Then wire the plugin up to the click event for the anchor tag:

$(document).ready(function() {
    $("#mylink").click(function() {
        $("div").expandcollapse();
    });
});

Providing that you set the initial 'display' attributes for each div to be 'block' and 'none' respectively, they should switch to being shown/hidden when the link is clicked.

Javascript change font color

You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor() method to define color, .fontsize() method to define the font size, .bold() method to define bold, etc. These are called JavaScript Built-in Functions.

  • Here is a list of some JavaScript built-in functions:

    .big()
    .small()
    .italics()
    .fixed()
    .strike()
    .sup()

  • The below built-in functions require parameters:

    .fontsize() //e.g.: the size to be applied in number .fontsize(4)

    .fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")

    .txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")

    .toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()

  • Remember the syntax is: string.functionName() e.g.:

    var txt = "Hello World!"; txt.bold();

  • This also can be done in one line:

    var txt = "Hello World!".bold();

    The result will be: Hello World!

  • You can use multiple built-in functions in one line, adding one next to the other. e.g.:

    "10/22/2018".fontcolor("red").fontsize(4).bold()

  • The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:

vForm.message = "<HTML><font size = 4 color = 'red'><b> Application Deadline was </b></font></HTML> " + "10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font color, size, bold and combined them with JavaScript functions to change font color, size, bold in JavaScript code */

  • Here is the result:

Application Deadline was  10/22/2018

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")

Result:

2011-08-09T23:49:58+02:00

Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:

DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")

Custom Date and Time Format Strings

SQL is null and = null

In SQL, a comparison between a null value and any other value (including another null) using a comparison operator (eg =, !=, <, etc) will result in a null, which is considered as false for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).

The reasoning is that a null means "unknown", so the result of any comparison to a null is also "unknown". So you'll get no hit on rows by coding where my_column = null.

SQL provides the special syntax for testing if a column is null, via is null and is not null, which is a special condition to test for a null (or not a null).

Here's some SQL showing a variety of conditions and and their effect as per above.

create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);

select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);

returns only 1 row (as expected):

TEST    X   Y
x = y   1   1

See this running on SQLFiddle

How do I handle ImeOptions' done button click?

Kotlin Solution

The base way to handle it in Kotlin is:

edittext.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        callback.invoke()
        true
    }
    false
}

Kotlin Extension

Use this to just call edittext.onDone{/*action*/} in your main code. Makes your code far more readable and maintainable

fun EditText.onDone(callback: () -> Unit) {
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            callback.invoke()
            true
        }
        false
    }
}

Don't forget to add these options to your edittext

<EditText ...
    android:imeOptions="actionDone"
    android:inputType="text"/>

If you need inputType="textMultiLine" support, read this post

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

For any case set overflow-x to hidden and I prefer to set max-height in order to limit the expansion of the height of the div. Your code should looks like this:

overflow-y: scroll;
overflow-x: hidden;
max-height: 450px;

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

How to prevent caching of my Javascript file?

<script src="test.js?random=<?php echo uniqid(); ?>"></script>

EDIT: Or you could use the file modification time so that it's cached on the client.

<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>

What is the difference between sed and awk?

1) What is the difference between awk and sed ?

Both are tools that transform text. BUT awk can do more things besides just manipulating text. Its a programming language by itself with most of the things you learn in programming, like arrays, loops, if/else flow control etc You can "program" in sed as well, but you won't want to maintain the code written in it.

2) What kind of application are best use cases for sed and awk tools ?

Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk. You will reduce your learning curve as well.

What is a regex to match ONLY an empty string?

The answer may be language dependent, but since you don't mention one, here is what I just came up with in js:

 var a = ['1','','2','','3'].join('\n');

 console.log(a.match(/^.{0}$/gm)); // ["", ""]

 // the "." is for readability. it doesn't really matter
 a.match(/^[you can put whatever the hell you want and this will also work just the same]{0}$/gm)

You could also do a.match(/^(.{10,}|.{0})$/gm) to match empty lines OR lines that meet a criteria. (This is what I was looking for to end up here.)

I know that ^ will match the beginning of any line and $ will match the end of any line

This is only true if you have the multiline flag turned on, otherwise it will only match the beginning/end of the string. I'm assuming you know this and are implying that, but wanted to note it here for learners.

IntelliJ: Working on multiple projects

In IntelliJ 14.1.2, I did it like following:

Select File->Project Structure->Modules.

Select + and Import Module and select the directory of your project(or directory where pom exists) and click OK.

Follow through the next flow of screens and after you click Finish, you should see the project alongside your existing one.

enter image description here

JSON to string variable dump

something along this?

function dump(x, indent) {
    var indent = indent || '';
    var s = '';
    if (Array.isArray(x)) {
        s += '[';
        for (var i=0; i<x.length; i++) {
            s += dump(x[i], indent)
            if (i < x.length-1) s += ', ';
        }
        s +=']';
    } else if (x === null) {
      s = 'NULL';
    } else switch(typeof x) {
        case 'undefined':
            s += 'UNDEFINED';
            break;
        case 'object':
            s += "{ ";
            var first = true;
            for (var p in x) {
                if (!first) s += indent + '  ';
                s += p + ': ';
                s += dump(x[p], indent + '  ');
                s += "\n"
                first = false;
            }
            s += '}';
            break;
        case 'boolean':
            s += (x) ? 'TRUE' : 'FALSE';
            break;
        case 'number':
            s += x;
            break;
        case 'string':
            s += '"' + x + '"';
            break;
        case 'function':
            s += '<FUNCTION>';
            break;
        default:
            s += x;
            break;
    }
    return s;
}

Difference between require, include, require_once and include_once?

Difference between _once functions and without _once functions: without _once code will be included again whereas with _once functions PHP keeps track of the included files and will include it only once.

Difference between require and include: If a required file is not found PHP will emit a fatal error whereas for include only a warning will be emitted.

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

Received an invalid column length from the bcp client for colid 6

Check the size of the columns in the table you are doing bulk insert/copy. the varchar or other string columns might needs to be extended or the value your are inserting needs to be trim. Column order also should be same as in table.

e.g, Increase size of varchar column 30 to 50 =>

ALTER TABLE [dbo].[TableName] ALTER COLUMN [ColumnName] Varchar(50)

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.

Access non-numeric Object properties by index?

"I'm specifically looking to target the index, just like the first example - if it's possible."

No, it isn't possible.

The closest you can get is to get an Array of the object's keys, and use that:

var keys = Object.keys( obj );

...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:

keys[ 0 ];  // 'evenmore'
keys[ 1 ];  // 'something'

LINQ: Select where object does not contain items from list

dump this into a more specific collection of just the ids you don't want

var notTheseBarIds = filterBars.Select(fb => fb.BarId);

then try this:

fooSelect = (from f in fooBunch
             where !notTheseBarIds.Contains(f.BarId)
             select f).ToList();

or this:

fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();

How to remove the hash from window.location (URL) with JavaScript without page refresh?

$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});

Regex select all text between tags

I use this solution:

preg_match_all( '/<((?!<)(.|\n))*?\>/si',  $content, $new);
var_dump($new);

MSVCP120d.dll missing

My problem was with x64 compilations deployed to a remote testing machine. I found the x64 versions of msvp120d.dll and msvcr120d.dll in

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\redist\Debug_NonRedist\x64\Microsoft.VC120.DebugCRT

What's the Android ADB shell "dumpsys" tool and what are its benefits?

According to official Android information about dumpsys:

The dumpsys tool runs on the device and provides information about the status of system services.

To get a list of available services use

adb shell dumpsys -l

Height equal to dynamic width (CSS fluid layout)

Using jQuery you can achieve this by doing

var cw = $('.child').width();
$('.child').css({'height':cw+'px'});

Check working example at http://jsfiddle.net/n6DAu/1/

PHP preg_replace special characters

do this in two steps:

  1. replace not letter characters with this regex:

    [\/\&%#\$]

  2. replace quotes with this regex:

    [\"\']

and use preg_replace:

$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);

update query with join on two tables

Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like

Update addresses
Set cid = (
            Select c.id
            From customers As c
            where c.id = a.id
            )
Where Exists    (
                Select 1
                From customers As C1
                Where C1.id = addresses.id
                )

However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:

Update addresses
Set cid = c.id
From addresses As a
    Join customers As c
        On c.id = a.id

TypeError: method() takes 1 positional argument but 2 were given

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

Print a list in reverse order with range()?

You can do printing of reverse numbers with range() BIF Like ,

for number in range ( 10 , 0 , -1 ) :
    print ( number ) 

Output will be [10,9,8,7,6,5,4,3,2,1]

range() - range ( start , end , increment/decrement ) where start is inclusive , end is exclusive and increment can be any numbers and behaves like step

How to fix getImageData() error The canvas has been tainted by cross-origin data?

You won't be able to draw images directly from another server into a canvas and then use getImageData. It's a security issue and the canvas will be considered "tainted".

Would it work for you to save a copy of the image to your server using PHP and then just load the new image? For example, you could send the URL to the PHP script and save it to your server, then return the new filename to your javascript like this:

<?php //The name of this file in this example is imgdata.php

  $url=$_GET['url'];

  // prevent hackers from uploading PHP scripts and pwning your system
  if(!@is_array(getimagesize($url))){
    echo "path/to/placeholderImage.png";
    exit("wrong file type.");
  }

  $img = file_get_contents($url);

  $fn = substr(strrchr($url, "/"), 1);
  file_put_contents($fn,$img);
  echo $fn;

?>

You'd use the PHP script with some ajax javascript like this:

xi=new XMLHttpRequest();
xi.open("GET","imgdata.php?url="+yourImageURL,true);
xi.send();

xi.onreadystatechange=function() {
  if(xi.readyState==4 && xi.status==200) {
    img=new Image;
    img.onload=function(){ 
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    }
    img.src=xi.responseText;
  }
}

If you use getImageData on the canvas after that, it will work fine.

Alternatively, if you don't want to save the whole image, you could pass x & y coordinates to your PHP script and calculate the pixel's rgba value on that side. I think there are good libraries for doing that kind of image processing in PHP.

If you want to use this approach, let me know if you need help implementing it.

edit-1: peeps pointed out that the php script is exposed and allows the internet to potentially use it maliciously. there are a million ways to handle this, one of the simplest being some sort of URL obfuscation... i reckon secure php practices deserves a separate google ;P

edit-2: by popular demand, I've added a check to ensure it is an image and not a php script (from: PHP check if file is an image).

Stop fixed position at footer

I was working on stopping the adbanner at a certain point before footer. And played with the code I found above.

Worked for me (banner disappears right before footer and reappears on scroll to top):

<style>
#leftsidebanner {width:300px;height:600px;position: fixed; padding: 0;top:288px;right:5%;display: block;background-color: aqua}
</style>

<div id="leftsidebanner">
</div>


<script>

    $.fn.followTo = function (pos) {
    var stickyAd = $(this),
    theWindow = $(window);
    $(window).scroll(function (e) {
      if ($(window).scrollTop() > pos) {
        stickyAd.css({'position': 'absolute','bottom': pos});
      } else {
        stickyAd.css({'position': 'fixed','top': '100'});
      }
    });
  };
  $('#leftsidebanner').followTo(2268);


</script>

What is the difference between call and apply?

Even though call and apply achive the same thing, I think there is atleast one place where you cannot use call but can only use apply. That is when you want to support inheritance and want to call the constructor.

Here is a function allows you to create classes which also supports creating classes by extending other classes.

function makeClass( properties ) {
    var ctor = properties['constructor'] || function(){}
    var Super = properties['extends'];
    var Class = function () {
                 // Here 'call' cannot work, only 'apply' can!!!
                 if(Super)
                    Super.apply(this,arguments);  
                 ctor.apply(this,arguments);
                }
     if(Super){
        Class.prototype = Object.create( Super.prototype );
        Class.prototype.constructor = Class;
     }
     Object.keys(properties).forEach( function(prop) {
           if(prop!=='constructor' && prop!=='extends')
            Class.prototype[prop] = properties[prop];
     });
   return Class; 
}

//Usage
var Car = makeClass({
             constructor: function(name){
                         this.name=name;
                        },
             yourName: function() {
                     return this.name;
                   }
          });
//We have a Car class now
 var carInstance=new Car('Fiat');
carInstance.youName();// ReturnsFiat

var SuperCar = makeClass({
               constructor: function(ignore,power){
                     this.power=power;
                  },
               extends:Car,
               yourPower: function() {
                    return this.power;
                  }
              });
//We have a SuperCar class now, which is subclass of Car
var superCar=new SuperCar('BMW xy',2.6);
superCar.yourName();//Returns BMW xy
superCar.yourPower();// Returns 2.6

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

How to set background image in Java?

Firstly create a new class that extends the WorldView class. I called my new class Background. So in this new class import all the Java packages you will need in order to override the paintBackground method. This should be:

import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;

Next after the class name make sure that it says extends WorldView. Something like this:

public class Background extends WorldView

Then declare the variables game of type Game and an image variable of type Image something like this:

private Game game;
private Image image;

Then in the constructor of this class make sure the game of type Game is in the signature of the constructor and that in the call to super you will have to initialise the WorldView, initialise the game and initialise the image variables, something like this:

super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();

Then you just override the paintBackground method in exactly the same way as you did when overriding the paint method in the Player class. Just like this:

public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}

Now finally you have to declare a class level reference to the new class you just made in the Game class and initialise this in the Game constructor, something like this:

private Background image;

And in the Game constructor:
image = new Background(this);

Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable frame has been declared:

frame.add(image);

Make sure you add this code just before frame.pack();. Also make sure you use a background image that isn't too big!

Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.

python error: no module named pylab

I installed python-numpy python-scipy python-matplotlib, but it didn't work for me and I got the same error. Pylab isn't recognized without matplotlib. So I used this:

from matplotlib import pylab
from pylab import *

and worked for me.

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Syntax for a single-line Bash infinite while loop

You can try this too WARNING: this you should not do but since the question is asking for infinite loop with no end...this is how you could do it.

while [[ 0 -ne 1 ]]; do echo "it's looping";   sleep 2; done

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

How to place and center text in an SVG rectangle

For horizontal and vertical alignment of text in graphics, you might want to use the following CSS styles. In particular, note that dominant-baseline:middle is probably wrong, since this is (usually) half way between the top and the baseline, rather than half way between the top and the bottom. Also, some some sources (e.g. Mozilla) use dominant-baseline:hanging instead of dominant-baseline:text-before-edge. This is also probably wrong, since hanging is designed for Indic scripts. Of course, if you're using a mixture of Latin, Indic, ideographs or whatever, you'll probably need to read the documentation.

/* Horizontal alignment */
text.goesleft{text-anchor:end}
text.equalleftright{text-anchor:middle}
text.goesright{text-anchor:start}
/* Vertical alignment */
text.goesup{dominant-baseline:text-after-edge}
text.equalupdown{dominant-baseline:central}
text.goesdown{dominant-baseline:text-before-edge}
text.ruledpaper{dominant-baseline:alphabetic}

Edit: I've just noticed that Mozilla also uses dominant-baseline:baseline which is definitely wrong: it's not even a recognized value! I assume it's defaulting to the font default, which is alphabetic, so they got lucky.

More edit: Safari (11.1.2) understands text-before-edge but not text-after-edge. It also fails on ideographic. Great stuff, Apple. So you might be forced to use alphabetic and allow for descenders after all. Sorry.

Vim: How to insert in visual block mode?

if you want to add new text before or after the selected colum:

  • press ctrl+v
  • select columns
  • press shift+i
  • write your text
  • press esc
  • press "jj"

hibernate: LazyInitializationException: could not initialize proxy

If you know about the impact of lazy=false and still want to makes it as default (e.g., for prototyping purposes), you can use any of the following:

  • if you are using XML configuration: add default-lazy="false" to your <hibernate-mapping> element
  • if you are using annotation configuration: add @Proxy(lazy=false) to your entity class(es)

What are the differences between ArrayList and Vector?

Differences

  • Vectors are synchronized, ArrayLists are not.
  • Data Growth Methods

Use ArrayLists if there is no specific requirement to use Vectors.

Synchronization

If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.

Collections.synchronizedList is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.

Reference

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Reference

How to parse a JSON Input stream

For those that pointed out the fact that you can't use the toString method of InputStream like this see https://stackoverflow.com/a/5445161/1304830 :

My correct answer would be then :

import org.json.JSONObject;

public static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

...

JSONObject json = new JSONObject(convertStreamToString(url.openStream());

Check difference in seconds between two times

Assuming dateTime1 and dateTime2 are DateTime values:

var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;

In your case, you 'd use DateTime.Now as one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1 is earlier than dateTime2.

How to put more than 1000 values into an Oracle IN clause

Instead of using IN clause, can you try using JOIN with the other table, which is fetching the id. that way we don't need to worry about limit. just a thought from my side.

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

How to center and crop an image to always appear in square shape with CSS?

object-fit property does the magic. On JsFiddle.

CSS

.image {
  width: 160px;
  height: 160px;
}

.object-fit_fill {
  object-fit: fill
}

.object-fit_contain {
  object-fit: contain
}

.object-fit_cover {
  object-fit: cover
}

.object-fit_none {
  object-fit: none
}

.object-fit_scale-down {
  object-fit: scale-down
}

HTML

<div class="original-image">
  <p>original image</p>
  <img src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: fill</p>
  <img class="object-fit_fill" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: contain</p>
  <img class="object-fit_contain" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: cover</p>
  <img class="object-fit_cover" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: none</p>
  <img class="object-fit_none" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: scale-down</p>
  <img class="object-fit_scale-down" src="http://lorempixel.com/500/200">
</div>

Result

How the rendered images look (in a browser that supports <code>object-fit</code>)

Find files and tar them (with spaces)

Would add a comment to @Steve Kehlet post but need 50 rep (RIP).

For anyone that has found this post through numerous googling, I found a way to not only find specific files given a time range, but also NOT include the relative paths OR whitespaces that would cause tarring errors. (THANK YOU SO MUCH STEVE.)

find . -name "*.pdf" -type f -mtime 0 -printf "%f\0" | tar -czvf /dir/zip.tar.gz --null -T -
  1. . relative directory

  2. -name "*.pdf" look for pdfs (or any file type)

  3. -type f type to look for is a file

  4. -mtime 0 look for files created in last 24 hours

  5. -printf "%f\0" Regular -print0 OR -printf "%f" did NOT work for me. From man pages:

This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use '\0' as a terminator than to use newline, as file names can contain white space and newline characters.

  1. -czvf create archive, filter the archive through gzip , verbosely list files processed, archive name

Edit 2019-08-14: I would like to add, that I was also able to use essentially use the same command in my comment, just using tar itself:

tar -czvf /archiveDir/test.tar.gz --newer-mtime=0 --ignore-failed-read *.pdf

Needed --ignore-failed-read in-case there were no new PDFs for today.

Java POI : How to read Excel cell value and not the formula computing it?

SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked . I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies . Full code is given below with exact imports.

 import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;

    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.util.CellReference;
    import org.apache.poi.sl.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellType;
    import org.apache.poi.ss.usermodel.CellValue;
    import org.apache.poi.ss.usermodel.FormulaEvaluator;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;


    public class ReadExcelFormulaValue {

        private static final CellType NUMERIC = null;
        public static void main(String[] args) {
            try {
                readFormula();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public static void readFormula() throws IOException {
            FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
            org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

            CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
            Row row = sheet.getRow(cellReference.getRow());
            Cell cell = row.getCell(cellReference.getCol());

            CellValue cellValue = evaluator.evaluate(cell);
            System.out.println("Cell type month  is "+cellValue.getCellTypeEnum());
            System.out.println("getNumberValue month is  "+cellValue.getNumberValue());     
          //  System.out.println("getStringValue "+cellValue.getStringValue());


            cellReference = new CellReference("H2"); // pass the cell which contains the formula
             row = sheet.getRow(cellReference.getRow());
             cell = row.getCell(cellReference.getCol());

            cellValue = evaluator.evaluate(cell);
            System.out.println("getNumberValue DAY is  "+cellValue.getNumberValue());    


        }

    }

How do I update a GitHub forked repository?

Starting in May 2014, it is possible to update a fork directly from GitHub. This still works as of September 2017, BUT it will lead to a dirty commit history.

  1. Open your fork on GitHub.
  2. Click on Pull Requests.
  3. Click on New Pull Request. By default, GitHub will compare the original with your fork, and there shouldn't be anything to compare if you didn't make any changes.
  4. Click switching the base if you see that link. Otherwise, manually set the base fork drop down to your fork, and the head fork to the upstream. Now GitHub will compare your fork with the original, and you should see all the latest changes. enter image description here
  5. Create pull request and assign a predictable name to your pull request (e.g., Update from original).
  6. Scroll down to Merge pull request, but don't click anything yet.

Now you have three options, but each will lead to a less-than-clean commit history.

  1. The default will create an ugly merge commit.
  2. If you click the dropdown and choose "Squash and merge", all intervening commits will be squashed into one. This is most often something you don't want.
  3. If you click Rebase and merge, all commits will be made "with" you, the original PRs will link to your PR, and GitHub will display This branch is X commits ahead, Y commits behind <original fork>.

So yes, you can keep your repo updated with its upstream using the GitHub web UI, but doing so will sully your commit history. Stick to the command line instead - it's easy.

'POCO' definition

"Plain Old C# Object"

Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.

EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.

TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.

See below for an example of each.

Example of a POCO:

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

Example of something that isn’t a POCO:

public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}

The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.

Purge or recreate a Ruby on Rails database

According to Rails guide, this one liner should be used because it would load from the schema.rb instead of reloading the migration files one by one:

rake db:reset

How can I find which tables reference a given table in Oracle SQL Developer?

SELECT DISTINCT table_name, 
                constraint_name, 
                column_name, 
                r_table_name, 
                position, 
                constraint_type 
FROM   (SELECT uc.table_name, 
               uc.constraint_name, 
               cols.column_name, 
               (SELECT table_name 
                FROM   user_constraints 
                WHERE  constraint_name = uc.r_constraint_name) r_table_name, 
               (SELECT column_name 
                FROM   user_cons_columns 
                WHERE  constraint_name = uc.r_constraint_name 
                       AND position = cols.position)           r_column_name, 
               cols.position, 
               uc.constraint_type 
        FROM   user_constraints uc 
               inner join user_cons_columns cols 
                       ON uc.constraint_name = cols.constraint_name 
        WHERE  constraint_type != 'C') 
START WITH table_name = '&&tableName' 
           AND column_name = '&&columnName' 
CONNECT BY NOCYCLE PRIOR table_name = r_table_name 
                         AND PRIOR column_name = r_column_name; 

How do I tell Python to convert integers into words

#This valid till 4 digit number
numbers={1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine',
10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen',
17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 
60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand'}

def my_fun(num):
    list = []
    num_len = len(str(num)) - 1
    while num_len > 0 and num > 0:
       while num_len > 0 and num > 0:
        if num in numbers and num < 1000:
            list.append(numbers[num])
            num_len = 0
        elif num < 100:
            list.extend([numbers[num - num%10], numbers[num%10]])
            num_len = 0
        else:
            quotent = num//10**num_len # 4567//1000= 4
            num = num % 10**num_len #4567%1000 =567
            if quotent != 0 :
                list.append(numbers[quotent])
                list.append(numbers[10**num_len])
            else:
                list.append(numbers[num])
            num_len -= 1
    return ' '.join(list)

Remove portion of a string after a certain character

How about using explode:

$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];

Advantages:

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

Absolutely Asset Catalog is you answer, it removes the need to follow naming conventions when you are adding or updating your app icons.

Below are the steps to Migrating an App Icon Set or Launch Image Set From Apple:

1- In the project navigator, select your target.

2- Select the General pane, and scroll to the App Icons section.

enter image description here

3- Specify an image in the App Icon table by clicking the folder icon on the right side of the image row and selecting the image file in the dialog that appears.

enter image description here

4-Migrate the images in the App Icon table to an asset catalog by clicking the Use Asset Catalog button, selecting an asset catalog from the popup menu, and clicking the Migrate button.

enter image description here

Alternatively, you can create an empty app icon set by choosing Editor > New App Icon, and add images to the set by dragging them from the Finder or by choosing Editor > Import.

simple vba code gives me run time error 91 object variable or with block not set

Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

It's likely that setting your DLL to CopyLocal/true or any of the other major fixes for this will fix your issue, but here is another edge-case that caught me for 20 minutes of wasted time.

When you add your namespaces to your Views/Web.config, ensure they are cased correctly:

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="THE.NameSpace" />
        <add namespace="THE.Namespace" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

width:auto for <input> fields

It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.

How can I read large text files in Python, line by line, without loading it into memory?

All you need to do is use the file object as an iterator.

for line in open("log.txt"):
    do_something_with(line)

Even better is using context manager in recent Python versions.

with open("log.txt") as fileobject:
    for line in fileobject:
        do_something_with(line)

This will automatically close the file as well.

Attach parameter to button.addTarget action in Swift

For Swift 2.X and above

button.addTarget(self,action:#selector(YourControllerName.buttonClicked(_:)),
                         forControlEvents:.TouchUpInside)

Generic Property in C#

public class MyProp<T>
{
...
}

public class ClassThatUsesMyProp
{
public MyProp<String> SomeProperty { get; set; }
}

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

This may be a little late; but someone will find it useful.

There's a Nuget Package for integrating AdminLTE - a popular Bootstrap template - to MVC5

Simply run this command in your Visual Studio Package Manager console

Install-Package AdminLteMvc

NB: It may take a while to install because it downloads all necessary files as well as create sample full and partial views (.cshtml files) that can guide you as you develop. A sample layout file _AdminLteLayout.cshtml is also provided.

You'll find the files in ~/Views/Shared/ folder

How to allow download of .json file with ASP.NET

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

Display only date and no time

I am not sure in Razor but in ASPX you do:

 <%if (item.Modify_Date != null)
  {%>
     <%=Html.Encode(String.Format("{0:D}", item.Modify_Date))%>     
<%} %>

There must be something similar in Razor. Hopefully this will help someone.

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

$(document).ready(function(){
     $("#a").mouseover(function(){
         $("#b").css("background-color", "red");
     });
});

Python: finding lowest integer

You aren't comparing integers, you're comparing strings. Strings compare lexicographically -- meaning character by character -- instead of (as you seem to want) by converting the value to a float. Make your list hold numbers (floats or integers, depending on what you want), or convert the strings to floats or integers in your loop, before you compare them.

You may also be interested in the min builtin function, which already does what your current loop does (without the converting, that is.)

how to delete the content of text file without deleting itself

Just write:

FileOutputStream writer = new FileOutputStream("file.txt");

What is the best way to detect a mobile device?

You could do simple thing very simple like this

(window.screen.width < 700) {
    //The device is a Mobile
} else {
    //The device is a Desktop
}

How to use Typescript with native ES6 Promises

As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

This will include the promise declarations that comes with TypeScript without having to set the target to ES6.

How to get PID of process I've just started within java program?

If portability is not a concern, and you just want to get the pid on Windows without a lot of hassle while using code that is tested and known to work on all modern versions of Windows, you can use kohsuke's winp library. It is also available on Maven Central for easy consumption.

Process process = //...;
WinProcess wp = new WinProcess(process);
int pid = wp.getPid();

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR is equivalent to wchar_t const *. It's a pointer to a wide character string that won't be modified by the function call.

You can assign to LPCWSTRs by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";

LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx is defined as FindWindowExA or FindWindowExW depending on this definition.

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

Check if an array item is set in JS

Use the in keyword to test if a attribute is defined in a object

if (assoc_var in assoc_pagine)

OR

if ("home" in assoc_pagine)

There are quite a few issues here.

Firstly, is var supposed to a variable has the value "home", "work" or "about"? Or did you mean to inspect actual property called "var"?

If var is supposed to be a variable that has a string value, please note that var is a reserved word in JavaScript and you will need to use another name, such as assoc_var.

var assoc_var = "home";
assoc_pagine[assoc_var] // equals 0 in your example

If you meant to inspect the property called "var", then you simple need to put it inside of quotes.

assoc_pagine["var"]

Then, undefined is not the same as "undefined". You will need typeof to get the string representation of the objects type.

This is a breakdown of all the steps.

var assoc_var = "home"; 
var value = assoc_pagine[assoc_var]; // 0
var typeofValue = typeof value; // "number"

So to fix your problem

if (typeof assoc_pagine[assoc_var] != "undefined") 

update: As other answers have indicated, using a array is not the best sollution for this problem. Consider using a Object instead.

var assoc_pagine = new Object();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;

How do you scroll up/down on the console of a Linux VM

PERSISTENT, definitive solution

Add this line to your ~/.screenrc

termcapinfo xterm* ti@:te@

Now you can create a screen, and scroll it up/down with your mouse; Like you normally do.

Where is Python's sys.path initialized from?

"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"

-- http://docs.python.org/library/sys.html#sys.path

How to make HTML input tag only accept numerical values?

I updated some answers posted to add the following:

  • Add the method as extension method
  • Allow only one point to be entered
  • Specify how many numbers after the decimal point is allowed.

    String.prototype.isDecimal = function isDecimal(evt,decimalPts) {
        debugger;
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
            return false;
    
        //Prevent more than one point
        if (charCode == 46 && this.includes("."))
            return false;
    
        // Restrict the needed decimal digits
        if (this.includes("."))
        {
            var number = [];
            number = this.split(".");
            if (number[1].length == decimalPts)
                 return false;
         }
    
         return true;
    };
    

Class has no objects member

I was able to update the user settings.json

On my mac it was stored in:

~/Library/Application Support/Code/User/settings.json

Within it, I set the following:

{
    "python.linting.pycodestyleEnabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pylintPath": "pylint",
    "python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
}

That solved the issue for me.

How to create a thread?

The following ways work.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

How do I ignore all files in a folder with a Git repository in Sourcetree?

Right click on a file → IgnoreIgnore everything beneath.

If the Ignore option is grayed out then:

  1. Stage a file first
  2. Right click → Stop Tracking
  3. That file will appear in the pane below with a question mark → Right click on it→ Ignore

Enter image description here

DataTables: Cannot read property style of undefined

Funnily i was getting the following error for having one th-/th pair too many and still google directed me here. I'll leave it written down so people can find it.

jquery.dataTables.min.js:27 Uncaught TypeError: Cannot read property 'className' of undefined
at ua (jquery.dataTables.min.js:27)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:127)
at Function.each (jquery.min.js:2)
at n.fn.init.each (jquery.min.js:2)
at n.fn.init.j (jquery.dataTables.min.js:116)
at HTMLDocument.<anonymous> (history:619)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at Function.ready (jquery.min.js:2)
at HTMLDocument.K (jquery.min.js:2)

What is the difference between Cygwin and MinGW?

To use Cygwin in a commercial / proprietary / non-open-source application, you'll need to fork out tens of thousands of dollars for a "license buyout" from Red Hat; this invalidates the standard licensing terms at a considerable cost. Google "cygwin license cost" and see first few results.

For mingw, no such cost is incurred, and the licenses (PD, BSD, MIT) are extremely permissive. At most you may be expected to supply license details with your application, such as the winpthreads license required when using mingw64-tdm.

EDIT thanks to Izzy Helianthus: The commercial license is no longer available or necessary because the API library found in the winsup subdirectory of Cygwin is now being distributed under the LGPL, as opposed to the full GPL.

How to convert BigInteger to String in java

String input = "0101";
BigInteger x = new BigInteger ( input , 2 );
String output = x.toString(2);

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

jQuery Set Select Index

I often use trigger ('change') to make it work

$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');

Example with id select = selectA1 and position_index = 0 (frist option in select):

$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');

What is the role of "Flatten" in Keras?

It is rule of thumb that the first layer in your network should be the same shape as your data. For example our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.

Importing a function from a class in another file?

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME is w/o the suffix

Git Server Like GitHub?

Bare Bones Browser

git instaweb --httpd=webrick

from the git scm book

combine it with something like the approach described here for distributed development (credit to datagrok for the well described concept)

Launch a one-off git server from any local repository.

I tweeted this already but I thought it could use some expansion:

Enable decentralized git workflow: git config alias.serve "daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/"

Say you use a git workflow that involves working with a core "official" repository that you pull and push your changes from and into. I'm sure many companies do this, as do many users of git hosting services like Github.

Say that server, or Github, goes down for a bit.

No worries, after all, one of the reasons you use git is so you have a copy of the entire project history in your local clone.

You can keep right on coding and committing, while you wait for the operations team to bring the server back to life. Note to self: buy doughnuts for operations team.

But what if, during this downtime, you want to collaborate with another person, who may not be a git expert, on the same repository?

Or, instead of downtime, what if you and your collaborator are in the field, and for some reason you can't get your VPN to let you connect to your official repo?

Or, what if you and your collaborator are spiking out a bunch of experimental changes, and even though you have access, you don't want to push your unfinished mess into the official central repository? (Not even as feature branches.) Maybe you're in the middle of cleaning up a disastrous rebase or merge and the branches are all over the place.

Well, git, as you are probably aware, is a "distributed" version control system.

Even though you might use a central "official" git repository in your workflow, you still have the ability to use git in a peer-to-peer manner, where you and your collaborator simply build and share commits with each other, and the central server never even has to know.

So, how do you get your branches and commits over to them, or vice versa?

  • You could use git's facilities for e-mailing patches. But that's a bit inelegant and requires some knowledge on their end of how to apply e-mailed patches.
  • You could create an account on your own machine for your collaborator to ssh into. But maybe you don't have local root access, or maybe you don't trust them with SSH access to your box.
  • You could clone your repo onto a thumbdrive and pass it back and forth. But that's rather tedious, especially if you happen to be on the same local network, and requires a thumb drive.

You can probably think of other methods, too. But there's a super easy way: if you can see each other on the network, you can launch a one-off git server that they can use as their remote to clone, fetch, and pull your changes, and kill it when you're done with it.

The tool that enables this is git daemon, which has a lot of options and functionality, but for the purpose of enabling this easy one-off "just serve up the repo I'm in," the way to use it is to create an alias. I like to call it git serve. Run:

git config --global alias.serve "daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/"

Using an alias is actually crucial, because git aliases are executed in the base directory of your working tree. So the path '.git' will always point to the right place, no matter where you are within the directory tree of your repository.

Use your new git serve like so:

  1. Run git serve. "Ready to rumble," it will report. Git is bad-ass.
  2. Find out your IP address. Say it's 192.168.1.123.
  3. Say "hey Jane, I'm not ready/able to push these commits up to origin, but you can fetch my commits into your clone by running git fetch git://192.168.1.123/"
  4. Press ctrl+c when you don't want to serve that repo any longer.

You could also tell Jane to git clone git://192.168.1.123/ local-repo-name if she does not yet have a clone of the repository. Or, use git pull git://192.168.1.123/ branchname to do a fetch and merge at once, useful if you are working together on a feature branch.

Note however that you shouldn't do this on hostile networks if you keep secrets in your repository, because there's no authentication. It doesn't advertise its existence, but anybody with a a port scanner can find it, connect to it, and clone your repo.

But it's not super dangerous because it is read-only by default. Read the git daemon man page carefully if you think that you want to enable write access. In the case where you want to obtain your collaborator's commits, it's much safer to leave it read-only, and ask your collaborator to also run this command, so you can pull from them.

Tangentially related: on the subject of one-off servers, if you want to temporarily share a bunch of static files over HTTP: python -m SimpleHTTPServer

PHP + curl, HTTP POST sample code?

If you try to login on site with cookies.

This code:

if ($server_output == "OK") { ... } else { ... }

May not works if you try to login, because many sites returns status 200, but the post is not successful.

Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.

Also the post can be successful, but the status can be redirect instead 200.

To be sure the post is successful try this:

Follow location after the post, so it will go to the page where the post do redirect to:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

And than check if new cookies existing in the request:

if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 

{echo 'post successful'; }

else { echo 'not successful'; }

Java: how do I initialize an array size if it's unknown?

You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.

If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.

How to insert default values in SQL table?

Try it like this

INSERT INTO table1 (field1, field3) VALUES (5,10)

Then field2 and field4 should have default values.

Python float to int conversion

Languages that use binary floating point representations (Python is one) cannot represent all fractional values exactly. If the result of your calculation is 250.99999999999 (and it might be), then taking the integer part will result in 250.

A canonical article on this topic is What Every Computer Scientist Should Know About Floating-Point Arithmetic.

how to remove empty strings from list, then remove duplicate values from a list

To simplify Amiram Korach's solution:

dtList.RemoveAll(s => string.IsNullOrWhiteSpace(s))

No need to use Distinct() or ToList()

psql: could not connect to server: No such file or directory (Mac OS X)

WARNING: If you delete postmaster.pid without making sure there are really no postgres processes running you, could permanently corrupt your database. (PostgreSQL should delete it automatically if the postmaster has exited.).

SOLUTION: This fixed the issue--I deleted this file, and then everything worked!

/usr/local/var/postgres/postmaster.pid

--

and here is how I figured out why this needed to be deleted.

  1. I used the following command to see if there were any PG processes running. for me there were none, I couldn't even start the PG server:

    ps auxw | grep post
    
  2. I searched for the file .s.PGSQL.5432 that was in the error message above. i used the following command:

    sudo find / -name .s.PGSQL.5432 -ls
    

    this didn't show anything after searching my whole computer so the file didn't exist, but obviously psql "wanted it to" or "thought it was there".

  3. I took a look at my server logs and saw the following error:

    cat /usr/local/var/postgres/server.log
    

    at the end of the server log I see the following error:

    FATAL:  pre-existing shared memory block (key 5432001, ID 65538) is still in use
    HINT:  If you're sure there are no old server processes still running, remove the shared memory block or just delete the file "postmaster.pid".
    
  4. Following the advice in the error message, I deleted the postmaster.pid file in the same directory as server.log. This resolved the issue and I was able to restart.

So, it seems that my macbook freezing and being hard-rebooted caused Postgres to think that it's processes were still running even after reboot. Deleting this file resolved. Hope this helps others! Lots of people have similar issues but most the answers had to do with file permissions, whereas in my case things were different.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

how to dynamically add options to an existing select in vanilla javascript

This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript

Basically:

 daySelect = document.getElementById('daySelect');
 daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');

Http Servlet request lose params from POST body after read it once

Spring has built-in support for this with an AbstractRequestLoggingFilter:

@Bean
public Filter loggingFilter(){
    final AbstractRequestLoggingFilter filter = new AbstractRequestLoggingFilter() {
        @Override
        protected void beforeRequest(final HttpServletRequest request, final String message) {

        }

        @Override
        protected void afterRequest(final HttpServletRequest request, final String message) {

        }
    };

    filter.setIncludePayload(true);
    filter.setIncludeQueryString(false);
    filter.setMaxPayloadLength(1000000);

    return filter;
}

Unfortunately you still won't be able to read the payload directly off the request, but the String message parameter will include the payload so you can grab it from there as follows:

String body = message.substring(message.indexOf("{"), message.lastIndexOf("]"));

How to trim white space from all elements in array?

Try this:

String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
    trimmedArray[i] = array[i].trim();

Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:

for (int i = 0; i < array.length; i++)
    array[i] = array[i].trim();

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

For me the issue got resolved by doing the following:

Navigated to Tool --> Options --> Project and Solutions --> Web Projects

I could find the first check box "Use the 64 bit version of IIS Express of web sites and projects" was unchecked.

Selecting this check box helped me in launching the WCF Client.

VS Version : VS2019

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How to trigger click event on href element

I was facing a similar issue how to click a button, instead of a link. It did not success in the methods .trigger('click') or [0].click(), and I did not know why. At last, the following was working for me:

$('#elementid').mousedown();

How to have an automatic timestamp in SQLite?

Reading datefunc a working example of automatic datetime completion would be:

sqlite> CREATE TABLE 'test' ( 
   ...>    'id' INTEGER PRIMARY KEY,
   ...>    'dt1' DATETIME NOT NULL DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')), 
   ...>    'dt2' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime')), 
   ...>    'dt3' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime'))
   ...> );

Let's insert some rows in a way that initiates automatic datetime completion:

sqlite> INSERT INTO 'test' ('id') VALUES (null);
sqlite> INSERT INTO 'test' ('id') VALUES (null);

The stored data clearly shows that the first two are the same but not the third function:

sqlite> SELECT * FROM 'test';
1|2017-09-26 09:10:08|2017-09-26 09:10:08|2017-09-26 09:10:08.053
2|2017-09-26 09:10:56|2017-09-26 09:10:56|2017-09-26 09:10:56.894

Pay attention that SQLite functions are surrounded in parenthesis! How difficult was this to show it in one example?

Have fun!

Getting reference to the top-most view/window in iOS application

Usually that will give you the top view, but there's no guarantee that it's visible to the user. It could be off the screen, have an alpha of 0.0, or could be have size of 0x0 for example.

It could also be that the keyWindow has no subviews, so you should probably test for that first. This would be unusual, but it's not impossible.

UIWindow is a subclass of UIView, so if you want to make sure your notification is visible to the user, you can add it directly to the keyWindow using addSubview: and it will instantly be the top most view. I'm not sure if this is what you're looking to do though. (Based on your question, it looks like you already know this.)

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

Conditional Formatting using Excel VBA code

This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5 in this case) will be? Then I can try to provide a more complete answer.

Sub setCondFormat()
    Range("B3").Select
    With Range("B3:H63")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = 5287936
                .TintAndShade = 0
            End With
        End With
    End With
End Sub

Note: this is tested in Excel 2010.

Edit: Updated code based on comments.

What does the construct x = x || y mean?

double pipe operator

is this example usefull?

var section = document.getElementById('special');
if(!section){
     section = document.getElementById('main');
}

can also be

var section = document.getElementById('special') || document.getElementById('main');

What is the significance of 1/1/1753 in SQL Server?

Incidentally, Windows no longer knows how to correctly convert UTC to U.S. local time for certain dates in March/April or October/November of past years. UTC-based timestamps from those dates are now somewhat nonsensical. It would be very icky for the OS to simply refuse to handle any timestamps prior to the U.S. government's latest set of DST rules, so it simply handles some of them wrong. SQL Server refuses to process dates before 1753 because lots of extra special logic would be required to handle them correctly and it doesn't want to handle them wrong.

Make a link in the Android browser start up my app?

Once you have the intent and custom url scheme for your app set up, this javascript code at the top of a receiving page has worked for me on both iOS and Android:

<script type="text/javascript">
// if iPod / iPhone, display install app prompt
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i) ||
    navigator.userAgent.match(/android/i)) {
  var store_loc = "itms://itunes.com/apps/raditaz";
  var href = "/iphone/";
  var is_android = false;
  if (navigator.userAgent.match(/android/i)) {
    store_loc = "https://play.google.com/store/apps/details?id=com.raditaz";
    href = "/android/";
    is_android = true;
  }
  if (location.hash) {
    var app_loc = "raditaz://" + location.hash.substring(2);
    if (is_android) {
      var w = null;
      try {
        w = window.open(app_loc, '_blank');
      } catch (e) {
        // no exception
      }
      if (w) { window.close(); }
      else { window.location = store_loc; }
    } else {
      var loadDateTime = new Date();
      window.setTimeout(function() {
        var timeOutDateTime = new Date();
        if (timeOutDateTime - loadDateTime < 5000) {
          window.location = store_loc;
        } else { window.close(); }
      },
      25);
      window.location = app_loc;
    }
  } else {
    location.href = href;
  }
}
</script>

This has only been tested on the Android browser. I am not sure about Firefox or Opera. The key is even though the Android browser will not throw a nice exception for you on window.open(custom_url, '_blank'), it will fail and return null which you can test later.

Update: using store_loc = "https://play.google.com/store/apps/details?id=com.raditaz"; to link to Google Play on Android.

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.

1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?

YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).

But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.

2. If yes, is there other way that I don't have to install them but still can run my application?

Yes, there is at least one way. And it is the Managed port of ODP.NET.

Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.

But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using statements, for example: using Oracle.DataAccess.Client becomes using Oracle.ManagedDataAccess.Client and that's it! (Unless you were supposedly using some of the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect nodes from your app.config/web.config files and never sweat that junk again!

References:

Troubleshooting:

That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).

Common solutions I have found to this problem:

App is 64-bit?

  • Install 64-bit Oracle Client (32-bit one wont work)

App is 32-bit?

  • Install 32-bit Oracle Client (64-bit one wont work)

Oracle Client is already installed for the correct architecture?

  • Verify your environment PATH and ORACLE_HOME variables, make sure Oracle can be found (newer versions may use Registry instead)
  • Verify the ORACLE_HOME and settings in the Registry (And remember: Registry is either 32-bit or 64-bit, so make sure you check the one that matches your app!)
  • Verify permissions on the ORACLE_HOME folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users group.. fixing perms on the home folder fixed this.
  • As always, it is handy to Use SysInternals Process Monitor to find out what file is missing or can't be read.

RandomForestClassfier.fit(): ValueError: could not convert string to float

LabelEncoding worked for me (basically you've to encode your data feature-wise) (mydata is a 2d array of string datatype):

myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1);

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for i in range(*NUMBER OF FEATURES*):
    myData[:,i] = le.fit_transform(myData[:,i])

Retrieving a random item from ArrayList

See https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57

public static void main(String[] args) {
    RandomList<String> set = new RandomList<>();

    set.add("a", 10);
    set.add("b", 10);
    set.add("c", 30);
    set.add("d", 300);

    set.forEach((t) -> {
        System.out.println(t.getChance());
    });

    HashMap<String, Integer> count = new HashMap<>();
    IntStream.range(0, 100).forEach((value) -> {
        String str = set.raffle();
        count.put(str, count.getOrDefault(str, 0) + 1);
    });

    count.entrySet().stream().forEach(entry -> {
        System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));
    });
}

Output:

2.857142857142857

2.857142857142857

8.571428571428571

85.71428571428571

a: 2

b: 1

c: 9

d: 88

Where should I put the log4j.properties file?

I found that Glassfish by default is looking at [Glassfish install location]\glassfish\domains[your domain]\ as the default working directory... you can drop the log4j.properties file in this location and initialize it in your code using PropertyConfigurator as previously mentioned...

Properties props = System.getProperties();
System.out.println("Current working directory is " + props.getProperty("user.dir"));
PropertyConfigurator.configure("log4j.properties");

How does Spring autowire by name when more than one matching bean is found?

You can use the @Qualifier annotation

From here

Fine-tuning annotation-based autowiring with qualifiers

Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:

class Main {
    private Country country;
    @Autowired
    @Qualifier("country")
    public void setCountry(Country country) {
        this.country = country;
    }
}

This will use the UK add an id to USA bean and use that if you want the USA.

How to return a html page from a restful controller in spring boot?

I did three things:

  • Put the HTML page in {project.basedir}/resources/static/myPage.html;
  • Switch @RestController to @Controller;
  • This is my controller:
@RequestMapping(method = RequestMethod.GET, value = "/")
public String aName() {
    return "myPage.html";
}

No particular dependency is needed.

How to re-sign the ipa file?

Try this app http://www.ketzler.de/2011/01/resign-an-iphone-app-insert-new-bundle-id-and-send-to-xcode-organizer-for-upload/

It supposed to help you resign the IPA file. I tried it myself but couldn't get pass an error with Entitlements.plist. Could just be a problem with my project. You should give it a try.

Space between two divs

If you don't require support for IE6:

h1 {margin-bottom:20px;}
div + div {margin-top:10px;}

The second line adds spacing between divs, but will not add any before the first div or after the last one.

Typescript ReferenceError: exports is not defined

I had the same issue, but my setup required a different solution.

I'm using the create-react-app-rewired package with a config-overrides.js file. Previously, I was using the addBabelPresets import (in the override() method) from customize-cra and decided to abstract those presets to a separate file. Coincidentally, this solved my problem.

I added useBabelRc() to the override() method in config-overrides.js and created a babel.config.js file with the following:

module.exports = {
    presets: [
        '@babel/preset-react',
        '@babel/preset-env'
    ],
}

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Your error states that cross-env is not installed.

'cross-env' is not recognized as an internal or external command, operable program or batch file.

You just need to run

npm install cross-env

How to get local server host and port in Spring Boot?

You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar

environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");

spring.factories of spring-cloud-commons-2.1.0.RC2.jar

org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor

Does Index of Array Exist

The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.

public ItemContext GetThisElement(int row,
    int col)
{
    ItemContext ctx = null;
    if (rgItemCtx[row, col] != null)
    {
        try
        {
          ctx = rgItemCtx[row, col];
        }
        catch (SystemException sex)
        {
          ctx = null;
          // perhaps do something with sex properties
        }
    }

    return (ctx);
}

Mysql adding user for remote access

Follow instructions (steps 1 to 3 don't needed in windows):

  1. Find mysql config to edit:

    /etc/mysql/my.cnf (Mysql 5.5)

    /etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)

  2. Find bind-address=127.0.0.1 in config file change bind-address=0.0.0.0 (you can set bind address to one of your interface ips or like me use 0.0.0.0)

  3. Restart mysql service run on console: service restart mysql

  4. Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql and if you set password for root run mysql -p):

    GRANT ALL PRIVILEGES 
     ON *.* TO 'remote'@'%' 
     IDENTIFIED BY 'safe_password' 
     WITH GRANT OPTION;`
    

Now you should have a user with name of user and password of safe_password with capability of remote connect.

Python Pandas Error tokenizing data

You can do this step to avoid the problem -

train = pd.read_csv('/home/Project/output.csv' , header=None)

just add - header=None

Hope this helps!!

How to run a makefile in Windows?

Check out GnuWin's make (for windows), which provides a native port for Windows (without requiring a full runtime environment like Cygwin)

If you have winget, you can install via the CLI like this:

winget install GnuWin32.Make

Also, be sure to add the install path to your system PATH:

C:\Program Files (x86)\GnuWin32\bin

Python strptime() and timezones?

Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:

>>> from email.utils import parsedate_tz
>>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
(2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)

See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.

In this format, EST is semantically equivalent to -0500. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.

How to POST JSON request using Apache HttpClient?

As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a StringEntity.

To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));

How to convert a column of DataTable to a List

I make a sample for you , and I hope this is helpful...

    static void Main(string[] args)
    {
        var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };

        DataTable table = new DataTable();
        foreach (var col in cols)
            table.Columns.Add(col);

        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });

        foreach (var col in cols)
        {
            var results = from p in table.AsEnumerable()
                          select p[col];

            Console.WriteLine("*************************");
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }
        }


        Console.ReadLine();
    }

How to transform array to comma separated words string?

You're looking for implode()

$string = implode(",", $array);

Add numpy array as column to Pandas data frame

Consider using a higher dimensional datastructure (a Panel), rather than storing an array in your column:

In [11]: p = pd.Panel({'df': df, 'csc': csc})

In [12]: p.df
Out[12]: 
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

In [13]: p.csc
Out[13]: 
   0  1  2
0  0  1  0
1  0  0  1
2  1  0  0

Look at cross-sections etc, etc, etc.

In [14]: p.xs(0)
Out[14]: 
   csc  df
0    0   1
1    1   2
2    0   3

See the docs for more on Panels.

How to move text up using CSS when nothing is working

used the following snippet and it worked fine..

.smallText .bmv-disclaimer {
   height: 40px;
}

Pass object to javascript function

The "braces" are making an object literal, i.e. they create an object. It is one argument.

Example:

function someFunc(arg) {
    alert(arg.foo);
    alert(arg.bar);
}

someFunc({foo: "This", bar: "works!"});

the object can be created beforehand as well:

var someObject = {
    foo: "This", 
    bar: "works!"
};

someFunc(someObject);

I recommend to read the MDN JavaScript Guide - Working with Objects.

"NOT IN" clause in LINQ to Entities

I took a list and used,

!MyList.Contains(table.columb.tostring())

Note: Make sure to use List and not Ilist

Can we cast a generic object to a custom object type in javascript?

This borrows from a few other answers here but I thought it might help someone. If you define the following function on your custom object, then you have a factory function that you can pass a generic object into and it will return for you an instance of the class.

CustomObject.create = function (obj) {
    var field = new CustomObject();
    for (var prop in obj) {
        if (field.hasOwnProperty(prop)) {
            field[prop] = obj[prop];
        }
    }

    return field;
}

Use like this

var typedObj = CustomObject.create(genericObj);

How to change href of <a> tag on button click through javascript

I know its bit old post. Still, it might help some one.

Instead of tag,if possible you can this as well.

 <script type="text/javascript">
        function IsItWorking() {
          // Do your stuff here ...
            alert("YES, It Works...!!!");
        }
    </script>   

    `<asp:HyperLinkID="Link1"NavigateUrl="javascript:IsItWorking();"`            `runat="server">IsItWorking?</asp:HyperLink>`

Any comments on this?

How do I refresh a DIV content?

You can use jQuery to achieve this using simple $.get method. .html work like innerHtml and replace the content of your div.

$.get("/YourUrl", {},
      function (returnedHtml) {
      $("#here").html(returnedHtml);
});

And call this using javascript setInterval method.

How to delete multiple rows in SQL where id = (x to y)

You can use BETWEEN:

DELETE FROM table
where id between 163 and 265

How to display Woocommerce Category image?

This solution with few code. I think is better.

<?php echo wp_get_attachment_image( get_term_meta( get_queried_object_id(), 'thumbnail_id', 1 ), 'thumbnail' ); ?>

Simulating a click in jQuery/JavaScript on a link

All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.

How do I execute a command and get the output of the command within C++ using POSIX?

Two possible approaches:

  1. I don't think popen() is part of the C++ standard (it's part of POSIX from memory), but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is ./some_command).

  2. On the off-chance that there is no popen(), you can use system("./some_command >/tmp/some_command.out");, then use the normal I/O functions to process the output file.

Getting distance between two points based on latitude/longitude

import numpy as np


def Haversine(lat1,lon1,lat2,lon2, **kwarg):
    """
    This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, 
    the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points 
    (ignoring any hills they fly over, of course!).
    Haversine
    formula:    a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
    c = 2 · atan2( va, v(1-a) )
    d = R · c
    where   f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
    note that angles need to be in radians to pass to trig functions!
    """
    R = 6371.0088
    lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])

    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
    c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
    d = R * c
    return round(d,4)

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

iOS Remote Debugging

Update:

This is not the best answer anymore, please follow gregers' advice.

New answer:

Use Weinre.

Old answer:

You can now use Safari for remote debugging. But it requires iOS 6.

Here is a quick translation of http://html5-mobile.de/blog/ios6-remote-debugging-web-inspector

  1. Connect your iDevice via USB with your Mac
  2. Open Safari on your Mac and activate the dev tools
  3. On your iDevice: go to settings > safari > advanced and activate the web inspector
  4. Go to any website with your iDevice
  5. On your Mac: Open the developer menu and chose the site from your iDevice (its at the top Safari Menu)

As pointed out by Simons answer one need to turn off private browsing to make remote debugging work.

Settings > Safari > Private Browsing > OFF

How to combine two byte arrays

String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
    byteData[start + i] = byteSalt[i];
}

The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array. So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32. What will correct it is replacing the following line:

for (int i = 0; i < byteData.length; i ++)

with:

for (int i = 0; i < byteSalt.length; i ++)

What is the '.well' equivalent class in Bootstrap 4

Looking for a one line option:

    <div class="jumbotron bg-dark"> got a team? </div>        

https://getbootstrap.com/docs/4.0/components/jumbotron/

Trigger validation of all fields in Angular Form submit

I like the this approach in handling validation on button click.

  1. There is no need to invoke anything from controller,

  2. it's all handled with a directive.

on github

Safari 3rd party cookie iframe trick no longer working?

You said you were willing to have your users click a button before the content loads. My solution was to have a button open a new browser window. That window sets a cookie for my domain, refreshes the opener and then closes.

So your main script could look like:

<?php if(count($_COOKIE) > 0): ?>
<!--Main Content Stuff-->
<?php else: ?>
<a href="/safari_cookie_fix.php" target="_blank">Click here to load content</a>
<?php endif ?>

Then safari_cookie_fix.php looks like:

<?php
setcookie("safari_test", "1");
?>
<html>
    <head>
        <title>Safari Fix</title>
        <script type="text/javascript" src="/libraries/prototype.min.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    document.observe('dom:loaded', function(){
        window.opener.location.reload();
        window.close();
    })
    </script>
    This window should close automatically
    </body>
</html>

PHP Create and Save a txt file to root directory

It's creating the file in the same directory as your script. Try this instead.

$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);

how to implement Pagination in reactJs

   Sample pagination react js working code 
    import React, { Component } from 'react';
    import {
    Pagination,
    PaginationItem,
    PaginationLink
    } from "reactstrap";


    let prev  = 0;
    let next  = 0;
    let last  = 0;
    let first = 0;
    export default class SamplePagination extends Component {
       constructor() {
         super();
         this.state = {
           todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','T','v','u','w','x','y','z'],
           currentPage: 1,
           todosPerPage: 3,

         };
         this.handleClick = this.handleClick.bind(this);
         this.handleLastClick = this.handleLastClick.bind(this);
         this.handleFirstClick = this.handleFirstClick.bind(this);
       }

       handleClick(event) {
         event.preventDefault();
         this.setState({
           currentPage: Number(event.target.id)
         });
       }

       handleLastClick(event) {
         event.preventDefault();
         this.setState({
           currentPage:last
         });
       }
       handleFirstClick(event) {
         event.preventDefault();
         this.setState({
           currentPage:1
         });
       }
       render() {
         let { todos, currentPage, todosPerPage } = this.state;

         // Logic for displaying current todos
         let indexOfLastTodo = currentPage * todosPerPage;
         let indexOfFirstTodo = indexOfLastTodo - todosPerPage;
         let currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
          prev  = currentPage > 0 ? (currentPage -1) :0;
          last = Math.ceil(todos.length/todosPerPage);
          next  = (last === currentPage) ?currentPage: currentPage +1;

         // Logic for displaying page numbers
         let pageNumbers = [];
         for (let i = 1; i <=last; i++) {
           pageNumbers.push(i);
         }

          return (
           <div>
             <ul>
              {
                currentTodos.map((todo,index) =>{
                  return <li key={index}>{todo}</li>;
                })
              }
             </ul><ul id="page-numbers">
             <nav>
              <Pagination>
              <PaginationItem>
              { prev === 0 ? <PaginationLink disabled>First</PaginationLink> :
                  <PaginationLink onClick={this.handleFirstClick} id={prev} href={prev}>First</PaginationLink>
              }
              </PaginationItem>
              <PaginationItem>
              { prev === 0 ? <PaginationLink disabled>Prev</PaginationLink> :
                  <PaginationLink onClick={this.handleClick} id={prev} href={prev}>Prev</PaginationLink>
              }
              </PaginationItem>
                 {
                  pageNumbers.map((number,i) =>
                  <Pagination key= {i}>
                  <PaginationItem active = {pageNumbers[currentPage-1] === (number) ? true : false} >
                   <PaginationLink onClick={this.handleClick} href={number} key={number} id={number}>
                   {number}
                   </PaginationLink>
                   </PaginationItem>
                  </Pagination>
                )}

             <PaginationItem>
             {
               currentPage === last ? <PaginationLink disabled>Next</PaginationLink> :
               <PaginationLink onClick={this.handleClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Next</PaginationLink>
             }
             </PaginationItem>

             <PaginationItem>
             {
               currentPage === last ? <PaginationLink disabled>Last</PaginationLink> :
               <PaginationLink onClick={this.handleLastClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Last</PaginationLink>
             }
             </PaginationItem>
             </Pagination>
              </nav>
             </ul>
           </div>
         );
       }
     }

     ReactDOM.render(
      <SamplePagination />,
      document.getElementById('root')
    );

How to install cron

Installing Crontab on Ubuntu

sudo apt-get update

We download the crontab file to the root

wget https://pypi.python.org/packages/47/c2/d048cbe358acd693b3ee4b330f79d836fb33b716bfaf888f764ee60aee65/crontab-0.20.tar.gz

Unzip the file crontab-0.20.tar.gz

tar xvfz crontab-0.20.tar.gz

Login to a folder crontab-0.20

cd crontab-0.20*

Installation order

python setup.py install

See also here:.. http://www.syriatalk.im/crontab.html

how to open a page in new tab on button click in asp.net?

You could use window.open. Like this:

protected void btnNewEntry_Click(object sender, EventArgs e)
{ 
   Page.ClientScript.RegisterStartupScript(
   this.GetType(),"OpenWindow","window.open('YourURL','_newtab');",true);
}

How to set scope property with ng-init?

Try this Code

var app = angular.module('myapp', []);
  app.controller('testController', function ($scope, $http) {
       $scope.init = function(){           
       alert($scope.testInput);
   };});

_x000D_
_x000D_
<body ng-app="myapp">_x000D_
      <div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >_x000D_
      </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Get element of JS object with an index

If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.

For example, using an array, you could do this:

var myobj = [{"A":["B"]}, {"B": ["C"]}];
var firstItem = myobj[0];

Then, you can use myobj[0] to get the first object in the array.

Or, depending upon what you're trying to do:

var myobj = [{key: "A", val:["B"]}, {key: "B",  val:["C"]}];
var firstKey = myobj[0].key;   // "A"
var firstValue = myobj[0].val; // "["B"]

Echo tab characters in bash script

res="\t\tx"
echo -e "[${res}]"

Build .NET Core console application to output an EXE

If a .bat file is acceptable, you can create a bat file with the same name as the DLL file (and place it in the same folder), then paste in the following content:

dotnet %~n0.dll %*

Obviously, this assumes that the machine has .NET Core installed and globally available.

c:\> "path\to\batch\file" -args blah

(This answer is derived from Chet's comment.)

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

How to kill all processes matching a name?

pkill -x matches the process name exactly.

pkill -x amarok

pkill -f is similar but allows a regular expression pattern.

Note that pkill with no other parameters (e.g. -x, -f) will allow partial matches on process names. So "pkill amarok" would kill amarok, amarokBanana, bananaamarok, etc.

I wish -x was the default behavior!

Can I change the fill color of an svg path with CSS?

if you want to change color by hovering in the element, try this:

path:hover{
  fill:red;
}

How to print last two columns using awk

Please try this out to take into account all possible scenarios:

awk '{print $(NF-1)"\t"$NF}'  file

or

awk 'BEGIN{OFS="\t"}' file

or

awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file

How to connect Bitbucket to Jenkins properly

I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.

Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

How to manipulate arrays. Find the average. Beginner Java

Using an enhanced for would be even nicer:

int sum = 0;
for (int d : data) sum += d;

Another thing that will probably give you a big surprise is the wrong result that you will obtain from

double average = sum / data.length;

Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length and only then promote that integer to a double. A solution would be

double average = 1.0d * sum / data.length;

This will force the dividend into a double, which will automatically propagate to the divisor.

iOS: UIButton resize according to text length

To accomplish this using autolayout, try setting a variable width constraint:

Width Constraint

You may also need to adjust your Content Hugging Priority and Content Compression Resistance Priority to get the results you need.


UILabel is completely automatically self-sizing:

This UILabel is simply set to be centered on the screen (two constraints only, horizontal/vertical):

It changes widths totally automatically:

You do not need to set any width or height - it's totally automatic.

enter image description here

enter image description here

Notice the small yellow squares are simply attached ("spacing" of zero). They automatically move as the UILabel resizes.

Adding a ">=" constraint sets a minimum width for the UILabel:

enter image description here

Excel VBA select range at last row and column

Is this what you are trying? I have commented the code so that you will not have any problem understanding it.

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim rng As Range

    '~~> Set this to the relevant worksheet
    Set ws = [Sheet1]

    With ws
        '~~> Get the last row and last column
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Set the range
        Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))

        With rng
            Debug.Print .Address
            '
            '~~> What ever you want to do with the address
            '
        End With
    End With
End Sub

BTW I am assuming that LastRow is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find to find the Last Row and the Last Column. You might want to see THIS

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

How to get a value from the last inserted row?

Here is how I solved it, based on the answers here:

Connection conn = ConnectToDB(); //ConnectToDB establishes a connection to the database.
String sql = "INSERT INTO \"TableName\"" +
        "(\"Column1\", \"Column2\",\"Column3\",\"Column4\")" +
        "VALUES ('value1',value2, 'value3', 'value4') RETURNING 
         \"TableName\".\"TableId\"";
PreparedStatement prpState = conn.prepareStatement(sql);
ResultSet rs = prpState.executeQuery();
if(rs.next()){
      System.out.println(rs.getInt(1));
        }

How to pass data between fragments

I'm working on a similar project and I guess my code may help in the above situation

Here is the overview of what i'm doing

My project Has two fragments Called "FragmentA" and "FragmentB"

-FragmentA Contains one list View,when you click an item in FragmentA It's INDEX is passed to FragmentB using Communicator interface

  • The design pattern is totally based on the concept of java interfaces that says "interface reference variables can refer to a subclass object"
  • Let MainActivity implement the interface provided by fragmentA(otherwise we can't make interface reference variable to point to MainActivity)
  • In the below code communicator object is made to refer to MainActivity's object by using "setCommunicator(Communicatot c)" method present in fragmentA.
  • I'm triggering respond() method of interface from FrgamentA using the MainActivity's reference.

    Interface communcator is defined inside fragmentA, this is to provide least access previlage to communicator interface.

below is my complete working code

FragmentA.java

public class FragmentA extends Fragment implements OnItemClickListener {

ListView list;
Communicator communicater;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragmenta, container,false);
}

public void setCommunicator(Communicator c){
    communicater=c;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    communicater=(Communicator) getActivity();
    list = (ListView) getActivity().findViewById(R.id.lvModularListView);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.items, android.R.layout.simple_list_item_1);
    list.setAdapter(adapter);
    list.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);

}

public interface Communicator{
    public void respond(int index);
}

}

fragmentB.java

public class FragmentA extends Fragment implements OnItemClickListener {

ListView list;
Communicator communicater;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragmenta, container,false);
}

public void setCommunicator(Communicator c){
    communicater=c;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    communicater=(Communicator) getActivity();
    list = (ListView) getActivity().findViewById(R.id.lvModularListView);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.items, android.R.layout.simple_list_item_1);
    list.setAdapter(adapter);
    list.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);

}

public interface Communicator{
    public void respond(int index);
}

}

MainActivity.java

public class MainActivity extends Activity implements FragmentA.Communicator {
FragmentManager manager=getFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentA fragA=(FragmentA) manager.findFragmentById(R.id.fragmenta);
    fragA.setCommunicator(this);


}

@Override
public void respond(int i) {
    // TODO Auto-generated method stub

FragmentB FragB=(FragmentB) manager.findFragmentById(R.id.fragmentb);
FragB.changetext(i);
}



}

How to make Sonar ignore some classes for codeCoverage metric?

At the time of this writing (which is with SonarQube 4.5.1), the correct property to set is sonar.coverage.exclusions, e.g.:

<properties>
    <sonar.coverage.exclusions>foo/**/*,**/bar/*</sonar.coverage.exclusions>
</properties>

This seems to be a change from just a few versions earlier. Note that this excludes the given classes from coverage calculation only. All other metrics and issues are calculated.

In order to find the property name for your version of SonarQube, you can try going to the General Settings section of your SonarQube instance and look for the Code Coverage item (in SonarQube 4.5.x, that's General Settings → Exclusions → Code Coverage). Below the input field, it gives the property name mentioned above ("Key: sonar.coverage.exclusions").

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

How to add parameters into a WebRequest?

If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.

If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:

private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
                                        CookieContainer cookieContainer,
                                        string userAgent, string acceptHeaderString,
                                        string referer,
                                        string contentType, out string responseUri)
        {
            var result = "";
            if (!string.IsNullOrEmpty(requestUri))
            {
                var request = WebRequest.Create(requestUri) as HttpWebRequest;
                if (request != null)
                {
                    request.KeepAlive = true;
                    var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                    request.CachePolicy = cachePolicy;
                    request.Expect = null;
                    if (!string.IsNullOrEmpty(method))
                        request.Method = method;
                    if (!string.IsNullOrEmpty(acceptHeaderString))
                        request.Accept = acceptHeaderString;
                    if (!string.IsNullOrEmpty(referer))
                        request.Referer = referer;
                    if (!string.IsNullOrEmpty(contentType))
                        request.ContentType = contentType;
                    if (!string.IsNullOrEmpty(userAgent))
                        request.UserAgent = userAgent;
                    if (cookieContainer != null)
                        request.CookieContainer = cookieContainer;

                    request.Timeout = Constants.RequestTimeOut;

                    if (request.Method == "POST")
                    {
                        if (postData != null)
                        {
                            request.ContentLength = postData.Length;
                            using (var dataStream = request.GetRequestStream())
                            {
                                dataStream.Write(postData, 0, postData.Length);
                            }
                        }
                    }

                    using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpWebResponse != null)
                        {
                            responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
                            cookieContainer.Add(httpWebResponse.Cookies);
                            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                            {
                                result = streamReader.ReadToEnd();
                            }
                            return result;
                        }
                    }
                }
            }
            responseUri = null;
            return null;
        }

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

Easy way to test a URL for 404 in PHP?

addendum;tested those 3 methods considering performance.

The result, at least in my testing environment:

Curl wins

This test is done under the consideration that only the headers (noBody) is needed. Test yourself:

$url = "http://de.wikipedia.org/wiki/Pinocchio";

$start_time = microtime(TRUE);
$headers = get_headers($url);
echo $headers[0]."<br>";
$end_time = microtime(TRUE);
echo $end_time - $start_time."<br>";


$start_time = microtime(TRUE);
$response = file_get_contents($url);
echo $http_response_header[0]."<br>";
$end_time = microtime(TRUE);
echo $end_time - $start_time."<br>";

$start_time = microtime(TRUE);
$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_NOBODY, 1); // and *only* get the header 
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
// if($httpCode == 404) {
    // /* Handle 404 here. */
// }
echo $httpCode."<br>";
curl_close($handle);
$end_time = microtime(TRUE);
echo $end_time - $start_time."<br>";

How to check the function's return value if true or false

You don't need to call ValidateForm() twice, as you are above. You can just do

if(!ValidateForm()){
..
} else ...

I think that will solve the issue as above it looks like your comparing true/false to the string equivalent 'false'.

Getting "cannot find Symbol" in Java project in Intellij

For me - I tried these steps(Invalidate Cache & Restart, Maven Reimport)) but they didn't work. So I deleted the .idea, .settings, and .project folder and tried - it worked.

Check list of words in another string

Easiest and Simplest method of solving this problem is using re

import re

search_list = ['one', 'two', 'there']
long_string = 'some one long two phrase three'
if re.compile('|'.join(search_list),re.IGNORECASE).search(long_string): #re.IGNORECASE is used to ignore case
    # Do Something if word is present
else:
    # Do Something else if word is not present

HTML tag inside JavaScript

If you write HTML into javascript anywhere, it will think the HTML is written in javascript. The best way to include HTML in JavaScript is to write the HTML code on the page. The browser can't display HTML tags, so the browser will recognize the HTML and write this code in HTML.

document.write("<p>Hello World!</p>");

Though if you would like to write HTML on a function, GetElementById is the best:

function functionName() {
   document.getElementById(" the id of the HTML element to be written in ").innerHTML = "whatever you want to say"
}

Hope this helps!

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Perform Button click event when user press Enter key in Textbox

You can do it with javascript/jquery:

<script>
    function runScript(e) {
        if (e.keyCode == 13) {
            $("#myButton").click(); //jquery
            document.getElementById("myButton").click(); //javascript
        }
    }
</script>

<asp:textbox id="txtUsername" runat="server" onkeypress="return runScript(event)" />

<asp:LinkButton id="myButton" text="Login" runat="server" />

Laravel blade check empty foreach

Check the documentation for the best result:

@forelse($status->replies as $reply)
    <p>{{ $reply->body }}</p>
@empty
    <p>No replies</p>
@endforelse

What is the MySQL JDBC driver connection string?

Here is a little code from my side :)

needed driver:

com.mysql.jdbc.Driver

download: here (Platform Independent)

connection string in one line:

jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false

example code:

public static void testDB(){
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false");
        if (connection != null) {
            Statement statement = connection.createStatement();
            if (statement != null) {
                ResultSet resultSet = statement.executeQuery("select * from test");
                if (resultSet != null) {
                    ResultSetMetaData meta = resultSet.getMetaData();
                    int length = meta.getColumnCount();
                    while(resultSet.next())
                    {
                        for(int i = 1; i <= length; i++){
                            System.out.println(meta.getColumnName(i) + ": " + resultSet.getString(meta.getColumnName(i)));
                        }
                    }
                    resultSet.close();
                }
                statement.close();
            }
            connection.close();
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}