Programs & Examples On #Ijg

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

Should I use Python 32bit or Python 64bit

In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:

  1. You generally use less memory.
  2. You have less problems using COM (since you are on Windows).
  3. If you have to load DLLs, they most probably are also 32-bit. Python 64-bit can't load 32-bit libraries without some heavy hacks running another Python, this time in 32-bit, and using IPC.
  4. If you have to load DLLs that you compile yourself, you'll have to compile them to 64-bit, which is usually harder to do (specially if using MinGW on Windows).
  5. If you ever use PyInstaller or py2exe, those tools will generate executables with the same bitness of your Python interpreter.

How to downgrade python from 3.7 to 3.6

Create a python virtual environment using conda, and then install the tensorflow:

$ conda create -n [environment-name] python=3.6
# it may ask for installing python-3.6 if you don't have it already. Type "y" to proceed...
$ activate [environment-name]
$ pip install tensorflow

From now on, you can activate the environment whenever you want to use tensorflow.

If you don't have the conda package manager, first download it from here: https://www.anaconda.com/distribution

How to change column width in DataGridView?

Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.

DataGridView1.Columns[0].Width=100;// The id column 
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining 
//space

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

Catch KeyError in Python

Try print(e.message) this should be able to print your exception.

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print(e.message)

how to release localhost from Error: listen EADDRINUSE

When you get an error Error: listen EADDRINUSE,

Try running the following shell commands:

netstat -a -o | grep 8080
taskkill /F /PID 6204

I greped for 8080, because I know my server is running on port 8080. (static tells me when I start it: 'serving "." at http://127.0.0.1:8080'.) You might have to search for a different port.

Python Finding Prime Factors

Isn't largest prime factor of 27 is 3 ?? The above code might be fastest,but it fails on 27 right ? 27 = 3*3*3 The above code returns 1 As far as I know.....1 is neither prime nor composite

I think, this is the better code

def prime_factors(n):
    factors=[]
    d=2
    while(d*d<=n):
        while(n>1):            
            while n%d==0:
                factors.append(d)
                n=n/d
            d+=1
    return factors[-1]

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

How do I use InputFilter to limit characters in an EditText in Android?

In addition to the accepted answer, it is also possible to use e.g.: android:inputType="textCapCharacters" as an attribute of <EditText> in order to only accept upper case characters (and numbers).

How do I get a YouTube video thumbnail from the YouTube API?

    function get_video_thumbnail( $src ) {
            $url_pieces = explode('/', $src);
            if( $url_pieces[2] == 'dai.ly'){
                $id = $url_pieces[3];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if($url_pieces[2] == 'www.dailymotion.com'){
                $id = $url_pieces[4];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if ( $url_pieces[2] == 'vimeo.com' ) { // If Vimeo
                $id = $url_pieces[3];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'youtu.be' ) { // If Youtube
                $extract_id = explode('?', $url_pieces[3]);
                $id = $extract_id[0];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            }else if ( $url_pieces[2] == 'player.vimeo.com' ) { // If Vimeo
                $id = $url_pieces[4];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'www.youtube.com' ) { // If Youtube
                $extract_id = explode('=', $url_pieces[3]);
                $id = $extract_id[1];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            } else{
                $thumbnail = tim_thumb_default_image('video-icon.png', null, 147, 252);
            }
            return $thumbnail;
        }

get_video_thumbnail('https://vimeo.com/154618727');
get_video_thumbnail('https://www.youtube.com/watch?v=SwU0I7_5Cmc');
get_video_thumbnail('https://youtu.be/pbzIfnekjtM');
get_video_thumbnail('http://www.dailymotion.com/video/x5thjyz');

Http Post With Body

You can use HttpClient and HttpPost to send a json string as body:

public void post(String completeUrl, String body) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(completeUrl);
    httpPost.setHeader("Content-type", "application/json");
    try {
        StringEntity stringEntity = new StringEntity(body);
        httpPost.getRequestLine();
        httpPost.setEntity(stringEntity);

        httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Json body example:

{
  "param1": "value 1",
  "param2": 123,
  "testStudentArray": [
    {
      "name": "Test Name 1",
      "gpa": 3.5
    },
    {
      "name": "Test Name 2",
      "gpa": 3.8
    }
  ]
}

Button Width Match Parent

Using a ListTile also works as well, since a list fills the entire width:

ListTile(
  title: new RaisedButton(...),
),

How can I style a PHP echo text?

You can style it by the following way:

echo "<p style='color:red;'>" . $ip['cityName'] . "</p>";
echo "<p style='color:red;'>" . $ip['countryName'] . "</p>";

Determining 32 vs 64 bit in C++

Your approach was not too far off, but you are only checking whether long and int are of the same size. Theoretically, they could both be 64 bits, in which case your check would fail, assuming both to be 32 bits. Here is a check that actually checks the size of the types themselves, not their relative size:

#if ((UINT_MAX) == 0xffffffffu)
    #define INT_IS32BIT
#else
    #define INT_IS64BIT
#endif
#if ((ULONG_MAX) == 0xfffffffful)
    #define LONG_IS32BIT
#else
    #define LONG_IS64BIT
#endif

In principle, you can do this for any type for which you have a system defined macro with the maximal value.

Note, that the standard requires long long to be at least 64 bits even on 32 bit systems.

Difference between \b and \B in regex

\B is not \b e.g. negative \b

pass-key here is no word boundary beside - so it matches \B in your first example there are word boundary beside cat so it matches \b

similar rules apply for others too. \W is negative of \w \UPPER CASE is negative of \LOWER CASE

.rar, .zip files MIME Type

You should not trust $_FILES['upfile']['mime'], check MIME type by yourself. For that purpose, you may use fileinfo extension, enabled by default as of PHP 5.3.0.

  $fileInfo = new finfo(FILEINFO_MIME_TYPE);
  $fileMime = $fileInfo->file($_FILES['upfile']['tmp_name']);
  $validMimes = array( 
    'zip' => 'application/zip',
    'rar' => 'application/x-rar',
  );

  $fileExt = array_search($fileMime, $validMimes, true);
  if($fileExt != 'zip' && $fileExt != 'rar')
    throw new RuntimeException('Invalid file format.');

NOTE: Don't forget to enable the extension in your php.ini and restart your server:

extension=php_fileinfo.dll

Invalidating JSON Web Tokens

If you want to be able to revoke user tokens, you can keep track of all issued tokens on your DB and check if they're valid (exist) on a session-like table. The downside is that you'll hit the DB on every request.

I haven't tried it, but i suggest the following method to allow token revocation while keeping DB hits to a minimum -

To lower the database checks rate, divide all issued JWT tokens into X groups according to some deterministic association (e.g., 10 groups by first digit of the user id).

Each JWT token will hold the group id and a timestamp created upon token creation. e.g., { "group_id": 1, "timestamp": 1551861473716 }

The server will hold all group ids in memory and each group will have a timestamp that indicates when was the last log-out event of a user belonging to that group. e.g., { "group1": 1551861473714, "group2": 1551861487293, ... }

Requests with a JWT token that have an older group timestamp, will be checked for validity (DB hit) and if valid, a new JWT token with a fresh timestamp will be issued for client's future use. If the token's group timestamp is newer, we trust the JWT (No DB hit).

So -

  1. We only validate a JWT token using the DB if the token has an old group timestamp, while future requests won't get validated until someone in the user's group will log-out.
  2. We use groups to limit the number of timestamp changes (say there's a user logging in and out like there's no tomorrow - will only affect limited number of users instead of everyone)
  3. We limit the number of groups to limit the amount of timestamps held in memory
  4. Invalidating a token is a breeze - just remove it from the session table and generate a new timestamp for the user's group.

Setting a max height on a table

Use divs with max height and min height around the content that needs to scroll.

<tr>
    <td>
        <div>content</div>
    </td>
</tr>

td div{
    max-height:20px;
}

https://jsfiddle.net/ethanabrace/4w0ksczr/

Resize font-size according to div size

Here's a SCSS version of @Patrick's mixin.

$mqIterations: 19;
@mixin fontResize($iterations)
{
  $i: 1;
  @while $i <= $iterations
  {
    @media all and (min-width: 100px * $i) {
      body { font-size:0.2em * $i; }
    }
    $i: $i + 1;
  }
}
@include fontResize($mqIterations);

Remove insignificant trailing zeros from a number?

After reading all of the answers - and comments - I ended up with this:

function isFloat(n) {
    let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n)) : n;
    return number;
}

I know using eval can be harmful somehow but this helped me a lot.

So:

isFloat(1.234000);     // = 1.234;
isFloat(1.234001);     // = 1.234001
isFloat(1.2340010000); // = 1.234001

If you want to limit the decimal places, use toFixed() as others pointed out.

let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n).toFixed(3)) : n;

That's it.

Check if a variable is of function type

For those who's interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.

Next code contains only pure and pointfree functions:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);

As of ES2017, async functions are available, so we can check against them as well:

const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

And then combine them together:

const isFunction = R.either(isSyncFunction, isAsyncFunction);

Of course, function should be protected against null and undefined values, so to make it "safe":

const safeIsFunction = R.unless(R.isNil, isFunction);

And, complete snippet to sum up:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

const isFunction = R.either(isSyncFunction, isAsyncFunction);

const safeIsFunction = R.unless(R.isNil, isFunction);

// ---

console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));

However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.

Using json_encode on objects in PHP (regardless of scope)

$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;

Inline onclick JavaScript variable

There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider

JS

var myvar=15;
function init(){
    document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;

HTML

<input id="EditBanner" type="button"  value="Edit Image" />

System.Security.SecurityException when writing to Event Log

I had a console application where I also had done a "Publish" to create an Install disk.
I was getting the same error at the OP: Error Message

The solution was right click setup.exe and click Run as Administrator

This enabled the install process the necessary privilege's.

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

Mailto: Body formatting

From the first result on Google:

mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second

Filter output in logcat by tagname

Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:

$ adb shell logcat | grep YouTag
# just like: 
$ ps -ef | grep your_proc 

Testing whether a value is odd or even

Otherway using strings because why not

function isEven(__num){
    return String(__num/2).indexOf('.') === -1;
}

Detect end of ScrollView

You can make use of the Support Library's NestedScrollView and it's NestedScrollView.OnScrollChangeListener interface.

https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html

Alternatively if your app is targeting API 23 or above, you can make use of the following method on the ScrollView:

View.setOnScrollChangeListener(OnScrollChangeListener listener) 

Then follow the example that @Fustigador described in his answer. Note however that as @Will described, you should consider adding a small buffer in case the user or system isn't able to reach the complete bottom of the list for any reason.

Also worth noting is that the scroll change listener will sometimes be called with negative values or values greater than the view height. Presumably these values represent the 'momentum' of the scroll action. However unless handled appropriately (floor / abs) they can cause problems detecting the scroll direction when the view is scrolled to the top or bottom of the range.

https://developer.android.com/reference/android/view/View.html#setOnScrollChangeListener(android.view.View.OnScrollChangeListener)

Better way to set distance between flexbox items

Moving on from sawa's answer, here's a slightly improved version that allows you to set a fixed spacing between the items without the surrounding margin.

http://jsfiddle.net/chris00/s52wmgtq/49/

Also included is the Safari "-webkit-flex" version.

.outer1 {
    background-color: orange;
    padding: 10px;
}

.outer0 {
    background-color: green;
    overflow: hidden;
}

.container
{
    display: flex;
    display: -webkit-flex;
    flex-wrap: wrap;    
    -webkit-flex-wrap: wrap;
    background-color: rgba(0, 0, 255, 0.5);
    margin-left: -10px;
    margin-top: -10px;
}

.item
{
    flex-grow: 1;
    -webkit-flex-grow: 1;
    background-color: rgba(255, 0, 0, 0.5);
    width: 100px;
    padding: 10px;
    margin-left: 10px;
    margin-top: 10px;
    text-align: center;
    color: white;
}

<div class="outer1">
    <div class="outer0">
        <div class="container">
            <div class="item">text</div>
            <div class="item">text</div>
            <div class="item">text</div>
            <div class="item">text</div>
            <div class="item">text</div>
            <div class="item">text</div>
        </div>
    </div>
</div>

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

  1. Find file:

    [XAMPP Installation Directory]\php\php.ini
    
  2. open php.ini.
  3. Find max_execution_time and increase the value of it as you required
  4. Restart XAMPP control panel

Cut Java String at a number of character

You can use safe substring:

org.apache.commons.lang3.StringUtils.substring(str, 0, LENGTH);

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

Is there a built-in function to print all the current properties and values of an object?

from pprint import pprint

def print_r(the_object):
    print ("CLASS: ", the_object.__class__.__name__, " (BASE CLASS: ", the_object.__class__.__bases__,")")
    pprint(vars(the_object))

Split string, convert ToList<int>() in one line

On Unity3d, int.Parse doesn't work well. So I use like bellow.

List<int> intList = new List<int>( Array.ConvertAll(sNumbers.Split(','),
 new Converter<string, int>((s)=>{return Convert.ToInt32(s);}) ) );

Hope this help for Unity3d Users.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Get selected element's outer HTML

Here is a very optimized outerHTML plugin for jquery: (http://jsperf.com/outerhtml-vs-jquery-clone-hack/5 => the 2 others fast code snippets are not compatible with some browsers like FF < 11)

(function($) {

  var DIV = document.createElement("div"),
      outerHTML;

  if ('outerHTML' in DIV) {
    outerHTML = function(node) {
      return node.outerHTML;
    };
  } else {
    outerHTML = function(node) {
      var div = DIV.cloneNode();
      div.appendChild(node.cloneNode(true));
      return div.innerHTML;
    };
  }

  $.fn.outerHTML = function() {
    return this.length ? outerHTML(this[0]) : void(0);
  };

})(jQuery);

@Andy E => I don't agree with you. outerHMTL doesn't need a getter AND a setter: jQuery already give us 'replaceWith'...

@mindplay => Why are you joining all outerHTML? jquery.html return only the HTML content of the FIRST element.

(Sorry, don't have enough reputation to write comments)

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

postgresql - add boolean column to table set default

If you want an actual boolean column:

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

How to get the body's content of an iframe in Javascript?

To get body content from javascript ,i have tried the following code:

var frameObj = document.getElementById('id_description_iframe');

var frameContent = frameObj.contentWindow.document.body.innerHTML;

where "id_description_iframe" is your iframe's id. This code is working fine for me.

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

What is a PDB file?

PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.

This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb files. So effectively pdb files are really a boon to developers while debugging a program.

Generally it is not recommended to exclude the generation of *.pdb files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.

If you still want to disable generation of *.pdb files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none from "Debug Info" drop-down box -> press OK as shown in the snapshot below.

None Debug Info setting for a C# Project

Note: This setting will have to be done separately for "Debug" and "Release" build configurations.

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

Owl Carousel, making custom navigation

Complete tutorial here

Demo link

enter image description here

JavaScript

$('.owl-carousel').owlCarousel({
    margin: 10,
    nav: true,
    navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
    responsive: {
        0: {
            items: 1
        },
        600: {
            items: 3
        },
        1000: {
            items: 5
        }
    }
});

CSS Style for navigation

.owl-carousel .nav-btn{
  height: 47px;
  position: absolute;
  width: 26px;
  cursor: pointer;
  top: 100px !important;
}

.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}

.owl-carousel .prev-slide{
  background: url(nav-icon.png) no-repeat scroll 0 0;
  left: -33px;
}
.owl-carousel .next-slide{
  background: url(nav-icon.png) no-repeat scroll -24px 0px;
  right: -33px;
}
.owl-carousel .prev-slide:hover{
 background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}   

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

how does array[100] = {0} set the entire array to 0?

Implementation is up to compiler developers.

If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.

JavaScript: undefined !== undefined?

From - JQuery_Core_Style_Guidelines

  • Global Variables:
    typeof variable === "undefined"

  • Local Variables:
    variable === undefined

  • Properties:
    object.prop === undefined

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Looks like you runs out of swap memory, try this

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

as mentioned by @BlackBurn027 on comments below, this solution was described in here

window.onload vs document.onload

Add Event Listener

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function(event) {
      // - Code to execute when all DOM content is loaded. 
      // - including fonts, images, etc.
  });
</script>


Update March 2017

1 Vanilla JavaScript

window.addEventListener('load', function() {
    console.log('All assets are loaded')
})


2 jQuery

$(window).on('load', function() {
    console.log('All assets are loaded')
})


Good Luck.

How is Pythons glob.glob ordered?

It is probably not sorted at all and uses the order at which entries appear in the filesystem, i.e. the one you get when using ls -U. (At least on my machine this produces the same order as listing glob matches).

Can't append <script> element

Just create an element by parsing it with jQuery.

<div id="someElement"></div>
<script>
    var code = "<script>alert(123);<\/script>";
    $("#someElement").append($(code));
</script>

Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz

Finding an item in a List<> using C#

var myItem = myList.Find(item => item.property == "something");

What does the term "canonical form" or "canonical representation" in Java mean?

I believe there are two related uses of canonical: forms and instances.

A canonical form means that values of a particular type of resource can be described or represented in multiple ways, and one of those ways is chosen as the favored canonical form. (That form is canonized, like books that made it into the bible, and the other forms are not.) A classic example of a canonical form is paths in a hierarchical file system, where a single file can be referenced in a number of ways:

myFile.txt                                   # in current working dir
../conf/myFile.txt                           # relative to the CWD
/apps/tomcat/conf/myFile.txt                 # absolute path using symbolic links
/u1/local/apps/tomcat-5.5.1/conf/myFile.txt  # absolute path with no symlinks

The classic definition of the canonical representation of that file would be the last path. With local or relative paths you cannot globally identify the resource without contextual information. With absolute paths you can identify the resource, but cannot tell if two paths refer to the same entity. With two or more paths converted to their canonical forms, you can do all the above, plus determine if two resources are the same or not, if that is important to your application (solve the aliasing problem).

Note that the canonical form of a resource is not a quality of that particular form itself; there can be multiple possible canonical forms for a given type like file paths (say, lexicographically first of all possible absolute paths). One form is just selected as the canonical form for a particular application reason, or maybe arbitrarily so that everyone speaks the same language.

Forcing objects into their canonical instances is the same basic idea, but instead of determining one "best" representation of a resource, it arbitrarily chooses one instance of a class of instances with the same "content" as the canonical reference, then converts all references to equivalent objects to use the one canonical instance.

This can be used as a technique for optimizing both time and space. If there are multiple instances of equivalent objects in an application, then by forcing them all to be resolved as the single canonical instance of a particular value, you can eliminate all but one of each value, saving space and possibly time since you can now compare those values with reference identity (==) as opposed to object equivalence (equals() method).

A classic example of optimizing performance with canonical instances is collapsing strings with the same content. Calling String.intern() on two strings with the same character sequence is guaranteed to return the same canonical String object for that text. If you pass all your strings through that canonicalizer, you know equivalent strings are actually identical object references, i.e., aliases

The enum types in Java 5.0+ force all instances of a particular enum value to use the same canonical instance within a VM, even if the value is serialized and deserialized. That is why you can use if (day == Days.SUNDAY) with impunity in java if Days is an enum type. Doing this for your own classes is certainly possible, but takes care. Read Effective Java by Josh Bloch for details and advice.

How do I format date and time on ssrs report?

The following is how I do it using Visual Studio 2017 for an RDL targetted for SSRS 2017:

Right-click on the field in the textbox on the design surface and choose Placeholder Properties. Choose the Number panel and click on Date in the Category listbox, then select the formatting you are looking for in the Type listbox.

Timeout a command in bash without unnecessary delay

Kinda hacky, but it works. Doesn't work if you have other foreground processes (please help me fix this!)

sleep TIMEOUT & SPID=${!}; (YOUR COMMAND HERE; kill ${SPID}) & CPID=${!}; fg 1; kill ${CPID}

Actually, I think you can reverse it, meeting your 'bonus' criteria:

(YOUR COMMAND HERE & SPID=${!}; (sleep TIMEOUT; kill ${SPID}) & CPID=${!}; fg 1; kill ${CPID}) < asdf > fdsa

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

python list in sql query as parameter

For example, if you want the sql query:

select name from studens where id in (1, 5, 8)

What about:

my_list = [1, 5, 8]
cur.execute("select name from studens where id in %s" % repr(my_list).replace('[','(').replace(']',')') )

Putting GridView data in a DataTable

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    DataTable _datatable = new DataTable();
    for (int i = 0; i < grdReport.Columns.Count; i++)
    {
        _datatable.Columns.Add(grdReport.Columns[i].ToString());
    }
    foreach (GridViewRow row in grdReport.Rows)
    {
        DataRow dr = _datatable.NewRow();
        for (int j = 0; j < grdReport.Columns.Count; j++)
        {
            if (!row.Cells[j].Text.Equals("&nbsp;"))
                dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
        }

        _datatable.Rows.Add(dr);
    }
    ExportDataTableToExcel(_datatable);
}

phpMyAdmin on MySQL 8.0

in my case, to fix it I preferred to create a new user to use with PhpMyAdmin because modifying the root user has caused native login problems with other applications such as MySQL WorkBench.

This is what I did:

  • Log in to MySQL console with root user: mysql -u root -p, enter your password.
  • Let’s create a new user within the MySQL shell:
CREATE USER 'newMySqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlNewUsernamePassword';
  • At this point the newMysqlUsername has no permissions to do anything with the databases. So is needed to provide the user with access to the information they will need.
GRANT ALL PRIVILEGES ON * . * TO ' newMySqlUsername'@'localhost';
  • Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.
FLUSH PRIVILEGES;
  • Log out by typing quit or \q, and your changes will now be in effect, we can log in into PhpMyAdmin with the new user and it will have access to the databases.

  • Also you can log back in with this command in terminal:

mysql -u newMySqlUsername -p

List columns with indexes in PostgreSQL

\d tablename shows the column names for me on version 8.3.8.

 "username_idx" UNIQUE, btree (username), tablespace "alldata1"

How may I sort a list alphabetically using jQuery?

Something like this:

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

Above code will sort your unordered list with id 'myUL'.

OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort

Check OS version in Swift?

Also if you want to check WatchOS.

Swift

let watchOSVersion = WKInterfaceDevice.currentDevice().systemVersion
print("WatchOS version: \(watchOSVersion)")

Objective-C

NSString *watchOSVersion = [[WKInterfaceDevice currentDevice] systemVersion];
NSLog(@"WatchOS version: %@", watchOSVersion);

Format the date using Ruby on Rails

Easiest is to use strftime (docs).

If it's for use on the view side, better to wrap it in a helper, though.

Error in plot.new() : figure margins too large, Scatter plot

If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and try plot() again.

Moreover Execute the command

graphics.off()

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

xpath find if node exists

Patrick is correct, both in the use of the xsl:if, and in the syntax for checking for the existence of a node. However, as Patrick's response implies, there is no xsl equivalent to if-then-else, so if you are looking for something more like an if-then-else, you're normally better off using xsl:choose and xsl:otherwise. So, Patrick's example syntax will work, but this is an alternative:

<xsl:choose>
 <xsl:when test="/html/body">body node exists</xsl:when>
 <xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>

Create a txt file using batch file in a specific folder

Changed the set to remove % as that will write to text file as Echo on or off

echo off
title Custom Text File
cls
set /p txt=What do you want it to say? ; 
echo %txt% > "D:\Testing\dblank.txt"
exit

How do I implement interfaces in python?

I invite you to explore what Python 3.8 has to offer for the subject matter in form of Structural subtyping (static duck typing) (PEP 544)

See the short description https://docs.python.org/3/library/typing.html#typing.Protocol

For the simple example here it goes like this:

from typing import Protocol

class MyShowProto(Protocol):
    def show(self):
        ...


class MyClass:
    def show(self):
        print('Hello World!')


class MyOtherClass:
    pass


def foo(o: MyShowProto):
    return o.show()

foo(MyClass())  # ok
foo(MyOtherClass())  # fails

foo(MyOtherClass()) will fail static type checks:

$ mypy proto-experiment.py 
proto-experiment.py:21: error: Argument 1 to "foo" has incompatible type "MyOtherClass"; expected "MyShowProto"
Found 1 error in 1 file (checked 1 source file)

In addition, you can specify the base class explicitly, for instance:

class MyOtherClass(MyShowProto):

but note that this makes methods of the base class actually available on the subclass, and thus the static checker will not report that a method definition is missing on the MyOtherClass. So in this case, in order to get a useful type-checking, all the methods that we want to be explicitly implemented should be decorated with @abstractmethod:

from typing import Protocol
from abc import abstractmethod

class MyShowProto(Protocol):
    @abstractmethod
    def show(self): raise NotImplementedError


class MyOtherClass(MyShowProto):
    pass


MyOtherClass()  # error in type checker

Visual c++ can't open include file 'iostream'

I had this exact same problem in VS 2015. It looks like as of VS 2010 and later you need to include #include "stdafx.h" in all your projects.

#include "stdafx.h"
#include <iostream>
using namespace std;

The above worked for me. The below did not:

#include <iostream>
using namespace std;

This also failed:

#include <iostream>
using namespace std;
#include "stdafx.h"

Pip - Fatal error in launcher: Unable to create process using '"'

One more very basic and simple solution. Run the related python version's installation file (setup file) and click repair mode. It hardly takes one-two minutes and everything works perfectly after that :)

How do you print in a Go test using the "testing" package?

For example,

package verbose

import (
    "fmt"
    "testing"
)

func TestPrintSomething(t *testing.T) {
    fmt.Println("Say hi")
    t.Log("Say bye")
}

go test -v
=== RUN TestPrintSomething
Say hi
--- PASS: TestPrintSomething (0.00 seconds)
    v_test.go:10: Say bye
PASS
ok      so/v    0.002s

Command go

Description of testing flags

-v
Verbose output: log all tests as they are run. Also print all
text from Log and Logf calls even if the test succeeds.

Package testing

func (*T) Log

func (c *T) Log(args ...interface{})

Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

JFrame in full screen Java

Add:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
frame.setUndecorated(true);
frame.setVisible(true);

TypeError: no implicit conversion of Symbol into Integer

This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item| you are assigning item to a two-element array [key, value], so item[:symbol] throws an error.

The system cannot find the file specified in java

When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.

I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

How to get default gateway in Mac OSX

You can try with:

route -n get default

It is not the same as GNU/Linux's route -n (or even ip route show) but is useful for checking the default route information. Also, you can check the route that packages will take to a particular host. E.g.

route -n get www.yahoo.com

The output would be similar to:

   route to: 98.137.149.56
destination: default
       mask: 128.0.0.0
    gateway: 5.5.0.1
  interface: tun0
      flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1500         0

IMHO netstat -nr is what you need. Even MacOSX's Network utility app(*) uses the output of netstat to show routing information. Network utility screenshot displaying routing table information

I hope this helps :)

(*) You can start Network utility with open /Applications/Utilities/Network\ Utility.app

Difference between single and double quotes in Bash

If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.

For example, this

#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'

will give this:

double quotes gives you sometext
single quotes gives you $MYVAR

How can I remove text within parentheses with a regex?

For those who want to use Python, here's a simple routine that removes parenthesized substrings, including those with nested parentheses. Okay, it's not a regex, but it'll do the job!

def remove_nested_parens(input_str):
    """Returns a copy of 'input_str' with any parenthesized text removed. Nested parentheses are handled."""
    result = ''
    paren_level = 0
    for ch in input_str:
        if ch == '(':
            paren_level += 1
        elif (ch == ')') and paren_level:
            paren_level -= 1
        elif not paren_level:
            result += ch
    return result

remove_nested_parens('example_(extra(qualifier)_text)_test(more_parens).ext')

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

What about using Excel Data Reader (previously hosted here) an open source project on codeplex? Its works really well for me to export data from excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

UPDATE

After some search around, I came across this article: Faster MS Excel Reading using Office Interop Assemblies. The article only uses Office Interop Assemblies to read data from a given Excel Sheet. The source code is of the project is there too. I guess this article can be a starting point on what you trying to achieve. See if that helps

UPDATE 2

The code below takes an excel workbook and reads all values found, for each excel worksheet inside the excel workbook.

private static void TestExcel()
    {
        ApplicationClass app = new ApplicationClass();
        Workbook book = null;
        Range range = null;

        try
        {
            app.Visible = false;
            app.ScreenUpdating = false;
            app.DisplayAlerts = false;

            string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

            book = app.Workbooks.Open(@"C:\data.xls", Missing.Value, Missing.Value, Missing.Value
                                              , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                             , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                            , Missing.Value, Missing.Value, Missing.Value);
            foreach (Worksheet sheet in book.Worksheets)
            {

                Console.WriteLine(@"Values for Sheet "+sheet.Index);

                // get a range to work with
                range = sheet.get_Range("A1", Missing.Value);
                // get the end of values to the right (will stop at the first empty cell)
                range = range.get_End(XlDirection.xlToRight);
                // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                range = range.get_End(XlDirection.xlDown);

                // get the address of the bottom, right cell
                string downAddress = range.get_Address(
                    false, false, XlReferenceStyle.xlA1,
                    Type.Missing, Type.Missing);

                // Get the range, then values from a1
                range = sheet.get_Range("A1", downAddress);
                object[,] values = (object[,]) range.Value2;

                // View the values
                Console.Write("\t");
                Console.WriteLine();
                for (int i = 1; i <= values.GetLength(0); i++)
                {
                    for (int j = 1; j <= values.GetLength(1); j++)
                    {
                        Console.Write("{0}\t", values[i, j]);
                    }
                    Console.WriteLine();
                }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            range = null;
            if (book != null)
                book.Close(false, Missing.Value, Missing.Value);
            book = null;
            if (app != null)
                app.Quit();
            app = null;
        }
    }

In the above code, values[i, j] is the value that you need to be added to the dataset. i denotes the row, whereas, j denotes the column.

SQL Greater than, Equal to AND Less Than

Supposing you use sql server:

WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
                    AND DATEADD(HOUR, 1, GetDate())

dd: How to calculate optimal blocksize?

  • for better performace use the biggest blocksize you RAM can accomodate (will send less I/O calls to the OS)
  • for better accurancy and data recovery set the blocksize to the native sector size of the input

As dd copies data with the conv=noerror,sync option, any errors it encounters will result in the remainder of the block being replaced with zero-bytes. Larger block sizes will copy more quickly, but each time an error is encountered the remainder of the block is ignored.

source

What is the difference between YAML and JSON?

Technically YAML offers a lot more than JSON (YAML v1.2 is a superset of JSON):

  • comments
  • anchors and inheritance - example of 3 identical items:

    item1: &anchor_name
      name: Test
      title: Test title
    item2: *anchor_name
    item3:
      <<: *anchor_name
      # You may add extra stuff.
    
  • ...

Most of the time people will not use those extra features and the main difference is that YAML uses indentation whilst JSON uses brackets. This makes YAML more concise and readable (for the trained eye).

Which one to choose?

  • YAML extra features and concise notation makes it a good choice for configuration files (non-user provided files).
  • JSON limited features, wide support, and faster parsing makes it a great choice for interoperability and user provided data.

How should I print types like off_t and size_t?

Looking at man 3 printf on Linux, OS X, and OpenBSD all show support for %z for size_t and %t for ptrdiff_t (for C99), but none of those mention off_t. Suggestions in the wild usually offer up the %u conversion for off_t, which is "correct enough" as far as I can tell (both unsigned int and off_t vary identically between 64-bit and 32-bit systems).

Python NoneType object is not callable (beginner)

You want to pass the function object hi to your loop() function, not the result of a call to hi() (which is None since hi() doesn't return anything).

So try this:

>>> loop(hi, 5)
hi
hi
hi
hi
hi

Perhaps this will help you understand better:

>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Here is a javascript class that detects IE10, IE11 and Edge.
Navigator object is injected for testing purposes.

var DeviceHelper = function (_navigator) {
    this.navigator = _navigator || navigator;
};
DeviceHelper.prototype.isIE = function() {
    if(!this.navigator.userAgent) {
        return false;
    }

    var IE10 = Boolean(this.navigator.userAgent.match(/(MSIE)/i)),
        IE11 = Boolean(this.navigator.userAgent.match(/(Trident)/i));
    return IE10 || IE11;
};

DeviceHelper.prototype.isEdge = function() {
    return !!this.navigator.userAgent && this.navigator.userAgent.indexOf("Edge") > -1;
};

DeviceHelper.prototype.isMicrosoftBrowser = function() {
    return this.isEdge() || this.isIE();
};

sql server #region

It is just a matter of using text indentation in the query editor.

Expanded View:

Expanded

Collapsed View:

Collapsed

How to split a string literal across multiple lines in C / Objective-C?

I am having this problem all the time, so I made a tiny tool to convert text to an escaped multi-line Objective-C string:

http://multilineobjc.herokuapp.com/

Hope this saves you some time.

How to set editable true/false EditText in Android programmatically?

Since setEditable(false) is deprecated, use textView.setKeyListener(null); to make editText non-clickable.

How much faster is C++ than C#?

One particular scenario where C++ still has the upper hand (and will, for years to come) occurs when polymorphic decisions can be predetermined at compile time.

Generally, encapsulation and deferred decision-making is a good thing because it makes the code more dynamic, easier to adapt to changing requirements and easier to use as a framework. This is why object oriented programming in C# is very productive and it can be generalized under the term “generalization”. Unfortunately, this particular kind of generalization comes at a cost at run-time.

Usually, this cost is non-substantial but there are applications where the overhead of virtual method calls and object creation can make a difference (especially since virtual methods prevent other optimizations such as method call inlining). This is where C++ has a huge advantage because you can use templates to achieve a different kind of generalization which has no impact on runtime but isn't necessarily any less polymorphic than OOP. In fact, all of the mechanisms that constitute OOP can be modelled using only template techniques and compile-time resolution.

In such cases (and admittedly, they're often restricted to special problem domains), C++ wins against C# and comparable languages.

How do I check whether a file exists without exceptions?

How do I check whether a file exists, using Python, without using a try statement?

Now available since Python 3.4, import and instantiate a Path object with the file name, and check the is_file method (note that this returns True for symlinks pointing to regular files as well):

>>> from pathlib import Path
>>> Path('/').is_file()
False
>>> Path('/initrd.img').is_file()
True
>>> Path('/doesnotexist').is_file()
False

If you're on Python 2, you can backport the pathlib module from pypi, pathlib2, or otherwise check isfile from the os.path module:

>>> import os
>>> os.path.isfile('/')
False
>>> os.path.isfile('/initrd.img')
True
>>> os.path.isfile('/doesnotexist')
False

Now the above is probably the best pragmatic direct answer here, but there's the possibility of a race condition (depending on what you're trying to accomplish), and the fact that the underlying implementation uses a try, but Python uses try everywhere in its implementation.

Because Python uses try everywhere, there's really no reason to avoid an implementation that uses it.

But the rest of this answer attempts to consider these caveats.

Longer, much more pedantic answer

Available since Python 3.4, use the new Path object in pathlib. Note that .exists is not quite right, because directories are not files (except in the unix sense that everything is a file).

>>> from pathlib import Path
>>> root = Path('/')
>>> root.exists()
True

So we need to use is_file:

>>> root.is_file()
False

Here's the help on is_file:

is_file(self)
    Whether this path is a regular file (also True for symlinks pointing
    to regular files).

So let's get a file that we know is a file:

>>> import tempfile
>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(file.name)
>>> filepathobj.is_file()
True
>>> filepathobj.exists()
True

By default, NamedTemporaryFile deletes the file when closed (and will automatically close when no more references exist to it).

>>> del file
>>> filepathobj.exists()
False
>>> filepathobj.is_file()
False

If you dig into the implementation, though, you'll see that is_file uses try:

def is_file(self):
    """
    Whether this path is a regular file (also True for symlinks pointing
    to regular files).
    """
    try:
        return S_ISREG(self.stat().st_mode)
    except OSError as e:
        if e.errno not in (ENOENT, ENOTDIR):
            raise
        # Path doesn't exist or is a broken symlink
        # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
        return False

Race Conditions: Why we like try

We like try because it avoids race conditions. With try, you simply attempt to read your file, expecting it to be there, and if not, you catch the exception and perform whatever fallback behavior makes sense.

If you want to check that a file exists before you attempt to read it, and you might be deleting it and then you might be using multiple threads or processes, or another program knows about that file and could delete it - you risk the chance of a race condition if you check it exists, because you are then racing to open it before its condition (its existence) changes.

Race conditions are very hard to debug because there's a very small window in which they can cause your program to fail.

But if this is your motivation, you can get the value of a try statement by using the suppress context manager.

Avoiding race conditions without a try statement: suppress

Python 3.4 gives us the suppress context manager (previously the ignore context manager), which does semantically exactly the same thing in fewer lines, while also (at least superficially) meeting the original ask to avoid a try statement:

from contextlib import suppress
from pathlib import Path

Usage:

>>> with suppress(OSError), Path('doesnotexist').open() as f:
...     for line in f:
...         print(line)
... 
>>>
>>> with suppress(OSError):
...     Path('doesnotexist').unlink()
... 
>>> 

For earlier Pythons, you could roll your own suppress, but without a try will be more verbose than with. I do believe this actually is the only answer that doesn't use try at any level in the Python that can be applied to prior to Python 3.4 because it uses a context manager instead:

class suppress(object):
    def __init__(self, *exceptions):
        self.exceptions = exceptions
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            return issubclass(exc_type, self.exceptions)

Perhaps easier with a try:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

Other options that don't meet the ask for "without try":

isfile

import os
os.path.isfile(path)

from the docs:

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

But if you examine the source of this function, you'll see it actually does use a try statement:

# This follows symbolic links, so both islink() and isdir() can be true
# for the same path on systems that support symlinks
def isfile(path):
    """Test whether a path is a regular file"""
    try:
        st = os.stat(path)
    except os.error:
        return False
    return stat.S_ISREG(st.st_mode)
>>> OSError is os.error
True

All it's doing is using the given path to see if it can get stats on it, catching OSError and then checking if it's a file if it didn't raise the exception.

If you intend to do something with the file, I would suggest directly attempting it with a try-except to avoid a race condition:

try:
    with open(path) as f:
        f.read()
except OSError:
    pass

os.access

Available for Unix and Windows is os.access, but to use you must pass flags, and it does not differentiate between files and directories. This is more used to test if the real invoking user has access in an elevated privilege environment:

import os
os.access(path, os.F_OK)

It also suffers from the same race condition problems as isfile. From the docs:

Note: Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"

is better written as:

try:
    fp = open("myfile")
except IOError as e:
    if e.errno == errno.EACCES:
        return "some default data"
    # Not a permission error.
    raise
else:
    with fp:
        return fp.read()

Avoid using os.access. It is a low level function that has more opportunities for user error than the higher level objects and functions discussed above.

Criticism of another answer:

Another answer says this about os.access:

Personally, I prefer this one because under the hood, it calls native APIs (via "${PYTHON_SRC_DIR}/Modules/posixmodule.c"), but it also opens a gate for possible user errors, and it's not as Pythonic as other variants:

This answer says it prefers a non-Pythonic, error-prone method, with no justification. It seems to encourage users to use low-level APIs without understanding them.

It also creates a context manager which, by unconditionally returning True, allows all Exceptions (including KeyboardInterrupt and SystemExit!) to pass silently, which is a good way to hide bugs.

This seems to encourage users to adopt poor practices.

git checkout all the files

If you want to checkout all the files 'anywhere'

git checkout -- $(git rev-parse --show-toplevel)

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

PostgreSQL database service

I'm not on windows, but I think you can use the pgAdmin you just installed to configure a server connection and start the server.

Resize on div element

There is a really nice, easy to use, lightweight (uses native browser events for detection) plugin for both basic JavaScript and for jQuery that was released this year. It performs perfectly:

https://github.com/sdecima/javascript-detect-element-resize

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

I came here looking for an answer to my distorted images. Not totally sure about what the op is looking for above, but I found that adding in align-items: center would solve it for me. Reading the docs, it makes sense to override this if you are flexing images directly, since align-items: stretch is the default. Another solution is to wrap your images with a div first.

.myFlexedImage {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
}

Differences between strong and weak in Objective-C

It may be helpful to think about strong and weak references in terms of balloons.

A balloon will not fly away as long as at least one person is holding on to a string attached to it. The number of people holding strings is the retain count. When no one is holding on to a string, the ballon will fly away (dealloc). Many people can have strings to that same balloon. You can get/set properties and call methods on the referenced object with both strong and weak references.

A strong reference is like holding on to a string to that balloon. As long as you are holding on to a string attached to the balloon, it will not fly away.

A weak reference is like looking at the balloon. You can see it, access it's properties, call it's methods, but you have no string to that balloon. If everyone holding onto the string lets go, the balloon flies away, and you cannot access it anymore.

Count the number of occurrences of a character in a string in Javascript

_x000D_
_x000D_
var i = 0;_x000D_
_x000D_
var split_start = new Date().getTime();_x000D_
while (i < 30000) {_x000D_
  "1234,453,123,324".split(",").length -1;_x000D_
  i++;_x000D_
}_x000D_
var split_end = new Date().getTime();_x000D_
var split_time = split_end - split_start;_x000D_
_x000D_
_x000D_
i= 0;_x000D_
var reg_start = new Date().getTime();_x000D_
while (i < 30000) {_x000D_
  ("1234,453,123,324".match(/,/g) || []).length;_x000D_
  i++;_x000D_
}_x000D_
var reg_end = new Date().getTime();_x000D_
var reg_time = reg_end - reg_start;_x000D_
_x000D_
alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");
_x000D_
_x000D_
_x000D_

How to retrieve records for last 30 minutes in MS SQL?

Change this (CURRENT_TIMESTAMP-30)

To This: DateADD(mi, -30, Current_TimeStamp)

To get the current date use GetDate().

MSDN Link to DateAdd Function
MSDN Link to Get Date Function

java.lang.IllegalArgumentException: contains a path separator

I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!

 public class MyClass {    

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");  
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

it might save some time to somebody.

If you use GuzzleHttp and you face with this error message cURL error 60: SSL: no alternative certificate subject name matches target host name and you are fine with the 'insecure' solution (not recommended on production) then you have to add \GuzzleHttp\RequestOptions::VERIFY => false to the client configuration:

$this->client = new \GuzzleHttp\Client([
    'base_uri'                          => 'someAccessPoint',
    \GuzzleHttp\RequestOptions::HEADERS => [
        'User-Agent' => 'some-special-agent',
    ],
    'defaults'                          => [
        \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
        \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true,
    ],
    \GuzzleHttp\RequestOptions::VERIFY  => false,
]);

which sets CURLOPT_SSL_VERIFYHOST to 0 and CURLOPT_SSL_VERIFYPEER to false in the CurlFactory::applyHandlerOptions() method

$conf[CURLOPT_SSL_VERIFYHOST] = 0;
$conf[CURLOPT_SSL_VERIFYPEER] = false;

From the GuzzleHttp documentation

verify

Describes the SSL certificate verification behavior of a request.

  • Set to true to enable SSL certificate verification and use the default CA bundle > provided by operating system.
  • Set to false to disable certificate verification (this is insecure!).
  • Set to a string to provide the path to a CA bundle to enable verification using a custom certificate.

How do you use script variables in psql?

You need to use one of the procedural languages such as PL/pgSQL not the SQL proc language. In PL/pgSQL you can use vars right in SQL statements. For single quotes you can use the quote literal function.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

tf.initialize_all_variables() is deprecated. Instead initialize tensorflow variables with:

tf.global_variables_initializer()

A common example usage is:

with tf.Session() as sess:
     sess.run(tf.global_variables_initializer())

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace.

The permanent generation has been removed. The PermSize and MaxPermSize are ignored and a warning is issued if they are present on the command line.

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

python 2.7: cannot pip on windows "bash: pip: command not found"

  1. press [win] + Pause
  2. Advanced settings
  3. System variables
  4. Append ;C:\python27\Scripts to the end of Path variable
  5. Restart console

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Search and replace in bash using regular expressions

Use sed:

MYVAR=ho02123ware38384you443d34o3434ingtod38384day
echo "$MYVAR" | sed -e 's/[a-zA-Z]/X/g' -e 's/[0-9]/N/g'
# prints XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX

Note that the subsequent -e's are processed in order. Also, the g flag for the expression will match all occurrences in the input.

You can also pick your favorite tool using this method, i.e. perl, awk, e.g.:

echo "$MYVAR" | perl -pe 's/[a-zA-Z]/X/g and s/[0-9]/N/g'

This may allow you to do more creative matches... For example, in the snip above, the numeric replacement would not be used unless there was a match on the first expression (due to lazy and evaluation). And of course, you have the full language support of Perl to do your bidding...

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

I have the same questions, and got some information from this link: git fetch doesn't fetch all branches

So now, I may not sure how this situation happened, at least we can solve it:

Step 1. Check your "remote.origin.fetch" setting, should be like this

$ git config --get remote.origin.fetch

+refs/heads/private_dev_branch:refs/remotes/origin/private_dev_branch

Step 2. Change "remote.origin.fetch" to fetch everything

$ git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"

$ git config --get remote.origin.fetch

+refs/heads/*:refs/remotes/origin/*

Then, you can try "git pull" (maybe "git fetch origin" also works but I didn't try) to get all the branch.

git push >> fatal: no configured push destination

The command (or the URL in it) to add the github repository as a remote isn't quite correct. If I understand your repository name correctly, it should be;

git remote add demo_app '[email protected]:levelone/demo_app.git'

angularjs getting previous route path

Use the $locationChangeStart or $locationChangeSuccess events, 3rd parameter:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
   console.log('success', evt, absNewUrl, absOldUrl);
});

How to transform currentTimeMillis to a readable date format?

There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

My situation was a little different, I was trying to segue into a UINavigationController, and what fixed it for me was getting the main queue portion.

For Objective-C:

dispatch_async(dispatch_get_main_queue(), ^{
    [self performSegueWithIdentifier:@"SegueName" sender:self];
});

For Swift 3:

DispatchQueue.main.async { [weak self] in
    self?.performSegue(withIdentifier: "SegueName", sender: self)
}

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Your dialog should not be a "long-lived object that needs a context". The documentation is confusing. Basically if you do something like:

static Dialog sDialog;

(note the static)

Then in an activity somewhere you did

 sDialog = new Dialog(this);

You would likely be leaking the original activity during a rotation or similar that would destroy the activity. (Unless you clean up in onDestroy, but in that case you probably wouldn't make the Dialog object static)

For some data structures it would make sense to make them static and based off the application's context, but generally not for UI related things, like dialogs. So something like this:

Dialog mDialog;

...

mDialog = new Dialog(this);

Is fine and shouldn't leak the activity as mDialog would be freed with the activity since it's not static.

Sort a Map<Key, Value> by values

Some simple changes in order to have a sorted map with pairs that have duplicate values. In the compare method (class ValueComparator) when values are equal do not return 0 but return the result of comparing the 2 keys. Keys are distinct in a map so you succeed to keep duplicate values (which are sorted by keys by the way). So the above example could be modified like this:

    public int compare(Object a, Object b) {

        if((Double)base.get(a) < (Double)base.get(b)) {
          return 1;
        } else if((Double)base.get(a) == (Double)base.get(b)) {
          return ((String)a).compareTo((String)b);
        } else {
          return -1;
        }
      }
    }

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

Apparently with Laravel 5.2, the closure in DB::listen only receives a single parameter.

So, if you want to use DB::listen in Laravel 5.2, you should do something like:

DB::listen(
    function ($sql) {
        // $sql is an object with the properties:
        //  sql: The query
        //  bindings: the sql query variables
        //  time: The execution time for the query
        //  connectionName: The name of the connection

        // To save the executed queries to file:
        // Process the sql and the bindings:
        foreach ($sql->bindings as $i => $binding) {
            if ($binding instanceof \DateTime) {
                $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
            } else {
                if (is_string($binding)) {
                    $sql->bindings[$i] = "'$binding'";
                }
            }
        }

        // Insert bindings into query
        $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);

        $query = vsprintf($query, $sql->bindings);

        // Save the query to file
        $logFile = fopen(
            storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
            'a+'
        );
        fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL);
        fclose($logFile);
    }
);

HttpClient - A task was cancelled?

I ran into this issue because my Main() method wasn't waiting for the task to complete before returning, so the Task<HttpResponseMessage> myTask was being cancelled when my console program exited.

The solution was to call myTask.GetAwaiter().GetResult() in Main() (from this answer).

Command not found after npm install in zsh

I've solved this by brew upgrade node

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

Disable single warning error

as @rampion mentioned, if you are in clang gcc, the warnings are by name, not number, and you'll need to do:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
// ..your code..
#pragma clang diagnostic pop

this info comes from here

Make a dictionary in Python from input values

for i in range(n):
    data = input().split(' ')
    d[data[0]] = data[1]
for keys,values in d.items():
    print(keys)
    print(values)

Can I add jars to maven 2 build classpath without installing them?

This doesn't answer how to add them to your POM, and may be a no brainer, but would just adding the lib dir to your classpath work? I know that is what I do when I need an external jar that I don't want to add to my Maven repos.

Hope this helps.

Dynamically updating css in Angular 2

You can also use hostbinding:

import { HostBinding } from '@angular/core';

export class HomeComponent {
    @HostBinding('style.width') width: Number;
    @HostBinding('style.height') height: Number;
} 

Now when you change the width or height property from within the HomeComponent, this should affect the style attributes.

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.

Get query from java.sql.PreparedStatement

This is nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString(). I.e.

System.out.println(preparedStatement);

To my experience, the ones which do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers. For the case your JDBC driver doesn't support it, your best bet is using a statement wrapper which logs all setXxx() methods and finally populates a SQL string on toString() based on the logged information. For example Log4jdbc or P6Spy.

Fast query runs slow in SSRS

Add this to the end of your proc: option(recompile)

This will make the report run almost as fast as the stored procedure

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

TypeScript, Looping through a dictionary

If you just for in a object without if statement hasOwnProperty then you will get error from linter like:

for (const key in myobj) {
   console.log(key);
}
WARNING in component.ts
for (... in ...) statements must be filtered with an if statement

So the solutions is use Object.keys and of instead.

for (const key of Object.keys(myobj)) {
   console.log(key);
}

Hope this helper some one using a linter.

Failed to load resource: the server responded with a status of 404 (Not Found)

I have added app.UseStaticFiles(); this code in my startup.cs than it is fixed

How to read files from resources folder in Scala?

import scala.io.Source

object Demo {

  def main(args: Array[String]): Unit = {

    val ipfileStream = getClass.getResourceAsStream("/folder/a-words.txt")
    val readlines = Source.fromInputStream(ipfileStream).getLines
    readlines.foreach(readlines => println(readlines))

  }

}

Regex pattern inside SQL Replace function?

Instead of stripping out the found character by its sole position, using Replace(Column, BadFoundCharacter, '') could be substantially faster. Additionally, instead of just replacing the one bad character found next in each column, this replaces all those found.

WHILE 1 = 1 BEGIN
    UPDATE dbo.YourTable
    SET Column = Replace(Column, Substring(Column, PatIndex('%[^0-9.-]%', Column), 1), '')
    WHERE Column LIKE '%[^0-9.-]%'
    If @@RowCount = 0 BREAK;
END;

I am convinced this will work better than the accepted answer, if only because it does fewer operations. There are other ways that might also be faster, but I don't have time to explore those right now.

EXCEL VBA Check if entry is empty or not 'space'

You can use the following code to check if a textbox object is null/empty

'Checks if the box is null

If Me.TextBox & "" <> "" Then

        'Enter Code here...

End if

Unix's 'ls' sort by name

For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort

To sort them in reverse order:
ls -1 | sort -r

Inserting HTML into a div

I using "+" (plus) to insert div to html :

document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';

Hope this help.

How can I convert a DOM element to a jQuery element?

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Best way to get hostname with php

What about gethostname()?

Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.

Convert System.Drawing.Color to RGB and Hex Value

e.g.

 ColorTranslator.ToHtml(Color.FromArgb(Color.Tomato.ToArgb()))

This can avoid the KnownColor trick.

Can I use a min-height for table, tr or td?

if you set style="height:100px;" on a td if the td has content that grows the cell more than that, it will do so no need for min height on a td.

Getting the text that follows after the regex match

You can do this with "just the regular expression" as you asked for in a comment:

(?<=sentence).*

(?<=sentence) is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence without making that text itself part of the match. Consequently, (?<=sentence).* will match any text after sentence.

This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4}) is legal, but (?<=sentence\s*) isn't.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

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

I had this same issue. I was doing

arr = []
arr.append["HI"]

So using [ was causing error. It should be arr.append("HI")

Remove trailing newline from the elements of a string list

>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']

How to refer to relative paths of resources when working with a code repository

Try to use a filename relative to the current files path. Example for './my_file':

fn = os.path.join(os.path.dirname(__file__), 'my_file')

In Python 3.4+ you can also use pathlib:

fn = pathlib.Path(__file__).parent / 'my_file'

Multiplying across in a numpy array

You could also use matrix multiplication (aka dot product):

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)

numpy.dot(c,a)

Which is more elegant is probably a matter of taste.

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

Creating a directory in /sdcard fails

The correct path to the sdcard is

/mnt/sdcard/

but, as answered before, you shouldn't hardcode it. If you are on Android 2.1 or after, use

getExternalFilesDir(String type) 

Otherwise:

Environment.getExternalStorageDirectory()

Read carefully https://developer.android.com/guide/topics/data/data-storage.html#filesExternal

Also, you'll need to use this method or something similar

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

then check if you can access the sdcard. As said, read the official documentation.

Another option, maybe you need to use mkdirs instead of mkdir

file.mkdirs()

Creates the directory named by the trailing filename of this file, including the complete directory path required to create this directory.

To delay JavaScript function call using jQuery

Very easy, just call the function within a specific amount of milliseconds using setTimeout()

setTimeout(myFunction, 2000)

function myFunction() {
    alert('Was called after 2 seconds');
}

Or you can even initiate the function inside the timeout, like so:

setTimeout(function() {
    alert('Was called after 2 seconds');
}, 2000)

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

How to get the path of the batch script in Windows?

You can use following script to get the path without trailing "\"

for %%i in ("%~dp0.") do SET "mypath=%%~fi"

Gradle error: could not execute build using gradle distribution

I entered: [C:\Users\user\].gradle\caches\1.8\scripts directory and deleted its content. I didn't had to restart anything, just removed scripts content any rerun it.

How to achieve pagination/table layout with Angular.js?

The simplest way is using slice. You pipe the slice and mention the start index and end index for the part of the data you wish to display. Here is the code:
HTML

<table>
  <thead>
     ...
  </thead>
  <tbody>
     <tr *ngFor="let row of rowData | slice:startIndex:endIndex">
        ...
     </tr>
  </tbody>
</table>
<nav *ngIf="rowData" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item">
            <a class="page-link" (click)="updateIndex(0)" aria-label="Previous">
                <span aria-hidden="true">First</span>
            </a>
        </li>
        <li *ngFor="let i of getArrayFromNumber(rowData.length)" class="page-item">
            <a class="page-link" (click)="updateIndex(i)">{{i+1}}</a></li>

        <li class="page-item">
            <a class="page-link" (click)="updateIndex(pageNumberArray.length-1)" aria-label="Next">
                <span aria-hidden="true">Last</span>
            </a>
        </li>
    </ul>
</nav>


TypeScript

...
public rowData = data // data you want to display in table
public paginationRowCount = 100 //number of records in a page
...
getArrayFromNumber(length) {
        if (length % this.paginationRowCount === 0) {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount)).keys());
        } else {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount) + 1).keys());
        }
        return this.pageNumberArray;
    }

    updateIndex(pageIndex) {
        this.startIndex = pageIndex * this.paginationRowCount;
        if (this.rowData.length > this.startIndex + this.paginationRowCount) {
            this.endIndex = this.startIndex + this.paginationRowCount;
        } else {
            this.endIndex = this.rowData.length;
        }
    }

Refence for tutorial: https://www.youtube.com/watch?v=Q0jPfb9iyE0

Put icon inside input element in a form

The CSS solutions posted by others are the best way to accomplish this.

If that should give you any problems (read IE6), you can also use a borderless input inside of a div.

<div style="border: 1px solid #DDD;">
    <img src="icon.png"/>
    <input style="border: none;"/>
</div>

Not as "clean", but should work on older browsers.

What's the scope of a variable initialized in an if statement?

Scope in python follows this order:

  • Search the local scope

  • Search the scope of any enclosing functions

  • Search the global scope

  • Search the built-ins

(source)

Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

CSS getting text in one line rather than two

The best way to use is white-space: nowrap; This will align the text to one line.

Fix columns in horizontal scrolling

SOLVED

http://jsfiddle.net/DJqPf/7/

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}
td, th {
    padding: 5px 20px;
    width: 100px;
}
th:first-child {
    position: fixed;
    left: 5px
}

UPDATE

_x000D_
_x000D_
$(function () {  _x000D_
  $('.table-wrapper tr').each(function () {_x000D_
    var tr = $(this),_x000D_
        h = 0;_x000D_
    tr.children().each(function () {_x000D_
      var td = $(this),_x000D_
          tdh = td.height();_x000D_
      if (tdh > h) h = tdh;_x000D_
    });_x000D_
    tr.css({height: h + 'px'});_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
    overflow-x:scroll;_x000D_
    overflow-y:visible;_x000D_
    width:200px;_x000D_
    margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
    padding: 5px 20px;_x000D_
    width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
  _x000D_
}_x000D_
th:first-child {_x000D_
    position: absolute;_x000D_
    left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
    <h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
    <table id="consumption-data" class="data">_x000D_
        <thead class="header">_x000D_
            <tr>_x000D_
                <th>Month</th>_x000D_
                <th>Item 1</th>_x000D_
                <th>Item 2</th>_x000D_
                <th>Item 3</th>_x000D_
                <th>Item 4</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody class="results">_x000D_
            <tr>_x000D_
                <th>Jan is an awesome month</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Feb</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Mar</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Apr</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>  _x000D_
            </tr>_x000D_
            <tr>    _x000D_
                <th>May</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Jun</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
_x000D_
            <tr>_x000D_
                <th>...</th>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

git replacing LF with CRLF

In vim open the file (e.g.: :e YOURFILEENTER), then

:set noendofline binary
:wq

Giving graphs a subtitle in matplotlib

This is a pandas code example that implements Floris van Vugt's answer (Dec 20, 2010). He said:

>What I do is use the title() function for the subtitle and the suptitle() for the >main title (they can take different fontsize arguments). Hope that helps!

import pandas as pd
import matplotlib.pyplot as plt

d = {'series a' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
      'series b' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)

title_string = "This is the title"
subtitle_string = "This is the subtitle"

plt.figure()
df.plot(kind='bar')
plt.suptitle(title_string, y=1.05, fontsize=18)
plt.title(subtitle_string, fontsize=10)

Note: I could not comment on that answer because I'm new to stackoverflow.

How may I reference the script tag that loaded the currently-executing script?

Consider this algorithm. When your script loads (if there are multiple identical scripts), look through document.scripts, find the first script with the correct "src" attribute, and save it and mark it as 'visited' with a data-attribute or unique className.

When the next script loads, scan through document.scripts again, passing over any script already marked as visited. Take the first unvisited instance of that script.

This assumes that identical scripts will likely execute in the order in which they are loaded, from head to body, from top to bottom, from synchronous to asynchronous.

(function () {
  var scripts = document.scripts;

  // Scan for this data-* attribute
  var dataAttr = 'data-your-attribute-here';

  var i = 0;
  var script;
  while (i < scripts.length) {
    script = scripts[i];
    if (/your_script_here\.js/i.test(script.src)
        && !script.hasAttribute(dataAttr)) {

        // A good match will break the loop before
        // script is set to null.
        break;
    }

    // If we exit the loop through a while condition failure,
    // a check for null will reveal there are no matches.
    script = null;
    ++i;
  }

  /**
   * This specific your_script_here.js script tag.
   * @type {Element|Node}
   */
  var yourScriptVariable = null;

  // Mark the script an pass it on.
  if (script) {
    script.setAttribute(dataAttr, '');
    yourScriptVariable = script;
  }
})();

This will scan through all the script for the first matching script that isn't marked with the special attribute.

Then mark that node, if found, with a data-attribute so subsequent scans won't choose it. This is similar to graph traversal BFS and DFS algorithms where nodes may be marked as 'visited' to prevent revisitng.

Entity Framework - Include Multiple Levels of Properties

For EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

Make sure to add using System.Data.Entity; to get the version of Include that takes in a lambda.


For EF Core

Use the new method ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

Is there a way to run Bash scripts on Windows?

Best option? Windows 10. Native Bash support!

How to send redirect to JSP page in Servlet

    String u = request.getParameter("username");
    String p = request.getParameter("password");

    try {
        st = con.createStatement();
        String sql;
        sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
                + p + "'";
        ResultSet rs = st.executeQuery(sql);
        if (rs.next()) {
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/home.jsp");
            requestDispatcher.forward(request, response);
        } else {

            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/invalidLogin.jsp");
            requestDispatcher.forward(request, response);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        try {
            rs.close();
            ps.close();
            con.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Use CSS3 transitions with gradient backgrounds

Try use :before and :after (ie9+)

#wrapper{
    width:400px;
    height:400px;
    margin:0 auto;
    border: 1px #000 solid;
    position:relative;}
#wrapper:after,
#wrapper:before{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    content:'';
    background: #1e5799;
    background: -moz-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(50%,#2989d8), color-stop(51%,#207cca), color-stop(100%,#7db9e8));
    background: -webkit-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
    background: -o-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
    background: -ms-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
    background: linear-gradient(to bottom, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
    opacity:1;
    z-index:-1;
    -webkit-transition: all 2s ease-out;
    -moz-transition: all 2s ease-out;
    -ms-transition: all 2s ease-out;
    -o-transition: all 2s ease-out;
    transition: all 2s ease-out;
}
#wrapper:after{
    opacity:0;
    background: #87e0fd;
    background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 40%, #05abe0 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#87e0fd), color-stop(40%,#53cbf1), color-stop(100%,#05abe0));
    background: -webkit-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
    background: -o-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
    background: -ms-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
    background: linear-gradient(to bottom, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
}
#wrapper:hover:before{opacity:0;}
#wrapper:hover:after{opacity:1;}

How to save/restore serializable object to/from file?

1. Restore Object From File

From Here you can deserialize an object from file in two way.

Solution-1: Read file into a string and deserialize JSON to a type

string json = File.ReadAllText(@"c:\myObj.json");
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);

Solution-2: Deserialize JSON directly from a file

using (StreamReader file = File.OpenText(@"c:\myObj.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    MyObject myObj2 = (MyObject)serializer.Deserialize(file, typeof(MyObject));
}

2. Save Object To File

from here you can serialize an object to file in two way.

Solution-1: Serialize JSON to a string and then write string to a file

string json = JsonConvert.SerializeObject(myObj);
File.WriteAllText(@"c:\myObj.json", json);

Solution-2: Serialize JSON directly to a file

using (StreamWriter file = File.CreateText(@"c:\myObj.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(file, myObj);
}

3. Extra

You can download Newtonsoft.Json from NuGet by following command

Install-Package Newtonsoft.Json

Intercept a form submit in JavaScript and prevent normal submission

Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests. These code should be added in the top of body element to create listener before any form rendered and submitted.

In example I set hidden field to any form on page on its submission even if it happens before page load.

//Handles jquery, dojo, etc. ajax requests
(function (send) {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    XMLHttpRequest.prototype.send = function (data) {
        if (isNotEmptyString(token) && isNotEmptyString(header)) {
            this.setRequestHeader(header, token);
        }
        send.call(this, data);
    };
})(XMLHttpRequest.prototype.send);


//Handles javascript submit
(function (submit) {
    HTMLFormElement.prototype.submit = function (data) {
        var token = $("meta[name='_csrf']").attr("content");
        var paramName = $("meta[name='_csrf_parameterName']").attr("content");
        $('<input>').attr({
            type: 'hidden',
            name: paramName,
            value: token
        }).appendTo(this);

        submit.call(this, data);
    };
})(HTMLFormElement.prototype.submit);


//Handles html submit
document.body.addEventListener('submit', function (event) {
    var token = $("meta[name='_csrf']").attr("content");
    var paramName = $("meta[name='_csrf_parameterName']").attr("content");
    $('<input>').attr({
        type: 'hidden',
        name: paramName,
        value: token
    }).appendTo(event.target);
}, false);

Google Maps how to Show city or an Area outline

so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.

Calgary pinpoint

I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)

<style>
  #map {
    height: 500px;
  }
</style>
<script>

// This example creates a simple polygon representing the host city of the 
// Greatest Outdoor Show On Earth.

 function initMap() {
   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 9,
      center: {lat: 51.039, lng: -114.204},
      mapTypeId: 'terrain'
    });

    // Define the LatLng coordinates for the polygon's path.
    var triangleCoords = [
      {lat: 51.183, lng: -114.234},
      {lat: 51.154, lng: -114.235},
      {lat: 51.156, lng: -114.261},
      {lat: 51.104, lng: -114.259},
      {lat: 51.106, lng: -114.261},
      {lat: 51.102, lng: -114.272},
      {lat: 51.081, lng: -114.271},
      {lat: 51.081, lng: -114.234},
      {lat: 51.009, lng: -114.236},
      {lat: 51.008, lng: -114.141},
      {lat: 50.995, lng: -114.142},
      {lat: 50.998, lng: -114.160},
      {lat: 50.984, lng: -114.163},
      {lat: 50.987, lng: -114.141},
      {lat: 50.979, lng: -114.141},
      {lat: 50.921, lng: -114.141},
      {lat: 50.921, lng: -114.210},
      {lat: 50.893, lng: -114.210},
      {lat: 50.892, lng: -114.140},
      {lat: 50.888, lng: -114.139},
      {lat: 50.878, lng: -114.094},
      {lat: 50.878, lng: -113.994},
      {lat: 50.840, lng: -113.954},
      {lat: 50.854, lng: -113.905},
      {lat: 50.922, lng: -113.906},
      {lat: 50.935, lng: -113.877},
      {lat: 50.943, lng: -113.877},
      {lat: 50.955, lng: -113.912},
      {lat: 51.183, lng: -113.910}
    ];

    // Construct the polygon.
    var bermudaTriangle = new google.maps.Polygon({
      paths: triangleCoords,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    bermudaTriangle.setMap(map);
  }
</script>


<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>

This gets you the outline for Calgary. I've attached an image here.

Find most frequent value in SQL column

One way I like to use is:

select ,COUNT()as VAR1 from Table_Name

group by

order by VAR1 desc

limit 1

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

catch forEach last iteration

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})

Android; Check if file exists without creating a new one

if(new File("/sdcard/your_filename.txt").exists())){

// Your code goes here...

}

Make XAMPP / Apache serve file outside of htdocs folder

Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:


Virtual Hosts

  1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf.
  2. Un-comment ~line 19 (NameVirtualHost *:80).
  3. Add your virtual host (~line 36):

    <VirtualHost *:80>
        DocumentRoot C:\Projects\transitCalculator\trunk
        ServerName transitcalculator.localhost
        <Directory C:\Projects\transitCalculator\trunk>
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>
    
  4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts).

  5. Add

    127.0.0.1 transitcalculator.localhost #transitCalculator
    

    to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).

  6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).
  7. Restart Apache.

Now you can access that directory by browsing to http://transitcalculator.localhost/.


Make an Alias

  1. Starting ~line 200 of your http.conf file, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.

  2. Find the <IfModule alias_module></IfModule> section (~line 300) and add

    Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
    

    (or whatever is relevant to your desires) below the Alias comment block, inside the module tags.


Change your document root

  1. Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).

  2. Edit ~line 203 to match your new location (in this case C:/Projects).


Notes:

  • You have to use forward slashes "/" instead of back slashes "\".
  • Don't include the trailing "/" at the end.
  • restart your server.

How do I get the collection of Model State Errors in ASP.NET MVC?

Putting together several answers from above, this is what I ended up using:

var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
    .SelectMany(E => E.Errors)
    .Select(E => E.ErrorMessage)
    .ToList();

validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.

enter image description here

How to check whether a Storage item is set?

localStorage['root2']=null;

localStorage.getItem("root2") === null //false

Maybe better to do a scan of the plan ?

localStorage['root1']=187;
187
'root1' in localStorage
true

How to get the separate digits of an int number?

neither chars() nor codePoints() — the other lambda

String number = Integer.toString( 1100 );

IntStream.range( 0, number.length() ).map( i -> Character.digit( number.codePointAt( i ), 10 ) ).toArray();  // [1, 1, 0, 0]

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

How can I format a number into a string with leading zeros?

See String formatting in C# for some example uses of String.Format

Actually a better example of formatting int

String.Format("{0:00000}", 15);          // "00015"

or use String Interpolation:

$"{15:00000}";                           // "00015"

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

Core jQuery doesn't have anything special for touch events, but you can easily build your own using the following events

  • touchstart
  • touchmove
  • touchend
  • touchcancel

For example, the touchmove

document.addEventListener('touchmove', function(e) {
    e.preventDefault();
    var touch = e.touches[0];
    alert(touch.pageX + " - " + touch.pageY);
}, false);

This works in most WebKit based browsers (incl. Android).

Here is some good documentation.

How do CSS triangles work?

SASS (SCSS) triangle mixin

I wrote this to make it easier (and DRY) to automatically generate a CSS triangle:

// Triangle helper mixin (by Yair Even-Or)
// @param {Direction} $direction - either `top`, `right`, `bottom` or `left`
// @param {Color} $color [currentcolor] - Triangle color
// @param {Length} $size [1em] - Triangle size
@mixin triangle($direction, $color: currentcolor, $size: 1em) {
  $size: $size/2;
  $transparent: rgba($color, 0);
  $opposite: (top:bottom, right:left, left:right, bottom:top);

  content: '';
  display: inline-block;
  width: 0;
  height: 0;
  border: $size solid $transparent;
  border-#{map-get($opposite, $direction)}-color: $color;
  margin-#{$direction}: -$size;
}

use-case example:

span {
  @include triangle(bottom, red, 10px);
}

Playground page


Important note:
if the triangle seems pixelated in some browsers, try one of the methods described here.

Printf width specifier to maintain precision of floating-point value

Simply use the macros from <float.h> and the variable-width conversion specifier (".*"):

float f = 3.14159265358979323846;
printf("%.*f\n", FLT_DIG, f);

Pytorch tensor to numpy array

This worked for me:

np_arr = torch_tensor.cpu().detach().numpy()

setting global sql_mode in mysql

Check the documentation of sql_mode

Method 1:

Check default value of sql_mode:

SELECT @@sql_mode //check current value for sql_mode

SET GLOBAL sql_mode = "NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

Method 2:

Access phpmyadmin for editing your sql_mode

  • Login on phpmyadmin and open localhost
  • Top on Variables present on the top in menu items and search out for sql mode
  • Click on edit button to modify sql_mode based on your requirements
  • Save the changes

sql mode settings in phpmyadmin

Restart server after executing above things

Loop and get key/value pair for JSON array using jQuery

You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

Live demo.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

You can try out this one as well as. Because this worked for me and it's simple.

<style>
    <%@ include file="/css/style.css" %>
</style>

Docker error : no space left on device

  1. Clean dangled images docker rmi $(docker images -f "dangling=true" -q)
  2. Remove unwanted volumes
  3. Remove unused images
  4. Remove unused containers

Convert Float to Int in Swift

Like this:

var float:Float = 2.2 // 2.2
var integer:Int = Int(float) // 2 .. will always round down.  3.9 will be 3
var anotherFloat: Float = Float(integer) // 2.0

Initializing a two dimensional std::vector

vector<vector<int>> board;
for(int i=0;i<m;i++) {
    board.push_back({});
    for(int j=0;j<n;j++) {
        board[i].push_back(0);
    }
}

This code snippet first inserts an empty vector at each turn, in the other nested loop it pushes the elements inside the vector created by the outer loop. Hope this solves the problem.

Writing String to Stream and reading it back does not work

After you write to the MemoryStream and before you read it back, you need to Seek back to the beginning of the MemoryStream so you're not reading from the end.

UPDATE

After seeing your update, I think there's a more reliable way to build the stream:

UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";

// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object    
using(MemoryStream ms = new MemoryStream())
{
    var sw = new StreamWriter(ms, uniEncoding);
    try
    {
        sw.Write(message);
        sw.Flush();//otherwise you are risking empty stream
        ms.Seek(0, SeekOrigin.Begin);

        // Test and work with the stream here. 
        // If you need to start back at the beginning, be sure to Seek again.
    }
    finally
    {
        sw.Dispose();
    }
}

As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream. This takes the hassle out of ensuring the entire byte array for the string is written.

Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.

How to fix libeay32.dll was not found error

I've encountered this kind of problem before. I was using the Windows x64 operating system, so I was getting an error in openssl. Later I realized that the path to the OpenSSL installation file was "C: \ OpenSSL win32". Finally, I deleted the OpenSSL program and installed it to "C: \ Program Files (x86)" and used it smoothly.

How to check if a file is a valid image file?

format = [".jpg",".png",".jpeg"]
 for (path,dirs,files) in os.walk(path):
     for file in files:
         if file.endswith(tuple(format)):
             print(path)
             print ("Valid",file)
         else:
             print(path)
             print("InValid",file)

Find out how much memory is being used by an object in Python

Try this:

sys.getsizeof(object)

getsizeof() Return the size of an object in bytes. It calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

A recursive recipe

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

Check table exist or not before create it in Oracle

My solution is just compilation of best ideas in thread, with a little improvement. I use both dedicated procedure (@Tomasz Borowiec) to facilitate reuse, and exception handling (@Tobias Twardon) to reduce code and to get rid of redundant table name in procedure.

DECLARE

    PROCEDURE create_table_if_doesnt_exist(
        p_create_table_query VARCHAR2
    ) IS
    BEGIN
        EXECUTE IMMEDIATE p_create_table_query;
    EXCEPTION
        WHEN OTHERS THEN
        -- suppresses "name is already being used" exception
        IF SQLCODE = -955 THEN
            NULL; 
        END IF;
    END;

BEGIN
    create_table_if_doesnt_exist('
        CREATE TABLE "MY_TABLE" (
            "ID" NUMBER(19) NOT NULL PRIMARY KEY,
            "TEXT" VARCHAR2(4000),
            "MOD_TIME" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ');
END;
/

Javascript onclick hide div

just add onclick handler for anchor tag

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

onclick="this.parentNode.parentNode.style.display = 'none'"