Programs & Examples On #Sorl thumbnail

Thumbnails for Django

Why does a base64 encoded string have an = sign at the end

It's padding. From http://en.wikipedia.org/wiki/Base64:

In theory, the padding character is not needed for decoding, since the number of missing bytes can be calculated from the number of Base64 digits. In some implementations, the padding character is mandatory, while for others it is not used. One case in which padding characters are required is concatenating multiple Base64 encoded files.

Split comma-separated input box values into array in jquery, and loop through it

use js split() method to create an array

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentation says:

In the case of an array, the callback is passed an array index and a corresponding array value each time

$.each(keywords, function(i, keyword){
   console.log(keyword);
});

Is it possible to change the radio button icon in an android radio button group

You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl" 
    android:state_pressed="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_checked="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />  
</selector> 

Here you can use 3 different images for radiobutton

and use this file to RadioButton like:

android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content" 

How do I add my bot to a channel?

As of now:

  • Only the creator of the channel can add a bot.
  • Other administrators can't add bots to channels.
  • Channel can be public or private (doesn't matter)
  • bots can be added only as admins, not members.*

To add the bot to your channel:

  • click on the channel name: enter image description here

  • click on admins: enter image description here

  • click on Add Admin: enter image description here

  • search for your bot like @your_bot_name, and click add:** enter image description here

* In some platforms like mac native telegram client it may look like that you can add bot as a member, but at the end it won't work.
** the bot doesn't need to be in your contact list.

Get page title with Selenium WebDriver using Java

You can do it easily by Assertion using Selenium Testng framework.

Steps:

1.Create Firefox browser session

2.Initialize expected title name.

3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.

4.Get the actual title name using "driver.getTitle()" and store it in String variable.

5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;

public class PageTitleVerification
{   
private static WebDriver driver = new FirefoxDriver();

@Test
public void test01_GooglePageTitleVerify()
{               
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";      
Utility.waitForElementInDOM(driver, "Google Search", 15);   
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);   
//Verify expected page title and actual page title is same  
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle 
),"Page title not matched or Problem in loading url page");     
}
}

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utility {

/*Wait for an element to be present in DOM before specified time (in seconds ) has 
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier, 
long timeOutInSeconds) 
{       
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds        
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier))); 
}
catch(NoSuchElementException e)
{           
e.printStackTrace();
}           
}
}

Why call super() in a constructor?

A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.

When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.

Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.

As a side note, some say that it's generally best to make that call manually for reasons of clarity.

Creating a JSON response using Django and Python

You'll want to use the django serializer to help with unicode stuff:

from django.core import serializers

json_serializer = serializers.get_serializer("json")()
    response =  json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
    return HttpResponse(response, mimetype="application/json")

How to speed up insertion performance in PostgreSQL

I encountered this insertion performance problem as well. My solution is spawn some go routines to finish the insertion work. In the meantime, SetMaxOpenConns should be given a proper number otherwise too many open connection error would be alerted.

db, _ := sql.open() 
db.SetMaxOpenConns(SOME CONFIG INTEGER NUMBER) 
var wg sync.WaitGroup
for _, query := range queries {
    wg.Add(1)
    go func(msg string) {
        defer wg.Done()
        _, err := db.Exec(msg)
        if err != nil {
            fmt.Println(err)
        }
    }(query)
}
wg.Wait()

The loading speed is much faster for my project. This code snippet just gave an idea how it works. Readers should be able to modify it easily.

Good way to encapsulate Integer.parseInt()

You shouldn't use Exceptions to validate your values.

For single character there is a simple solution:

Character.isDigit()

For longer values it's better to use some utils. NumberUtils provided by Apache would work perfectly here:

NumberUtils.isNumber()

Please check https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

How do you completely remove Ionic and Cordova installation from mac?

Command to remove Cordova and ionic

  • For Window system

    • npm uninstall -g ionic
    • npm uninstall -g cordova
  • For Mac system

    • sudo npm uninstall -g ionic
    • sudo npm uninstall -g cordova
  • For install cordova and ionic

    • npm install -g cordova
    • npm install -g ionic

Note:

  • If you want to install in MAC System use before npm use sudo only.
  • And plan to install specific version of ionic and cordova then use @(version no.).

eg.

sudo npm install -g [email protected]

sudo npm install -g [email protected]

How can you export the Visual Studio Code extension list?

For Linux

On the old machine:

code --list-extensions > vscode-extensions.list

On the new machine:

cat vscode-extensions.list | xargs -L 1 code --install-extension

Differences between fork and exec

fork() creates a copy of the current process, with execution in the new child starting from just after the fork() call. After the fork(), they're identical, except for the return value of the fork() function. (RTFM for more details.) The two processes can then diverge still further, with one unable to interfere with the other, except possibly through any shared file handles.

exec() replaces the current process with a new one. It has nothing to do with fork(), except that an exec() often follows fork() when what's wanted is to launch a different child process, rather than replace the current one.

vim line numbers - how to have them on by default?

set nu set ai set tabstop=4 set ls=2 set autoindent

Add the above code in your .vimrc file. if .vimrc file is not present please create in your home directory (/home/name of user)

set nu -> This makes Vim display line numbers

set ai -> This makes Vim enable auto-indentation

set ls=2 -> This makes Vim show a status line

set tabstop=4 -> This makes Vim set tab of length 4 spaces (it is 8 by default)

enter image description here

enter image description here

The filename will also be displayed.

UITextField border color

Here's a Swift implementation. You can make an extension so that it will be usable by other views if you like.

extension UIView {
    func addBorderAndColor(color: UIColor, width: CGFloat, corner_radius: CGFloat = 0, clipsToBounds: Bool = false) {
        self.layer.borderWidth  = width
        self.layer.borderColor  = color.cgColor
        self.layer.cornerRadius = corner_radius
        self.clipsToBounds      = clipsToBounds
    }
}

Call this like: email.addBorderAndColor(color: UIColor.white, width: 0.5, corner_radius: 5, clipsToBounds: true).

How to convert List<string> to List<int>?

Convert string value into integer list

var myString = "010"; 
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();

Is there a way to use use text as the background with CSS?

You can have an absolutely positioned element inside of your relative positioned element:

_x000D_
_x000D_
#container {
   position: relative;
}

#background {
   position: absolute;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
   z-index: -1;
   overflow: hidden;
}
_x000D_
<div id="container">
    <div id="background">
    Text to have as background
    </div>
    Normal contents
</div>
_x000D_
_x000D_
_x000D_

Here's an example of it.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Should I put #! (shebang) in Python scripts, and what form should it take?

If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example:

#!/usr/bin/python2.7

Note the script could still be run via a complete Python command line, or via import, in which case the she-bang is ignored. But for scripts run directly, this is a decent reason to use the she-bang.

#!/usr/bin/env python is generally the better approach, but this helps with special cases.

Usually it would be better to establish a Python virtual environment, in which case the generic #!/usr/bin/env python would identify the correct instance of Python for the virtualenv.

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;

@Entity
public class Purchase {

    private Date date;

    @Column
    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        // force java.sql.Timestamp to be set as a java.util.Date
        this.date = new Date(date.getTime());
    }

}

SQL Query - Change date format in query to DD/MM/YYYY

If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

 SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...

Should do the job for MySQL, for SqlServer I'm sure there is an analog function. If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE for MySQL.

How to downgrade php from 5.5 to 5.3

Short answer is no.

XAMPP is normally built around a specific PHP version to ensure plugins and modules are all compatible and working correctly.

If your project specifically needs PHP 5.3 - the cleanest method is simply reinstalling an older version of XAMPP with PHP 5.3 packaged into it.

XAMPP 1.7.7 was their last update before moving off PHP 5.3.

Deleting an SVN branch

From the working copy:

svn rm branches/features
svn commit -m "delete stale feature branch"

How to break lines in PowerShell?

You can also just use:

Write-Host "";

Or, to put it in terms of your specific question:

$str = ""
foreach($line in $file){
  if($line -Match $review){ #Special condition
    $str += Write-Host ""
    $str += ANSWER #looking for ANSWER
  }
  #code.....
}

substring index range

Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end.

To make life easier for substring operation, imagine that characters are between indexes.

0 1 2 3 4 5 6 7 8 9 10  <- available indexes for substring 
 u n i v E R S i t y
        ?     ?
      start  end --> range of "E R S"

Quoting the docs:

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

How do I pass command-line arguments to a WinForms application?

This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.

Add a reference to Microsoft.VisualBasic

Create a class called WindowsFormsApplication

public class WindowsFormsApplication : WindowsFormsApplicationBase
{

    /// <summary>
    /// Runs the specified mainForm in this application context.
    /// </summary>
    /// <param name="mainForm">Form that is run.</param>
    public virtual void Run(Form mainForm)
    {
        // set up the main form.
        this.MainForm = mainForm;

        // Example code
        ((Form1)mainForm).FileName = this.CommandLineArgs[0];

        // then, run the the main form.
        this.Run(this.CommandLineArgs);
    }

    /// <summary>
    /// Runs this.MainForm in this application context. Converts the command
    /// line arguments correctly for the base this.Run method.
    /// </summary>
    /// <param name="commandLineArgs">Command line collection.</param>
    private void Run(ReadOnlyCollection<string> commandLineArgs)
    {
        // convert the Collection<string> to string[], so that it can be used
        // in the Run method.
        ArrayList list = new ArrayList(commandLineArgs);
        string[] commandLine = (string[])list.ToArray(typeof(string));
        this.Run(commandLine);
    }

}

Modify your Main() routine to look like this

static class Program
{

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var application = new WindowsFormsApplication();
        application.Run(new Form1());
    }
}

This method offers some additional usefull features (like SplashScreen support and some usefull events)

public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
public event ShutdownEventHandler Shutdown;
public event StartupEventHandler Startup;
public event StartupNextInstanceEventHandler StartupNextInstance;
public event UnhandledExceptionEventHandler UnhandledException;

Full-screen responsive background image

Simple fullscreen and centered image https://jsfiddle.net/maestro888/3a9Lrmho

_x000D_
_x000D_
jQuery(function($) {_x000D_
    function resizeImage() {_x000D_
        $('.img-fullscreen').each(function () {_x000D_
            var $imgWrp = $(this);_x000D_
_x000D_
            $('img', this).each(function () {_x000D_
                var imgW = $(this)[0].width,_x000D_
                    imgH = $(this)[0].height;_x000D_
_x000D_
                $(this).removeClass();_x000D_
_x000D_
                $imgWrp.css({_x000D_
                    width: $(window).width(),_x000D_
                    height: $(window).height()_x000D_
                });_x000D_
_x000D_
                imgW / imgH < $(window).width() / $(window).height() ?_x000D_
                    $(this).addClass('full-width') : $(this).addClass('full-height');_x000D_
            });_x000D_
        });_x000D_
    }_x000D_
_x000D_
    window.onload = function () {_x000D_
        resizeImage();_x000D_
    };_x000D_
_x000D_
    window.onresize = function () {_x000D_
        setTimeout(resizeImage, 300);_x000D_
    };_x000D_
 _x000D_
    resizeImage();_x000D_
});
_x000D_
/*_x000D_
 * Hide scrollbars_x000D_
 */_x000D_
_x000D_
#wrapper {_x000D_
    overflow: hidden;_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Basic styles_x000D_
 */_x000D_
_x000D_
.img-fullscreen {_x000D_
    position: relative;_x000D_
    overflow: hidden;_x000D_
}_x000D_
_x000D_
.img-fullscreen img {_x000D_
    vertical-align: middle;_x000D_
    position: absolute;_x000D_
    display: table;_x000D_
    margin: auto;_x000D_
    height: auto;_x000D_
    width: auto;_x000D_
    bottom: -100%;_x000D_
    right: -100%;_x000D_
    left: -100%;_x000D_
    top: -100%;_x000D_
}_x000D_
_x000D_
.img-fullscreen .full-width {_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.img-fullscreen .full-height {_x000D_
    height: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="wrapper">_x000D_
    <div class="img-fullscreen">_x000D_
        <img src="https://static.pexels.com/photos/33688/delicate-arch-night-stars-landscape.jpg" alt=""/>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CodeIgniter htaccess and URL rewrite issues

I am using something like this - codeigniter-htaccess-file, its a good article to begin with.

  • leave the .htaccess file in CI root dir
  • make sure that mod_rewrite is on
  • check for typos (ie. controller file/class name)
  • in /application/config/config.php set $config['index_page'] = "";
  • in /application/config/routes.php set your default controller $route['default_controller']="home";

If you are running clean installation of CI (2.1.3) there isn't really much that could be wrong.

  • 2 config files
  • controller
  • .htaccess
  • mod_rewrite

read

window.onload vs $(document).ready()

One thing to remember (or should I say recall) is that you cannot stack onloads like you can with ready. In other words, jQuery magic allows multiple readys on the same page, but you can't do that with onload.

The last onload will overrule any previous onloads.

A nice way to deal with that is with a function apparently written by one Simon Willison and described in Using Multiple JavaScript Onload Functions.

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

// Example use:
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* More code to run on page load */
});

HTML5 Canvas Rotate Image

This is full degree image rotation code. I recommend you to check the below example app in the jsfiddle.

https://jsfiddle.net/casamia743/xqh48gno/

enter image description here

The process flow of this example app is

  1. load Image, calculate boundaryRad
  2. create temporary canvas
  3. move canvas context origin to joint position of the projected rect
  4. rotate canvas context with input degree amount
  5. use canvas.toDataURL method to make image blob
  6. using image blob, create new Image element and render

function init() {
  ...
  image.onload = function() {
     app.boundaryRad = Math.atan(image.width / image.height);
  }
  ...
}



/**
 * NOTE : When source rect is rotated at some rad or degrees, 
 * it's original width and height is no longer usable in the rendered page.
 * So, calculate projected rect size, that each edge are sum of the 
 * width projection and height projection of the original rect.
 */
function calcProjectedRectSizeOfRotatedRect(size, rad) {
  const { width, height } = size;

  const rectProjectedWidth = Math.abs(width * Math.cos(rad)) + Math.abs(height * Math.sin(rad));
  const rectProjectedHeight = Math.abs(width * Math.sin(rad)) + Math.abs(height * Math.cos(rad));

  return { width: rectProjectedWidth, height: rectProjectedHeight };
}

/**
 * @callback rotatedImageCallback
 * @param {DOMString} dataURL - return value of canvas.toDataURL()
 */

/**
 * @param {HTMLImageElement} image 
 * @param {object} angle
 * @property {number} angle.degree 
 * @property {number} angle.rad
 * @param {rotatedImageCallback} cb
 * 
 */
function getRotatedImage(image, angle, cb) {
  const canvas = document.createElement('canvas');
  const { degree, rad: _rad } = angle;

  const rad = _rad || degree * Math.PI / 180 || 0;
  debug('rad', rad);

  const { width, height } = calcProjectedRectSizeOfRotatedRect(
    { width: image.width, height: image.height }, rad
  );
  debug('image size', image.width, image.height);
  debug('projected size', width, height);

  canvas.width = Math.ceil(width);
  canvas.height = Math.ceil(height);

  const ctx = canvas.getContext('2d');
  ctx.save();

  const sin_Height = image.height * Math.abs(Math.sin(rad))
  const cos_Height = image.height * Math.abs(Math.cos(rad))
  const cos_Width = image.width * Math.abs(Math.cos(rad))
  const sin_Width = image.width * Math.abs(Math.sin(rad))

  debug('sin_Height, cos_Width', sin_Height, cos_Width);
  debug('cos_Height, sin_Width', cos_Height, sin_Width);

  let xOrigin, yOrigin;

  if (rad < app.boundaryRad) {
    debug('case1');
    xOrigin = Math.min(sin_Height, cos_Width);
    yOrigin = 0;
  } else if (rad < Math.PI / 2) {
    debug('case2');
    xOrigin = Math.max(sin_Height, cos_Width);
    yOrigin = 0;
  } else if (rad < Math.PI / 2 + app.boundaryRad) {
    debug('case3');
    xOrigin = width;
    yOrigin = Math.min(cos_Height, sin_Width);
  } else if (rad < Math.PI) {
    debug('case4');
    xOrigin = width;
    yOrigin = Math.max(cos_Height, sin_Width);
  } else if (rad < Math.PI + app.boundaryRad) {
    debug('case5');
    xOrigin = Math.max(sin_Height, cos_Width);
    yOrigin = height;
  } else if (rad < Math.PI / 2 * 3) {
    debug('case6');
    xOrigin = Math.min(sin_Height, cos_Width);
    yOrigin = height;
  } else if (rad < Math.PI / 2 * 3 + app.boundaryRad) {
    debug('case7');
    xOrigin = 0;
    yOrigin = Math.max(cos_Height, sin_Width);
  } else if (rad < Math.PI * 2) {
    debug('case8');
    xOrigin = 0;
    yOrigin = Math.min(cos_Height, sin_Width);
  }

  debug('xOrigin, yOrigin', xOrigin, yOrigin)

  ctx.translate(xOrigin, yOrigin)
  ctx.rotate(rad);
  ctx.drawImage(image, 0, 0);
  if (DEBUG) drawMarker(ctx, 'red');

  ctx.restore();

  const dataURL = canvas.toDataURL('image/jpg');

  cb(dataURL);
}

function render() {
    getRotatedImage(app.image, {degree: app.degree}, renderResultImage)
}

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

You need to link the with the -lm linker option

You need to compile as

gcc test.c  -o test -lm

gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l linker option followed by the library name m thus -lm.

Get viewport/window height in ReactJS

// just use (useEffect). every change will be logged with current value
import React, { useEffect } from "react";

export function () {
  useEffect(() => {
    window.addEventListener('resize', () => {
      const myWidth  = window.innerWidth;
      console.log('my width :::', myWidth)
   })
  },[window])

  return (
    <>
      enter code here
   </>
  )
}

Extract and delete all .gz in a directory- Linux

There's more than one way to do this obviously.

    # This will find files recursively (you can limit it by using some 'find' parameters. 
    # see the man pages
    # Final backslash required for exec example to work
    find . -name '*.gz' -exec gunzip '{}' \;

    # This will do it only in the current directory
    for a in *.gz; do gunzip $a; done

I'm sure there's other ways as well, but this is probably the simplest.

And to remove it, just do a rm -rf *.gz in the applicable directory

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

I created simple examples to clarify understanding of ManualResetEvent vs AutoResetEvent.

AutoResetEvent: lets assume you have 3 workers thread. If any of those threads will call WaitOne() all other 2 threads will stop execution and wait for signal. I am assuming they are using WaitOne(). It is like; if I do not work, nobody works. In first example you can see that

autoReset.Set();
Thread.Sleep(1000);
autoReset.Set();

When you call Set() all threads will work and wait for signal. After 1 second I am sending second signal and they execute and wait (WaitOne()). Think about these guys are soccer team players and if one player says I will wait until manager calls me, and others will wait until manager tells them to continue (Set())

public class AutoResetEventSample
{
    private AutoResetEvent autoReset = new AutoResetEvent(false);

    public void RunAll()
    {
        new Thread(Worker1).Start();
        new Thread(Worker2).Start();
        new Thread(Worker3).Start();
        autoReset.Set();
        Thread.Sleep(1000);
        autoReset.Set();
        Console.WriteLine("Main thread reached to end.");
    }

    public void Worker1()
    {
        Console.WriteLine("Entered in worker 1");
        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker1 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
    public void Worker2()
    {
        Console.WriteLine("Entered in worker 2");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker2 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
    public void Worker3()
    {
        Console.WriteLine("Entered in worker 3");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker3 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
}

In this example you can clearly see that when you first hit Set() it will let all threads go, then after 1 second it signals all threads to wait! As soon as you set them again regardless they are calling WaitOne() inside, they will keep running because you have to manually call Reset() to stop them all.

manualReset.Set();
Thread.Sleep(1000);
manualReset.Reset();
Console.WriteLine("Press to release all threads.");
Console.ReadLine();
manualReset.Set();

It is more about Referee/Players relationship there regardless of any of the player is injured and wait for playing others will continue to work. If Referee says wait (Reset()) then all players will wait until next signal.

public class ManualResetEventSample
{
    private ManualResetEvent manualReset = new ManualResetEvent(false);

    public void RunAll()
    {
        new Thread(Worker1).Start();
        new Thread(Worker2).Start();
        new Thread(Worker3).Start();
        manualReset.Set();
        Thread.Sleep(1000);
        manualReset.Reset();
        Console.WriteLine("Press to release all threads.");
        Console.ReadLine();
        manualReset.Set();
        Console.WriteLine("Main thread reached to end.");
    }

    public void Worker1()
    {
        Console.WriteLine("Entered in worker 1");
        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker1 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
    public void Worker2()
    {
        Console.WriteLine("Entered in worker 2");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker2 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
    public void Worker3()
    {
        Console.WriteLine("Entered in worker 3");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker3 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
}

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

How to count number of files in each directory?

Assuming you have GNU find, let it find the directories and let bash do the rest:

find . -type d -print0 | while read -d '' -r dir; do
    files=("$dir"/*)
    printf "%5d files in directory %s\n" "${#files[@]}" "$dir"
done

How can I add items to an empty set in python

When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

How to scroll UITableView to specific position

Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES]; Scrolls the receiver until a row identified by index path is at a particular location on the screen.

And

scrollToNearestSelectedRowAtScrollPosition:animated:

Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.

FFT in a single C-file

This file works properly as it is: just copy and paste in your computer. Surfing on the web I have found this easy implementation on wikipedia page here. The page is in italian, so I re-wrote the code with some translations. Here there are almost the same informations but in english. ENJOY!

#include <iostream>
#include <complex>
#define MAX 200

using namespace std;

#define M_PI 3.1415926535897932384

int log2(int N)    /*function to calculate the log2(.) of int numbers*/
{
  int k = N, i = 0;
  while(k) {
    k >>= 1;
    i++;
  }
  return i - 1;
}

int check(int n)    //checking if the number of element is a power of 2
{
  return n > 0 && (n & (n - 1)) == 0;
}

int reverse(int N, int n)    //calculating revers number
{
  int j, p = 0;
  for(j = 1; j <= log2(N); j++) {
    if(n & (1 << (log2(N) - j)))
      p |= 1 << (j - 1);
  }
  return p;
}

void ordina(complex<double>* f1, int N) //using the reverse order in the array
{
  complex<double> f2[MAX];
  for(int i = 0; i < N; i++)
    f2[i] = f1[reverse(N, i)];
  for(int j = 0; j < N; j++)
    f1[j] = f2[j];
}

void transform(complex<double>* f, int N) //
{
  ordina(f, N);    //first: reverse order
  complex<double> *W;
  W = (complex<double> *)malloc(N / 2 * sizeof(complex<double>));
  W[1] = polar(1., -2. * M_PI / N);
  W[0] = 1;
  for(int i = 2; i < N / 2; i++)
    W[i] = pow(W[1], i);
  int n = 1;
  int a = N / 2;
  for(int j = 0; j < log2(N); j++) {
    for(int i = 0; i < N; i++) {
      if(!(i & n)) {
        complex<double> temp = f[i];
        complex<double> Temp = W[(i * a) % (n * a)] * f[i + n];
        f[i] = temp + Temp;
        f[i + n] = temp - Temp;
      }
    }
    n *= 2;
    a = a / 2;
  }
  free(W);
}

void FFT(complex<double>* f, int N, double d)
{
  transform(f, N);
  for(int i = 0; i < N; i++)
    f[i] *= d; //multiplying by step
}

int main()
{
  int n;
  do {
    cout << "specify array dimension (MUST be power of 2)" << endl;
    cin >> n;
  } while(!check(n));
  double d;
  cout << "specify sampling step" << endl; //just write 1 in order to have the same results of matlab fft(.)
  cin >> d;
  complex<double> vec[MAX];
  cout << "specify the array" << endl;
  for(int i = 0; i < n; i++) {
    cout << "specify element number: " << i << endl;
    cin >> vec[i];
  }
  FFT(vec, n, d);
  cout << "...printing the FFT of the array specified" << endl;
  for(int j = 0; j < n; j++)
    cout << vec[j] << endl;
  return 0;
}

scrollTop jquery, scrolling to div with id?

try this

    $('#div_id').animate({scrollTop:0}, '500', 'swing');

boto3 client NoRegionError: You must specify a region error only sometimes

I believe, by default, boto picks the region which is set in aws cli. You can run command #aws configure and press enter (it shows what creds you have set in aws cli with region)twice to confirm your region.

Vim: How to insert in visual block mode?

Try this

After selecting a block of text, press Shift+i or capital I.

Lowercase i will not work.

Then type the things you want and finally to apply it to all lines, press Esc twice.




If this doesn't work...

Check if you have +visualextra enabled in your version of Vim.

You can do this by typing in :ver and scrolling through the list of features. (You might want to copy and paste it into a buffer and do incremental search because the format is odd.)

Enabling it is outside the scope of this question but I'm sure you can find it somewhere.

Setting size for icon in CSS

Funnily enough, adjusting the padding seems to do it.

_x000D_
_x000D_
.arrow {
  border: solid rgb(2, 0, 0);
  border-width: 0 3px 3px 0;
  display: inline-block;
}

.first{
  padding: 2vh;
}

.second{
  padding: 4vh;
}

.left {
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
 }
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
_x000D_
_x000D_

Calculate relative time in C#

There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation.

DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"

DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"

TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"

Scott Hanselman has a writeup on it on his blog

form action with javascript

A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.

The best is to just set form action to your PHP script; if you need to do anything before submission you can just add to onsubmit

Edit turned out you didn't need any extra function, just a small change here:

function validateFormOnSubmit(theForm) {
    var reason = "";
    reason += validateName(theForm.name);
    reason += validatePhone(theForm.phone);
    reason += validateEmail(theForm.emaile);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
    } else {
        simpleCart.checkout();
    }
    return false;
}

Then in your form:

<form action="#" onsubmit="return validateFormOnSubmit(this);">

How do I generate random integers within a specific range in Java?

I just generate a random number using Math.random() and multiply it by a big number, let's say 10000. So, I get a number between 0 to 10,000 and call this number i. Now, if I need numbers between (x, y), then do the following:

i = x + (i % (y - x));

So, all i's are numbers between x and y.

To remove the bias as pointed out in the comments, rather than multiplying it by 10000 (or the big number), multiply it by (y-x).

How can I initialize an ArrayList with all zeroes in Java?

The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:

for (int i = 0; i < 60; i++) {
    list.add(0);
}

UTF-8 all the way through

Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.

The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)

Is Safari on iOS 6 caching $.ajax results?

From my own blog post iOS 6.0 caching Ajax POST requests:

How to fix it: There are various methods to prevent caching of requests. The recommended method is adding a no-cache header. This is how it is done.

jQuery:

Check for iOS 6.0 and set Ajax header like this:

$.ajaxSetup({ cache: false });

ZeptoJS:

Check for iOS 6.0 and set the Ajax header like this:

$.ajax({
    type: 'POST',
    headers : { "cache-control": "no-cache" },
    url : ,
    data:,
    dataType : 'json',
    success : function(responseText) {…}

Server side

Java:

httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");

Make sure to add this at the top the page before any data is sent to the client.

.NET

Response.Cache.SetNoStore();

Or

Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

PHP

header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.

How do I hide an element when printing a web page?

In your stylesheet add:

@media print
{    
    .no-print, .no-print *
    {
        display: none !important;
    }
}

Then add class='no-print' (or add the no-print class to an existing class statement) in your HTML that you don't want to appear in the printed version, such as your button.

width:auto for <input> fields

"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."

No one actually answered the above part of the original poster's question.

Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/

As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...

On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.

To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/

Create a txt file using batch file in a specific folder

You can also use

cd %localhost%

to set the directory to the folder the batch file was opened from. Your script would look like this:

@echo off
cd %localhost%
echo .> dblank.txt

Make sure you set the directory before you use the command to create the text file.

Sql query to insert datetime in SQL Server

you need to add it like

insert into table1(date1) values('12-mar-2013');

How to get the real and total length of char * (char array)?

Given just the pointer, you can't. You'll have to keep hold of the length you passed to new[] or, better, use std::vector to both keep track of the length, and release the memory when you've finished with it.

Note: this answer only addresses C++, not C.

Why can't I center with margin: 0 auto?

An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.

This is how it works for me:

#content {
display: block;
margin: 0 auto;
}

How to hash a password

  1. Create a salt,
  2. Create a hash password with salt
  3. Save both hash and salt
  4. decrypt with password and salt... so developers cant decrypt password
public class CryptographyProcessor
{
    public string CreateSalt(int size)
    {
        //Generate a cryptographic random number.
          RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
         byte[] buff = new byte[size];
         rng.GetBytes(buff);
         return Convert.ToBase64String(buff);
    }


      public string GenerateHash(string input, string salt)
      { 
         byte[] bytes = Encoding.UTF8.GetBytes(input + salt);
         SHA256Managed sHA256ManagedString = new SHA256Managed();
         byte[] hash = sHA256ManagedString.ComputeHash(bytes);
         return Convert.ToBase64String(hash);
      }

      public bool AreEqual(string plainTextInput, string hashedInput, string salt)
      {
           string newHashedPin = GenerateHash(plainTextInput, salt);
           return newHashedPin.Equals(hashedInput); 
      }
 }

Better naming in Tuple classes than "Item1", "Item2"

C# 7 tuple example

var tuple = TupleExample(key, value);

     private (string key1, long value1) ValidateAPIKeyOwnerId(string key, string value)
            {
                return (key, value);
            }
      if (!string.IsNullOrEmpty(tuple.key1) && tuple.value1 > 0)
          {
                    //your code

                }     

How to prevent sticky hover effects for buttons on touch devices

Based on Darren Cooks answer which also works if you moved your finger over another element.

See Find element finger is on during a touchend event

jQuery(function() {
    FastClick.attach(document.body);
});
// Prevent sticky hover effects for buttons on touch devices
// From https://stackoverflow.com/a/17234319
//
//
// Usage:
// <a href="..." touch-focus-fix>..</a>
//
// Refactored from a directive for better performance and compability
jQuery(document.documentElement).on('touchend', function(event) {
  'use strict';

  function fix(sourceElement) {
    var el = $(sourceElement).closest('[touch-focus-fix]')[0];
    if (!el) {
      return;
    }
    var par = el.parentNode;
    var next = el.nextSibling;
    par.removeChild(el);
    par.insertBefore(el, next);
  }

  fix(event.target);
  var changedTouch = event.originalEvent.changedTouches[0];
  // http://www.w3.org/TR/2011/WD-touch-events-20110505/#the-touchend-event
  if (!changedTouch) {
    return;
  }
  var touchTarget = document.elementFromPoint(changedTouch.clientX, changedTouch.clientY);
  if (touchTarget && touchTarget !== event.target) {
    fix(touchTarget);
  }
});

Codepen Demo

Git: How do I list only local branches?

git branch -a - All branches.

git branch -r - Remote branches only.

git branch -l or git branch - Local branches only.

C - determine if a number is prime

OK, so forget about C. Suppose I give you a number and ask you to determine if it's prime. How do you do it? Write down the steps clearly, then worry about translating them into code.

Once you have the algorithm determined, it will be much easier for you to figure out how to write a program, and for others to help you with it.

edit: Here's the C# code you posted:

static bool IsPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0 && i != number) return false;
    }
    return true;
}

This is very nearly valid C as is; there's no bool type in C, and no true or false, so you need to modify it a little bit (edit: Kristopher Johnson correctly points out that C99 added the stdbool.h header). Since some people don't have access to a C99 environment (but you should use one!), let's make that very minor change:

int IsPrime(int number) {
    int i;
    for (i=2; i<number; i++) {
        if (number % i == 0 && i != number) return 0;
    }
    return 1;
}

This is a perfectly valid C program that does what you want. We can improve it a little bit without too much effort. First, note that i is always less than number, so the check that i != number always succeeds; we can get rid of it.

Also, you don't actually need to try divisors all the way up to number - 1; you can stop checking when you reach sqrt(number). Since sqrt is a floating-point operation and that brings a whole pile of subtleties, we won't actually compute sqrt(number). Instead, we can just check that i*i <= number:

int IsPrime(int number) {
    int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

One last thing, though; there was a small bug in your original algorithm! If number is negative, or zero, or one, this function will claim that the number is prime. You likely want to handle that properly, and you may want to make number be unsigned, since you're more likely to care about positive values only:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

This definitely isn't the fastest way to check if a number is prime, but it works, and it's pretty straightforward. We barely had to modify your code at all!

Create an instance of a class from a string

I've used this method successfully:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

You'll need to cast the returned object to your desired object type.

Display names of all constraints for a table in Oracle SQL

Often enterprise databases have several users and I'm not aways on the right one :

SELECT * FROM ALL_CONSTRAINTS WHERE table_name = 'YOUR TABLE NAME' ;

Picked from Oracle documentation

Access parent URL from iframe

This worked for me to access the iframe src url.

window.document.URL

java get file size efficiently

I ran into this same issue. I needed to get the file size and modified date of 90,000 files on a network share. Using Java, and being as minimalistic as possible, it would take a very long time. (I needed to get the URL from the file, and the path of the object as well. So its varied somewhat, but more than an hour.) I then used a native Win32 executable, and did the same task, just dumping the file path, modified, and size to the console, and executed that from Java. The speed was amazing. The native process, and my string handling to read the data could process over 1000 items a second.

So even though people down ranked the above comment, this is a valid solution, and did solve my issue. In my case I knew the folders I needed the sizes of ahead of time, and I could pass that in the command line to my win32 app. I went from hours to process a directory to minutes.

The issue did also seem to be Windows specific. OS X did not have the same issue and could access network file info as fast as the OS could do so.

Java File handling on Windows is terrible. Local disk access for files is fine though. It was just network shares that caused the terrible performance. Windows could get info on the network share and calculate the total size in under a minute too.

--Ben

What is the difference between static func and class func in Swift?

I did some experiments in playground and got some conclusions.

TL;DR enter image description here

As you can see, in the case of class, the use of class func or static func is just a question of habit.

Playground example with explanation:

class Dog {
    final func identity() -> String {
        return "Once a woofer, forever a woofer!"
    }

    class func talk() -> String {
        return "Woof woof!"
    }

    static func eat() -> String {
        return "Miam miam"
    }

    func sleep() -> String {
        return "Zzz"
    }
}

class Bulldog: Dog {
    // Can not override a final function
//    override final func identity() -> String {
//        return "I'm once a dog but now I'm a cat"
//    }

    // Can not override a "class func", but redeclare is ok
    func talk() -> String {
        return "I'm a bulldog, and I don't woof."
    }

    // Same as "class func"
    func eat() -> String {
        return "I'm a bulldog, and I don't eat."
    }

    // Normal function can be overridden
    override func sleep() -> String {
        return "I'm a bulldog, and I don't sleep."
    }
}

let dog = Dog()
let bullDog = Bulldog()

// FINAL FUNC
//print(Dog.identity()) // compile error
print(dog.identity()) // print "Once a woofer, forever a woofer!"
//print(Bulldog.identity()) // compile error
print(bullDog.identity()) // print "Once a woofer, forever a woofer!"

// => "final func" is just a "normal" one but prevented to be overridden nor redeclared by subclasses.


// CLASS FUNC
print(Dog.talk()) // print "Woof woof!", called directly from class
//print(dog.talk()) // compile error cause "class func" is meant to be called directly from class, not an instance.
print(Bulldog.talk()) // print "Woof woof!" cause it's called from Bulldog class, not bullDog instance.
print(bullDog.talk()) // print "I'm a bulldog, and I don't woof." cause talk() is redeclared and it's called from bullDig instance

// => "class func" is like a "static" one, must be called directly from class or subclassed, can be redeclared but NOT meant to be overridden.

// STATIC FUNC
print(Dog.eat()) // print "Miam miam"
//print(dog.eat()) // compile error cause "static func" is type method
print(Bulldog.eat()) // print "Miam miam"
print(bullDog.eat()) // print "I'm a bulldog, and I don't eat."

// NORMAL FUNC
//print(Dog.sleep()) // compile error
print(dog.sleep()) // print "Zzz"
//print(Bulldog.sleep()) // compile error
print(bullDog.sleep()) // print "I'm a bulldog, and I don't sleep."

error: Your local changes to the following files would be overwritten by checkout

You can force checkout your branch, if you do not want to commit your local changes.

git checkout -f branch_name

"Invalid form control" only in Google Chrome

If you don't care about HTML5 validation (maybe you are validating in JS or on the server), you could try adding "novalidate" to the form or the input elements.

Android Studio: Can't start Git

Try this...

  1. Make sure, have you installed git on your machine. If not you can download(Windows user) from here and install it your system. For Mac user can download from here

  2. Get location of git.exe Get location of git.exe

  3. Test git.exe manually test

  4. Now you can set your git.exe location in android studio.

Conditional formatting using AND() function

COLUMN() and ROW() won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.

For instance, if you want to use this conditional formating on a range begining on cell A1, you can try:

`COLUMN(A1)` and `ROW(A1)`

Excel will automatically adapt the conditional formating to the current cell.

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

+--------------------+-------------------+--------+
|                 _c5|                _c7|count(1)|
+--------------------+-------------------+--------+
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|
+--------------------+-------------------+--------+

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

MySQL - How to select data by string length

I used this sentences to filter

SELECT table.field1, table.field2 FROM table WHERE length(field) > 10;

you can change 10 for other number that you want to filter.

How to remove duplicate white spaces in string using Java?

You can use the regex

(\s)\1

and

replace it with $1.

Java code:

str = str.replaceAll("(\\s)\\1","$1");

If the input is "foo\t\tbar " you'll get "foo\tbar " as output
But if the input is "foo\t bar" it will remain unchanged because it does not have any consecutive whitespace characters.

If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:

str = str.replaceAll("\\s+"," ");

But if you want to replace two consecutive white space with a single space you should do:

str = str.replaceAll("\\s{2}"," ");

jQuery show for 5 seconds then hide

You can use the below effect to animate, you can change the values as per your requirements

$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow'); 

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

How do you keep parents of floated elements from collapsing?

I use 2 and 4 where applicable (i.e. when I know the content's height or if overflowing doesn't harm). Anywhere else, I go with solution 3. By the way, your first solution has no advantage over 3 (that I can spot) because it isn't any more semantic since it uses the same dummy element.

By the way, I wouldn't be concerned about the fourth solution being a hack. Hacks in CSS would only be harmful if their underlying behaviour is subject to reinterpretation or other change. This way, your hack wouldn't be guaranteed to work. However in this case, your hack relies on the exact behaviour that overflow: auto is meant to have. No harm in hitching a free ride.

How to POST a FORM from HTML to ASPX page

Hope this will help - Put this tag in html and

remove your login.aspx design content..just write only page directive

and you will get the values in aspx page after submit button click like this- protected void Page_Load(object sender, EventArgs e) {

        if (!IsPostBack)
        {
            CompleteRegistration();
        }
    }

public void CompleteRegistration() {

        NameValueCollection nv = Request.Form;
        if (nv.Count != 0)
        {
            string strname = nv["txtbox1"];
            string strPwd = nv["txtbox2"];
        }
    }

How to check if a function exists on a SQL database

Why not just:

IF object_id('YourFunctionName', 'FN') IS NOT NULL
BEGIN
    DROP FUNCTION [dbo].[YourFunctionName]
END
GO

The second argument of object_id is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:

  • FN : Scalar function
  • IF : Inline table-valued function
  • TF : Table-valued-function
  • FS : Assembly (CLR) scalar-function
  • FT : Assembly (CLR) table-valued function

How to Apply Mask to Image in OpenCV?

You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.

Insert image after each list item

ul li + li:before
{
    content:url(imgs/separator.gif);
}

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

Formatting PowerShell Get-Date inside string

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:

$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u") 

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

C#: Looping through lines of multiline string

You can use a StringReader to read a line at a time:

using (StringReader reader = new StringReader(input))
{
    string line = string.Empty;
    do
    {
        line = reader.ReadLine();
        if (line != null)
        {
            // do something with the line
        }

    } while (line != null);
}

How can I force clients to refresh JavaScript files?

The common practice nowadays is to generate a content hash code as part of the file name to force the browser especially IE to reload the javascript files or css files.

For example,

vendor.a7561fb0e9a071baadb9.js
main.b746e3eb72875af2caa9.js

It is generally the job for the build tools such as webpack. Here is more details if anyone wants to try out if you are using webpack.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Overview

As reported by Tim Anderson

Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.

Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.

Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.

Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.

edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)

Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:

We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)

This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.

Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.

PhoneGap

The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.

To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.

PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.

  • Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.

  • Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.

  • Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).

  • Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.

by Karl Waclawek

Appcelerator Titanium

The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.

So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.

Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO

Xamarin (+ MVVMCross)

AZDevelop.net

Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.

In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.

From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.

In my opinion there are several HUGE advantages including

  • native performance
  • easier to read code (IMO)
  • testability
  • shared code between client and server
  • support (although Xam could do better on bugzilla)

Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.

Conclusion

My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.

I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.

References and links

Having services in React application

Keep in mind that the purpose of React is to better couple things that logically should be coupled. If you're designing a complicated "validate password" method, where should it be coupled?

Well you're going to need to use it every time the user needs to input a new password. This could be on the registration screen, a "forgot password" screen, an administrator "reset password for another user" screen, etc.

But in any of those cases, it's always going to be tied to some text input field. So that's where it should be coupled.

Make a very small React component that consists solely of an input field and the associated validation logic. Input that component within all of the forms that might want to have a password input.

It's essentially the same outcome as having a service/factory for the logic, but you're coupling it directly to the input. So you now never need to tell that function where to look for it's validation input, as it is permanently tied together.

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me.

But make sure you include x64 JDK and JRE addresses in your path.

Angular 2: 404 error occur when I refresh through the browser

If you're running Angular 2 through ASP.NET Core 1 in Visual Studio 2015, you might find this solution from Jürgen Gutsch helpful. He describes it in a blog post. It was the best solution for me. Place the C# code provided below in your Startup.cs public void Configure() just before app.UseStaticFiles();

app.Use( async ( context, next ) => {
    await next();

    if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
        context.Request.Path = "/index.html";
        await next();
    }
});

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

If the python version is 3.X, it's okay.

I think your python version is 2.X, the super would work when adding this code

__metaclass__ = type

so the code is

__metaclass__ = type
class B:
    def meth(self, arg):
        print arg
class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)
print C().meth(1)

Exit from app when click button in android phonegap?

navigator.app.exitApp();

add this line where you want you exit the application.

Collection that allows only unique items in .NET?

Just to add my 2 cents...

if you need a ValueExistingException-throwing HashSet<T> you can also create your collection easily:

public class ThrowingHashSet<T> : ICollection<T>
{
    private HashSet<T> innerHash = new HashSet<T>();

    public void Add(T item)
    {
        if (!innerHash.Add(item))
            throw new ValueExistingException();
    }

    public void Clear()
    {
        innerHash.Clear();
    }

    public bool Contains(T item)
    {
        return innerHash.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        innerHash.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return innerHash.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public bool Remove(T item)
    {
        return innerHash.Remove(item);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return innerHash.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

this can be useful for example if you need it in many places...

Format number to always show 2 decimal places

parseInt(number * 100) / 100; worked for me.

Difference between Subquery and Correlated Subquery

Above example is not Co-related Sub-Query. It is Derived Table / Inline-View since i.e, a Sub-query within FROM Clause.

A Corelated Sub-query should refer its parent(main Query) Table in it. For example See find the Nth max salary by Co-related Sub-query:

SELECT Salary 
FROM Employee E1
WHERE N-1 = (SELECT COUNT(*)
             FROM Employee E2
             WHERE E1.salary <E2.Salary) 

Co-Related Vs Nested-SubQueries.

Technical difference between Normal Sub-query and Co-related sub-query are:

1. Looping: Co-related sub-query loop under main-query; whereas nested not; therefore co-related sub-query executes on each iteration of main query. Whereas in case of Nested-query; subquery executes first then outer query executes next. Hence, the maximum no. of executes are NXM for correlated subquery and N+M for subquery.

2. Dependency(Inner to Outer vs Outer to Inner): In the case of co-related subquery, inner query depends on outer query for processing whereas in normal sub-query, Outer query depends on inner query.

3.Performance: Using Co-related sub-query performance decreases, since, it performs NXM iterations instead of N+M iterations. ¨ Co-related Sub-query Execution.

For more information with examples :

http://dotnetauthorities.blogspot.in/2013/12/Microsoft-SQL-Server-Training-Online-Learning-Classes-Sql-Sub-Queries-Nested-Co-related.html

How to construct a std::string from a std::vector<char>?

I like Stefan’s answer (Sep 11 ’13) but would like to make it a bit stronger:

If the vector ends with a null terminator, you should not use (v.begin(), v.end()): you should use v.data() (or &v[0] for those prior to C++17).

If v does not have a null terminator, you should use (v.begin(), v.end()).

If you use begin() and end() and the vector does have a terminating zero, you’ll end up with a string "abc\0" for example, that is of length 4, but should really be only "abc".

Are there best practices for (Java) package organization?

I prefer feature before layers, but I guess it depends on you project. Consider your forces:

  • Dependencies
    Try minimize package dependencies, especially between features. Extract APIs if necessary.
  • Team organization
    In some organizations teams work on features and in others on layers. This influence how code is organized, use it to formalize APIs or encourage cooperation.
  • Deployment and versioning
    Putting everything into a module make deployment and versioning simpler, but bug fixing harder. Splitting things enable better control, scalability and availability.
  • Respond to change
    Well organized code is much simpler to change than a big ball of mud.
  • Size (people and lines of code)
    The bigger the more formalized/standardized it needs to be.
  • Importance/quality
    Some code is more important than other. APIs should be more stable then the implementation. Therefore it needs to be clearly separated.
  • Level of abstraction and entry point
    It should be possible for an outsider to know what the code is about, and where to start reading from looking at the package tree.

Example:

com/company/module
  + feature1/
    - MainClass          // The entry point for exploring
    + api/               // Public interface, used by other features
    + domain/
      - AggregateRoot
      + api/             // Internal API, complements the public, used by web
      + impl/ 
    + persistence/       
    + web/               // presentation layer 
    + services/          // Rest or other remote API 
    + support/            
  + feature2/
  + support/             // Any support or utils used by more than on feature
    + io
    + config
    + persistence
    + web

This is just an example. It is quite formal. For example it defines 2 interfaces for feature1. Normally that is not required, but could be a good idea if used differently by different people. You may let the internal API extend the public.

I do not like the 'impl' or 'support' names, but they help separate the less important stuff from the important (domain and API). When it comes to naming I like to be as concrete as possible. If you have a package called 'utils' with 20 classes, move StringUtils to support/string, HttpUtil to support/http and so on.

Any way to exit bash script, but not quitting the terminal

You can add an extra exit command after the return statement/command so that it works for both, executing the script from the command line and sourcing from the terminal.

Example exit code in the script:

   if [ $# -lt 2 ]; then
     echo "Needs at least two arguments"
     return 1 2>/dev/null
     exit 1
   fi

The line with the exit command will not be called when you source the script after the return command.

When you execute the script, return command gives an error. So, we suppress the error message by forwarding it to /dev/null.

How do I get the max ID with Linq to Entity?

In case if you are using the async and await feature, it would be as follows:

User currentUser = await db.Users.OrderByDescending(u => u.UserId).FirstOrDefaultAsync();

jQuery Scroll to bottom of page/iframe

The scripts mentioned in previous answers, like:

$("body, html").animate({
    scrollTop: $(document).height()
}, 400)

or

$(window).scrollTop($(document).height());

will not work in Chrome and will be jumpy in Safari in case html tag in CSS has overflow: auto; property set. It took me nearly an hour to figure out.

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

is there a function in lodash to replace matched item

Seems like the simplest solution would to use ES6's .map or lodash's _.map:

var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];

// lodash
var newArr = _.map(arr, function(a) {
  return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});

// ES6
var newArr = arr.map(function(a) {
  return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});

This has the nice effect of avoiding mutating the original array.

Difference between Date(dateString) and new Date(dateString)

You're not getting an "invalid date" error. Rather, the value of temp is "Invalid Date".

Is your date string in a valid format? If you're using Firefox, check Date.parse

In Firefox javascript console:

>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000

I would try a different date string format.

Zebi, are you using Internet Explorer?

Stacking DIVs on top of each other?

You can now use CSS Grid to fix this.

<div class="outer">
  <div class="top"> </div>
  <div class="below"> </div>
</div>

And the css for this:

.outer {
  display: grid;
  grid-template: 1fr / 1fr;
  place-items: center;
}
.outer > * {
  grid-column: 1 / 1;
  grid-row: 1 / 1;
}
.outer .below {
  z-index: 2;
}
.outer .top {
  z-index: 1;
}

VHDL - How should I create a clock in a testbench?

If multiple clock are generated with different frequencies, then clock generation can be simplified if a procedure is called as concurrent procedure call. The time resolution issue, mentioned by Martin Thompson, may be mitigated a little by using different high and low time in the procedure. The test bench with procedure for clock generation is:

library ieee;
use ieee.std_logic_1164.all;

entity tb is
end entity;

architecture sim of tb is

  -- Procedure for clock generation
  procedure clk_gen(signal clk : out std_logic; constant FREQ : real) is
    constant PERIOD    : time := 1 sec / FREQ;        -- Full period
    constant HIGH_TIME : time := PERIOD / 2;          -- High time
    constant LOW_TIME  : time := PERIOD - HIGH_TIME;  -- Low time; always >= HIGH_TIME
  begin
    -- Check the arguments
    assert (HIGH_TIME /= 0 fs) report "clk_plain: High time is zero; time resolution to large for frequency" severity FAILURE;
    -- Generate a clock cycle
    loop
      clk <= '1';
      wait for HIGH_TIME;
      clk <= '0';
      wait for LOW_TIME;
    end loop;
  end procedure;

  -- Clock frequency and signal
  signal clk_166 : std_logic;
  signal clk_125 : std_logic;

begin

  -- Clock generation with concurrent procedure call
  clk_gen(clk_166, 166.667E6);  -- 166.667 MHz clock
  clk_gen(clk_125, 125.000E6);  -- 125.000 MHz clock

  -- Time resolution show
  assert FALSE report "Time resolution: " & time'image(time'succ(0 fs)) severity NOTE;

end architecture;

The time resolution is printed on the terminal for information, using the concurrent assert last in the test bench.

If the clk_gen procedure is placed in a separate package, then reuse from test bench to test bench becomes straight forward.

Waveform for clocks are shown in figure below.

Waveforms for clk_166 and clk_125

An more advanced clock generator can also be created in the procedure, which can adjust the period over time to match the requested frequency despite the limitation by time resolution. This is shown here:

-- Advanced procedure for clock generation, with period adjust to match frequency over time, and run control by signal
procedure clk_gen(signal clk : out std_logic; constant FREQ : real; PHASE : time := 0 fs; signal run : std_logic) is
  constant HIGH_TIME   : time := 0.5 sec / FREQ;  -- High time as fixed value
  variable low_time_v  : time;                    -- Low time calculated per cycle; always >= HIGH_TIME
  variable cycles_v    : real := 0.0;             -- Number of cycles
  variable freq_time_v : time := 0 fs;            -- Time used for generation of cycles
begin
  -- Check the arguments
  assert (HIGH_TIME /= 0 fs) report "clk_gen: High time is zero; time resolution to large for frequency" severity FAILURE;
  -- Initial phase shift
  clk <= '0';
  wait for PHASE;
  -- Generate cycles
  loop
    -- Only high pulse if run is '1' or 'H'
    if (run = '1') or (run = 'H') then
      clk <= run;
    end if;
    wait for HIGH_TIME;
    -- Low part of cycle
    clk <= '0';
    low_time_v := 1 sec * ((cycles_v + 1.0) / FREQ) - freq_time_v - HIGH_TIME;  -- + 1.0 for cycle after current
    wait for low_time_v;
    -- Cycle counter and time passed update
    cycles_v := cycles_v + 1.0;
    freq_time_v := freq_time_v + HIGH_TIME + low_time_v;
  end loop;
end procedure;

Again reuse through a package will be nice.

Can I scroll a ScrollView programmatically in Android?

**to scroll up to desired height. I have come up with some good solution **

                scrollView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.scrollBy(0, childView.getHeight());
                    }
                }, 100);

How to Extract Year from DATE in POSTGRESQL

you can also use just like this in newer version of sql,

select year('2001-02-16 20:38:40') as year,
month('2001-02-16 20:38:40') as month,
day('2001-02-16 20:38:40') as day,
hour('2001-02-16 20:38:40') as hour,
minute('2001-02-16 20:38:40') as minute

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )

The dump itself will be faster. (for what I tested it was double as fast)

Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.

So I would go for "&& gzip" instead of "| gzip"

Important: check for free disk space first with df -h since you will need more then piping | gzip.

mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

-> which will also result in 1 file called dumpfilename.sql.gz

Furthermore the option --single-transaction prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here

mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

Django - limiting query results

Yes. If you want to fetch a limited subset of objects, you can with the below code:

Example:

obj=emp.objects.all()[0:10]

The beginning 0 is optional, so

obj=emp.objects.all()[:10]

The above code returns the first 10 instances.

$watch an object

As you are looking for form object changes, the best watching approach is to use
$watchCollection. Please have a look into official documentation for different performance characteristics.

How to list files and folder in a dir (PHP)

You can use:

 foreach (new DirectoryIterator("./system/information/") as $fn) {
     print $fn->getFilename();
 }

You'll have to use it twice for each subdir, Players and User.

Is it possible to decompile a compiled .pyc file into a .py file?

Install using pip install pycompyle6

pycompyle6 filename.pyc

Can I change the name of `nohup.out`?

As the file handlers points to i-nodes (which are stored independently from file names) on Linux/Unix systems You can rename the default nohup.out to any other filename any time after starting nohup something&. So also one could do the following:

$ nohup something&
$ mv nohup.out nohup2.out
$ nohup something2&

Now something adds lines to nohup2.out and something2 to nohup.out.

Javascript Equivalent to C# LINQ Select

Had to merge this nice answers. It revealed something like that;

Extension;

 Array.prototype.where = function (filter) {

                                var collection = this;

                                switch (typeof filter) {

                                    case 'function':
                                        return $.grep(collection, filter);

                                    case 'object':
                                        for (var property in filter) {
                                            if (!filter.hasOwnProperty(property))
                                                continue; // ignore inherited properties

                                            collection = $.grep(collection, function (item) {
                                                return item[property] === filter[property];
                                            });
                                        }
                                        return collection.slice(0); // copy the array 
                                    // (in case of empty object filter)

                                    default:
                                        throw new TypeError('func must be either a' +
                                            'function or an object of properties and values to filter by');
                                }
                            };

Usage;



masterTableView.get_dataItems().where(function (t) {
if (t.findElement("_invoiceGridCheckbox").checked) {
    invoiceIds.push(t.getDataKeyValue("Id"));
  }
});

Difference in months between two dates

It seems that the DateTimeSpan solution pleases a lot of people. I don't know. Let's consider the:

BeginDate = 1972/2/29 EndDate = 1972/4/28.

The DateTimeSpan based answer is:

1 year(s), 2 month(s) and 0 day(s)

I implemented a method and based on that the answer is:

1 year(s), 1 month(s) and 28 day(s)

Clearly there are not 2 full months there. I would say that because we are at the end of the month of the begin date what's left is actually the full month of March plus the number of days passed in the month of the end date (April), so 1 month and 28 days.

If you read so far and you are intrigued I posted the method below. I am explaining in the comments the assumptions I make because how many months, the concept of months is such a moving target. Test it many times and see if the answers make sense. I usually choose test dates in adjacent years and once I verify an answer I move a day or two back and forth. So far it looks good, I'm sure you'll find some bugs :D. The code might look a bit rough but I hope it is clear enough:

static void Main(string[] args) {
        DateTime EndDate = new DateTime(1973, 4, 28);
        DateTime BeginDate = new DateTime(1972, 2, 29);
        int years, months, days;
        GetYearsMonthsDays(EndDate, BeginDate, out years, out months, out days);
        Console.WriteLine($"{years} year(s), {months} month(s) and {days} day(s)");
    }

    /// <summary>
    /// Calculates how many years, months and days are between two dates.
    /// </summary>
    /// <remarks>
    /// The fundamental idea here is that most of the time all of us agree
    /// that a month has passed today since the same day of the previous month.
    /// A particular case is when both days are the last days of their respective months 
    /// when again we can say one month has passed.
    /// In the following cases the idea of a month is a moving target.
    /// - When only the beginning date is the last day of the month then we're left just with 
    /// a number of days from the next month equal to the day of the month that end date represent
    /// - When only the end date is the last day of its respective month we clearly have a 
    /// whole month plus a few days after the the day of the beginning date until the end of its
    /// respective months
    /// In all the other cases we'll check
    /// - beginingDay > endDay -> less then a month just daysToEndofBeginingMonth + dayofTheEndMonth
    /// - beginingDay < endDay -> full month + (endDay - beginingDay)
    /// - beginingDay == endDay -> one full month 0 days
    /// 
    /// </remarks>
    /// 
    private static void GetYearsMonthsDays(DateTime EndDate, DateTime BeginDate, out int years, out int months, out int days ) {
        var beginMonthDays = DateTime.DaysInMonth(BeginDate.Year, BeginDate.Month);
        var endMonthDays = DateTime.DaysInMonth(EndDate.Year, EndDate.Month);
        // get the full years
        years = EndDate.Year - BeginDate.Year - 1;
        // how many full months in the first year
        var firstYearMonths = 12 - BeginDate.Month;
        // how many full months in the last year
        var endYearMonths = EndDate.Month - 1;
        // full months
        months = firstYearMonths + endYearMonths;           
        days = 0;
        // Particular end of month cases
        if(beginMonthDays == BeginDate.Day && endMonthDays == EndDate.Day) {
            months++;
        }
        else if(beginMonthDays == BeginDate.Day) {
            days += EndDate.Day;
        }
        else if(endMonthDays == EndDate.Day) {
            days += beginMonthDays - BeginDate.Day;
        }
        // For all the other cases
        else if(EndDate.Day > BeginDate.Day) {
            months++;
            days += EndDate.Day - BeginDate.Day;
        }
        else if(EndDate.Day < BeginDate.Day) {                
            days += beginMonthDays - BeginDate.Day;
            days += EndDate.Day;
        }
        else {
            months++;
        }
        if(months >= 12) {
            years++;
            months = months - 12;
        }
    }

Set variable in jinja

Just Set it up like this

{% set active_link = recordtype -%}

Adjust list style image position?

I normally hide the list-style-type and use a background image, which is moveable

li 
{
    background: url(/Images/arrow_icon.gif) no-repeat 7px 7px transparent;
    list-style-type: none;
    margin: 0;
    padding: 0px 0px 1px 24px;
    vertical-align: middle;
}

The "7px 7px" is what aligns the background image inside the element and is also relative to the padding.

Split column at delimiter in data frame

Hadley has a very elegant solution to do this inside data frames in his reshape package, using the function colsplit.

require(reshape)
> df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
> df
  ID FOO
1 11 a|b
2 12 b|c
3 13 x|y
> df = transform(df, FOO = colsplit(FOO, split = "\\|", names = c('a', 'b')))
> df
  ID FOO.a FOO.b
1 11     a     b
2 12     b     c
3 13     x     y

Re-render React component when prop changes

You could use KEY unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.

jQuery.ajax returns 400 Bad Request

I was getting the 400 Bad Request error, even after setting:

contentType: "application/json",
dataType: "json"

The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

This was my initial code:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

Now after making the request, I checked the console tab in the browser development tool.
It looked like this: enter image description here

responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

Changing the data object creation like below fixed the issue for me:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

I assume other possible errors could also be identified by logging and inspecting the error object.

HTML img scaling

Only set the width or height, and it will scale the other automatically. And yes you can use a percentage.

The first part can be done, but requires JavaScript, so might not work for all users.

android:drawableLeft margin and/or padding

just remake from:

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

    <corners android:radius="40dp"/>

    <solid android:color="@android:color/white"/>

</shape>

to

<layer-list
        xmlns:android="http://schemas.android.com/apk/res/android">
    <item
            android:right="@dimen/_2dp"
            android:left="@dimen/_2dp"
            android:bottom="@dimen/_2dp"
            android:top="@dimen/_2dp"
            >
        <shape
                xmlns:android="http://schemas.android.com/apk/res/android">

            <corners android:radius="40dp"/>

            <solid android:color="@android:color/white"/>

        </shape>
    </item>

</layer-list>

Eclipse change project files location

You can copy your .classpath and .project files to the root of the new project directory and then choose 'Import...' from the file menu, and select 'General/Existing Projects into Workspace.' In the resulting dialog, locate the root of the new project directory and finish. Make sure that you have deleted the old project from the work space before importing.

How can I calculate an md5 checksum of a directory?

Checksum all files, including both content and their filenames

grep -ar -e . /your/dir | md5sum | cut -c-32

Same as above, but only including *.py files

grep -ar -e . --include="*.py" /your/dir | md5sum | cut -c-32

You can also follow symlinks if you want

grep -aR -e . /your/dir | md5sum | cut -c-32

Other options you could consider using with grep

-s, --no-messages         suppress error messages
-D, --devices=ACTION      how to handle devices, FIFOs and sockets;
-Z, --null                print 0 byte after FILE name
-U, --binary              do not strip CR characters at EOL (MSDOS/Windows)

TypeError: ObjectId('') is not JSON serializable

in my case I needed something like this:

class JsonEncoder():
    def encode(self, o):
        if '_id' in o:
            o['_id'] = str(o['_id'])
        return o

How to get current html page title with javascript

$('title').text();

returns all the title

but if you just want the page title then use

document.title

Using SQL LOADER in Oracle to import CSV file

LOAD DATA INFILE 'D:\CertificationInputFile.csv' INTO TABLE CERT_EXCLUSION_LIST FIELDS TERMINATED BY "|" OPTIONALLY ENCLOSED BY '"' ( CERTIFICATIONNAME, CERTIFICATIONVERSION )

How to delete a cookie using jQuery?

What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.

Rails migration for change column

I think this should work.

change_column :table_name, :column_name, :date

Check if string contains only letters in javascript

You need

/^[a-zA-Z]+$/

Currently, you are matching a single character at the start of the input. If your goal is to match letter characters (one or more) from start to finish, then you need to repeat the a-z character match (using +) and specify that you want to match all the way to the end (via $)

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

Quickest way to convert XML to JSON in Java

I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.

How to handle notification when app in background in Firebase

To make firebase library to call your onMessageReceived() in the following cases

  1. App in foreground
  2. App in background
  3. App has been killed

you must not put JSON key 'notification' in your request to firebase API but instead use 'data', see below.

The following message will not call your onMessageReceived() when your app is in the background or killed, and you can't customize your notification.

{
   "to": "/topics/journal",
   "notification": {
       "title" : "title",
       "text": "data!",
       "icon": "ic_notification"
    }
}

but instead using this will work

{
  "to": "/topics/dev_journal",
   "data": {
       "text":"text",
       "title":"",
       "line1":"Journal",
       "line2":"??"
   }
} 

Basically, the message is sent in the argument RemoteMessage along with your data object as Map<String, String>, then you can manage the notification in onMessageReceived as in the snippet here

@Override
public void onMessageReceived(RemoteMessage remoteMessage) { 
     Map<String, String> data = remoteMessage.getData();

     //you can get your text message here.
     String text= data.get("text");


     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        // optional, this is to make beautiful icon
             .setLargeIcon(BitmapFactory.decodeResource(
                                    getResources(), R.mipmap.ic_launcher))  
        .setSmallIcon(smallIcon)  //mandatory
      .......
    /*You can read more on notification here:
    https://developer.android.com/training/notify-user/build-notification.html
    https://www.youtube.com/watch?v=-iog_fmm6mE
    */
}

What is the point of "final class" in Java?

Android Looper class is a good practical example of this. http://developer.android.com/reference/android/os/Looper.html

The Looper class provides certain functionality which is NOT intended to be overridden by any other class. Hence, no sub-class here.

How to print SQL statement in codeigniter model

You can use this:

$this->db->last_query();

"Returns the last query that was run (the query string, not the result)."

Reff: https://www.codeigniter.com/userguide3/database/helpers.html

Can you nest html forms?

You can also use formaction="" inside the button tag.

<button type="submit" formaction="/rmDog" method='post' id="rmDog">-</button>

This would be nested in the original form as a separate button.

How to enter special characters like "&" in oracle database?

You can either use the backslash character to escape a single character or symbol

'Java_22 \& Oracle_14'

or braces to escape a string of characters or symbols

'{Java_22 & Oracle_14}'

wamp server mysql user id and password

Use http://localhost/sqlbuddy --> users interface.

You can find it at the localhost main page at Your Aliases section.

Tkinter module not found on Ubuntu

I had the same problem. I tried to use:

sudo apt-get install python3-tk

It gave an error stating blt(>=2.4z-7) is not present and is not installable.

I went here and manually installed it. (For Ubuntu 14.04)

Then I used apt again and it worked.

I concluded that python3.4 in Ubuntu didn't come with the .so file required to carry on installation. And blt was required to download it.

How to convert a number to string and vice versa in C++

Update for C++11

As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).

string to numeric

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).

If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.

Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.

Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.

numeric to string

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.

As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.

There are also similar functions defined that are named to_wstring, these will return a std::wstring.

Redirect from a view to another view

Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToAction method for this.

How to compare dates in datetime fields in Postgresql?

Use Date convert to compare with date: Try This:

select * from table 
where TO_DATE(to_char(timespanColumn,'YYYY-MM-DD'),'YYYY-MM-DD') = to_timestamp('2018-03-26', 'YYYY-MM-DD')

Javascript format date / time

I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.

function formatDate(date) {
    var year = date.getFullYear(),
        month = date.getMonth() + 1, // months are zero indexed
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
        minuteFormatted = minute < 10 ? "0" + minute : minute,
        morning = hour < 12 ? "am" : "pm";

    return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
            minuteFormatted + morning;
}

How to only find files in a given directory, and ignore subdirectories using bash

find /dev -maxdepth 1 -name 'abc-*'

Does not work for me. It return nothing. If I just do '.' it gives me all the files in directory below the one I'm working in on.

find /dev -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls

Return nothing with '.' instead I get list of all 'big' files in my directory as well as the rootfiles/ directory where I store old ones.

Continuing. This works.

find ./ -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls
564751   71 -rw-r--r--   1 snyder   bfactory   115739 May 21 12:39 ./R24eTightPiPi771052-55.root
565197  105 -rw-r--r--   1 snyder   bfactory   150719 May 21 14:27 ./R24eTightPiPi771106-2.root
565023   94 -rw-r--r--   1 snyder   bfactory   134180 May 21 12:59 ./R24eTightPiPi77999-109.root
719678   82 -rw-r--r--   1 snyder   bfactory   121149 May 21 12:42 ./R24eTightPiPi771098-10.root
564029  140 -rw-r--r--   1 snyder   bfactory   170181 May 21 14:14 ./combo77v.root

Apparently /dev means directory of interest. But ./ is needed, not just .. The need for the / was not obvious even after I figured out what /dev meant more or less.

I couldn't respond as a comment because I have no 'reputation'.

How to filter object array based on attributes?

I'm surprised no one has posted the one-line response:

const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

...and just so you can read it easier:

const filteredHomes = json.homes.filter( x => 
  x.price <= 1000 && 
  x.sqft >= 500 && 
  x.num_of_beds >=2 && 
  x.num_of_baths >= 2.5
);

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

ng: command not found while creating new project using angular-cli

soluton for windows operating system only....... first step:

install nodejs version: nodev 8.1.2

second step: set up environment variable like: C:\ProgramFiles\nodejs

Third step: install angular use this command: npm install -g @angular/cli

after installation whereever you have to create project like: ng new first-project......

Check if string contains \n Java

For portability, you really should do something like this:

public static final String NEW_LINE = System.getProperty("line.separator")
.
.
.
word.contains(NEW_LINE);

unless you're absolutely certain that "\n" is what you want.

Symfony - generate url with parameter in controller

Get the router from the container.

$router = $this->get('router');

Then use the router to generate the Url

$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

 android:theme="@style/Theme.AppCompat"

or each kind of AppCompat theme!

What is the difference between rb and r+b modes in file objects

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Source: Reading and Writing Files

Python equivalent to 'hold on' in Matlab

You can use the following:

plt.hold(True)

How to use ESLint with Jest

You can also set the test env in your test file as follows:

/* eslint-env jest */

describe(() => {
  /* ... */
})

How to get the list of all database users

I try to avoid using the "SELECT * " option and just pull what data I want or need. The code below is what I use, you may cull out or add columns and aliases per your needs.

I also us "IIF" (instant if) to replace binary 0 or 1 with a yes or no. It just makes it easier to read for the non-techie that may want this info.

Here is what I use:

SELECT 
    name AS 'User'
  , PRINCIPAL_ID
  , type AS 'User Type'
  , type_desc AS 'Login Type'
  , CAST(create_date AS DATE) AS 'Date Created' 
  , default_database_name AS 'Database Name'
  , IIF(is_fixed_role LIKE 0, 'No', 'Yes') AS 'Is Active'
FROM master.sys.server_principals
WHERE type LIKE 's' OR type LIKE 'u'
ORDER BY [User], [Database Name]; 
GO

Hope this helps.

Add space between cells (td) using css

Consider using cellspacing and cellpadding attributes for table tag or border-spacing css property.

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

execute this query before restoring database:

alter database [YourDBName] 
set offline with rollback immediate

and this one after restoring:

  alter database [YourDBName] 
  set online

Spring Boot - Cannot determine embedded database driver class for database type NONE

Spring boot will look for datasoure properties in application.properties file.

Please define it in application.properties or yml file

application.properties

spring.datasource.url=xxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=xxx

If you need your own configuration you could set your own profile and use the datasource values while bean creation.

<> And Not In VB.NET

I think your question boils down to "the difference between (Is and =) and also (IsNot and <>)".

The answer in both cases is the same :

= and <> are implicitly defined for value types and you can explicitly define them for your types.

Is and IsNot are designed for comparisons between reference types to check if the two references refer to the same object.

In your example, you are comparing a string object to Nothing (Null) and since the =/<> operators are defined for strings, the first example works. However, it does not work when a Null is encountered because Strings are reference types and can be Null. The better way (as you guessed) is the latter version using Is/IsNot.

How do I programmatically set device orientation in iOS 7?

If you want only portrait mode, in iOS 9 (Xcode 7) you can:

  • Going to Info.plist
  • Select "Supported interface orientations" item
  • Delete "Landscape(left home button)" and "Landscape(right home button)"

enter image description here

How to read barcodes with the camera on Android?

module app:

implementation 'com.google.zxing:core:3.2.1'

implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'

AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button BarCode;

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

        BarCode = findViewById(R.id.button_barcode);
        final Activity activity = this;

        BarCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
                intentIntegrator.setDesiredBarcodeFormats(intentIntegrator.ALL_CODE_TYPES);
                intentIntegrator.setBeepEnabled(false);
                intentIntegrator.setCameraId(0);
                intentIntegrator.setPrompt("SCAN");
                intentIntegrator.setBarcodeImageEnabled(false);
                intentIntegrator.initiateScan();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        IntentResult Result = IntentIntegrator.parseActivityResult(requestCode , resultCode ,data);
        if(Result != null){
            if(Result.getContents() == null){
                Log.d("MainActivity" , "cancelled scan");
                Toast.makeText(this, "cancelled", Toast.LENGTH_SHORT).show();
            }
            else {
                Log.d("MainActivity" , "Scanned");
                Toast.makeText(this,"Scanned -> " + Result.getContents(), Toast.LENGTH_SHORT).show();
            }
        }
        else {
            super.onActivityResult(requestCode , resultCode , data);
        }
    }
}

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

instanceof Vs getClass( )

The reason that the performance of instanceof and getClass() == ... is different is that they are doing different things.

  • instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.

  • getClass() == ... tests whether the types are identical.

So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.

Is using the instanceOf operator bad practice ?

Not necessarily. Overuse of either instanceOf or getClass() may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.

However, there are cases where these are NOT "design smell". For example, in equals(Object) you need to test the actual type of the argument, and return false if it doesn't match. This is best done using getClass().


Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices if they haven't already done so.

Bash integer comparison

The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1.

(("$#" < 1)) && ( (("$1" != 1)) ||  (("$1" -ne 0q)) )

Your boolean logic is also a bit confused:

(( "$#" < 1 && # If the number of arguments is less than one…
  "$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?

This is probably what you want:

(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1

What is href="#" and why is it used?

Unfortunately, the most common use of <a href="#"> is by lazy programmers who want clickable non-hyperlink javascript-coded elements that behave like anchors, but they can't be arsed to add cursor: pointer; or :hover styles to a class for their non-hyperlink elements, and are additionally too lazy to set href to javascript:void(0);.

The problem with this is that one <a href="#" onclick="some_function();"> or another inevitably ends up with a javascript error, and an anchor with an onclick javascript error always ends up following its href. Normally this ends up being an annoying jump to the top of the page, but in the case of sites using <base>, <a href="#"> is handled as <a href="[base href]/#">, resulting in an unexpected navigation. If any logable errors are being generated, you won't see them in the latter case unless you enable persistent logs.

If an anchor element is used as a non-anchor it should have its href set to javascript:void(0); for the sake of graceful degradation.

I just wasted two days debugging a random unexpected page redirect that should have simply refreshed the page, and finally tracked it down to a function raising the click event of an <a href="#">. Replacing the # with javascript:void(0); fixed it.

The first thing I'm doing Monday is purging the project of all instances of <a href="#">.

docker container ssl certificates

You can use relative path to mount the volume to container:

docker run -v `pwd`/certs:/container/path/to/certs ...

Note the back tick on the pwd which give you the present working directory. It assumes you have the certs folder in current directory that the docker run is executed. Kinda great for local development and keep the certs folder visible to your project.

Can I set subject/content of email using mailto:?

The mailto: URL scheme is defined in RFC 2368. Also, the convention for encoding information into URLs and URIs is defined in RFC 1738 and then RFC 3986. These prescribe how to include the body and subject headers into a URL (URI):

mailto:[email protected]?subject=current-issue&body=send%20current-issue

Specifically, you must percent-encode the email address, subject, and body and put them into the format above. Percent-encoded text is legal for use in HTML, however this URL must be entity encoded for use in an href attribute, according to the HTML4 standard:

<a href="mailto:[email protected]?subject=current-issue&amp;body=send%20current-issue">Send email</a>

And most generally, here is a simple PHP script that encodes per the above.

<?php
$encodedTo = rawurlencode($message->to);
$encodedSubject = rawurlencode($message->subject);
$encodedBody = rawurlencode($message->body);
$uri = "mailto:$encodedTo?subject=$encodedSubject&body=$encodedBody";
$encodedUri = htmlspecialchars($uri);
echo "<a href=\"$encodedUri\">Send email</a>";
?>

how to align img inside the div to the right?

<p>
  <img style="float: right; margin: 0px 15px 15px 0px;" src="files/styles/large_hero_desktop_1x/public/headers/Kids%20on%20iPad%20 %202400x880.jpg?itok=PFa-MXyQ" width="100" />
  Nunc pulvinar lacus id purus ultrices id sagittis neque convallis. Nunc vel libero orci. 
  <br style="clear: both;" />
</p>

PDOException SQLSTATE[HY000] [2002] No such file or directory

This happened to me because MySQL wasn't running. MySQL was failing to start because I had a missing /usr/local/etc/my.cnf.d/ directory.

This was being required by my /usr/local/etc/my.cnf config file as a glob include (include /usr/local/etc/my.cnf.d/*.cnf).

Running mkdir /usr/local/etc/my.cnf.d, and then starting MySQL, fixed the issue.

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

how i solve it in Eclipse

  1. go to the properties of the project enter image description here

  2. go to Java compiler enter image description here

  3. change in the Compiler complicated level to java that my project work with (java 11 in my project) you can see that it your java that you work when the last message disappear

  4. Apply enter image description here

Can I use an image from my local file system as background in HTML?

It seems you can provide just the local image name, assuming it is in the same folder...

It suffices like:

background-image: url("img1.png")

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

In my case it happened after I converted the whole solution (using an extension called Target Framework Migrator) to 4.6.2 but ended up undoing the changes and going back to 3.5 (solution is versioned by TFS). To solve this, I converted just the problematic project (which was using IIS Express to run) to 4.6.2 and then back to 3.5.

Combine several images horizontally with Python

Here's my solution:

from PIL import Image


def join_images(*rows, bg_color=(0, 0, 0, 0), alignment=(0.5, 0.5)):
    rows = [
        [image.convert('RGBA') for image in row]
        for row
        in rows
    ]

    heights = [
        max(image.height for image in row)
        for row
        in rows
    ]

    widths = [
        max(image.width for image in column)
        for column
        in zip(*rows)
    ]

    tmp = Image.new(
        'RGBA',
        size=(sum(widths), sum(heights)),
        color=bg_color
    )

    for i, row in enumerate(rows):
        for j, image in enumerate(row):
            y = sum(heights[:i]) + int((heights[i] - image.height) * alignment[1])
            x = sum(widths[:j]) + int((widths[j] - image.width) * alignment[0])
            tmp.paste(image, (x, y))

    return tmp


def join_images_horizontally(*row, bg_color=(0, 0, 0), alignment=(0.5, 0.5)):
    return join_images(
        row,
        bg_color=bg_color,
        alignment=alignment
    )


def join_images_vertically(*column, bg_color=(0, 0, 0), alignment=(0.5, 0.5)):
    return join_images(
        *[[image] for image in column],
        bg_color=bg_color,
        alignment=alignment
    )

For these images:

images = [
    [Image.open('banana.png'), Image.open('apple.png')],
    [Image.open('lime.png'), Image.open('lemon.png')],
]

Results will look like:


join_images(
    *images,
    bg_color='green',
    alignment=(0.5, 0.5)
).show()

enter image description here


join_images(
    *images,
    bg_color='green',
    alignment=(0, 0)

).show()

enter image description here


join_images(
    *images,
    bg_color='green',
    alignment=(1, 1)
).show()

enter image description here

JavaScript code for getting the selected value from a combo box

It probably is the # sign like tho others have mentioned because this appears to work just fine.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

</head>
<body>

    <select id="#ticket_category_clone">
  <option value="hw">Hardware</option>
  <option>fsdf</option>
  <option>sfsd</option>
  <option>sdfs</option>
</select>
<script type="text/javascript">
    (function check() {
        var e = document.getElementById("#ticket_category_clone");
        var str = e.options[e.selectedIndex].text;

        alert(str);
        if (str === "Hardware") { 
            alert('Hi'); 
        }


    })();
</script>
</body>

Task continuation on UI thread

With async you just do:

await Task.Run(() => do some stuff);
// continue doing stuff on the same context as before.
// while it is the default it is nice to be explicit about it with:
await Task.Run(() => do some stuff).ConfigureAwait(true);

However:

await Task.Run(() => do some stuff).ConfigureAwait(false);
// continue doing stuff on the same thread as the task finished on.

What is the best way to seed a database in Rails?

Using seeds.rb file or FactoryBot is great, but these are respectively great for fixed data structures and testing.

The seedbank gem might give you more control and modularity to your seeds. It inserts rake tasks and you can also define dependencies between your seeds. Your rake task list will have these additions (e.g.):

rake db:seed                    # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/ENVIRONMENT/*.seeds.rb. ENVIRONMENT is the current environment in Rails.env.
rake db:seed:bar                # Load the seed data from db/seeds/bar.seeds.rb
rake db:seed:common             # Load the seed data from db/seeds.rb and db/seeds/*.seeds.rb.
rake db:seed:development        # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/development/*.seeds.rb.
rake db:seed:development:users  # Load the seed data from db/seeds/development/users.seeds.rb
rake db:seed:foo                # Load the seed data from db/seeds/foo.seeds.rb
rake db:seed:original           # Load the seed data from db/seeds.rb

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.

How can I specify the default JVM arguments for programs I run from eclipse?

As far as I know there is no option to create global configuration for java applications. You always create a duplicate of the configuration.

enter image description here

Also, if you are using PDE (for plugin development), you can create target platform using windows -> Preferences -> Plug-in development -> Target Platform. Edit has options for program/vm arguments.

Hope this helps

How can I define fieldset border color?

It does appear red on Firefox and IE 8. But perhaps you need to change the border-style too.

_x000D_
_x000D_
.field_set{_x000D_
  border-color: #F00;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<fieldset class="field_set">_x000D_
  <legend>box</legend>_x000D_
  <table width="100%" border="0" cellspacing="0" cellpadding="0">_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

alt text

Codeigniter : calling a method of one controller from other

very simple in first controllr call

 $this->load->model('MyController');
 $this->MyController->test();

place file MyController.php to /model patch

MyController.php should be contain

class MyController extends CI_Model {

    function __construct() {
        parent::__construct();
    }
    function test()
    {
        echo 'OK';
    }
}

How do I get an apk file from an Android device?

I've seen that many solutions to this problem either you have to root your phone or you have to install an app. Then after much googling I got this solution for non rooted/rooted phones.

To list which apps you got so far.

adb shell pm list packages

Then you may select an app, for instance twitter

adb backup -apk com.twitter.android

An important thing here is to not set up a password for encrypt your backup

This is going to create a file named as backup.ap, but you still can't open it. For this you got to extract it again but using the dd command.

dd if=backup.ab bs=24 skip=1 | openssl zlib -d > backup.tar

After this all you have to do is to extract the tar content and it's done.

Hope it works for you guys

How to increase the gap between text and underlining in CSS

What I use:

<span style="border-bottom: 1px solid black"> Enter text here </span>

Get skin path in Magento?

The way that Magento themes handle actual url's is as such (in view partials - phtml files):

echo $this->getSkinUrl('images/logo.png');

If you need the actual base path on disk to the image directory use:

echo Mage::getBaseDir('skin');

Some more base directory types are available in this great blog post:

http://alanstorm.com/magento_base_directories

css transform, jagged edges in chrome

Adding a 1px transparent border will trigger anti-aliasing

outline: 1px solid transparent;

Alternatively, add a 1px transparent box-shadow.

box-shadow: 0 0 1px rgba(255,255,255,0);

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

What is __declspec and when do I need to use it?

I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec() can bee used at the same level as the export keyword.

/** Declare a public MRuby API function. */
#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I got the same error because I was trying to run my program without starting mysql server.

After starting the mysql server, everything went right.

jQuery find file extension (from string)

Yet another way to write it up:

function getExtension(filename) {
    return filename.split('.').pop().toLowerCase();
}

function openFile(file) { 
    switch(getExtension(file)) {
        //if .jpg/.gif/.png do something
        case 'jpg': case 'gif': case 'png':
            /* handle */
            break;
        //if .zip/.rar do something else
        case 'zip': case 'rar':
            /* handle */
            break;

        //if .pdf do something else
        case 'pdf':
            /* handle */
            break;
    }
}

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.

  • Even worse, while the delete cascade is going on, the tables involved are locked so those tables (and potentially your whole database) is unusable.
  • Still worse, it's hard to get postgres to tell you what it's doing during the delete cascade. If it's taking a long time, which table or tables is making it slow? Perhaps it's somewhere in the pg_stats information? It's hard to tell.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

How to install pip for Python 3 on Mac OS X?

  1. brew install python3
  2. create alias in your shell profile

    • eg. alias pip3="python3 -m pip" in my .zshrc

? ~ pip3 --version

pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

How to check if a string starts with "_" in PHP?

To build on pinusnegra's answer, and in response to Gumbo's comment on that answer:

function has_leading_underscore($string) {

    return $string[0] === '_';

}

Running on PHP 5.3.0, the following works and returns the expected value, even without checking if the string is at least 1 character in length:

echo has_leading_underscore('_somestring').', ';
echo has_leading_underscore('somestring').', ';
echo has_leading_underscore('').', ';
echo has_leading_underscore(null).', ';
echo has_leading_underscore(false).', ';
echo has_leading_underscore(0).', ';
echo has_leading_underscore(array('_foo', 'bar'));

/*
 * output: true, false, false, false, false, false, false
 */

I don't know how other versions of PHP will react, but if they all work, then this method is probably more efficient than the substr route.

Difference between spring @Controller and @RestController annotation

@RestController annotated classes are the same as @Controller but the @ResponseBody on the handler methods are implied.

Insert Data Into Temp Table with Query

Personally, I needed a little hand holding figuring out how to use this and it is really, awesome.

IF(OBJECT_ID('tempdb..#TEMP') IS NOT NULL) BEGIN DROP TABLE #TEMP END
        SELECT *
            INTO #TEMP
            FROM (
            The query you want to use many times
            ) AS X

SELECT * FROM #TEMP WHERE THIS = THAT
SELECT * FROM #TEMP WHERE THIS <> THAT
SELECT COL1,COL3 FROM #TEMP WHERE THIS > THAT

DROP TABLE #TEMP

Nullable types: better way to check for null or zero in c#

This is really just an expansion of Freddy Rios' accepted answer only using Generics.

public static bool IsNullOrDefault<T>(this Nullable<T> value) where T : struct
{
    return default(T).Equals( value.GetValueOrDefault() );
}

public static bool IsValue<T>(this Nullable<T> value, T valueToCheck) where T : struct
{
    return valueToCheck.Equals((value ?? valueToCheck));
}

NOTE we don't need to check default(T) for null since we are dealing with either value types or structs! This also means we can safely assume T valueToCheck will not be null; Remember here that T? is shorthand Nullable<T> so by adding the extension to Nullable<T> we get the method in int?, double?, bool? etc.

Examples:

double? x = null;
x.IsNullOrDefault(); //true

int? y = 3;
y.IsNullOrDefault(); //false

bool? z = false;
z.IsNullOrDefault(); //true

Sorting using Comparator- Descending order (User defined classes)

I would create a comparator for the person class that can be parametrized with a certain sorting behaviour. Here I can set the sorting order but it can be modified to allow sorting for other person attributes as well.

public class PersonComparator implements Comparator<Person> {

  public enum SortOrder {ASCENDING, DESCENDING}

  private SortOrder sortOrder;

  public PersonComparator(SortOrder sortOrder) {
    this.sortOrder = sortOrder;
  }

  @Override
  public int compare(Person person1, Person person2) {
    Integer age1 = person1.getAge();
    Integer age2 = person2.getAge();
    int compare = Math.signum(age1.compareTo(age2));

    if (sortOrder == ASCENDING) {
      return compare;
    } else {
      return compare * (-1);
    }
  }
}

(hope it compiles now, I have no IDE or JDK at hand, coded 'blind')

Edit

Thanks to Thomas, edited the code. I wouldn't say that the usage of Math.signum is good, performant, effective, but I'd like to keep it as a reminder, that the compareTo method can return any integer and multiplying by (-1) will fail if the implementation returns Integer.MIN_INTEGER... And I removed the setter because it's cheap enough to construct a new PersonComparator just when it's needed.

But I keep the boxing because it shows that I rely on an existing Comparable implementation. Could have done something like Comparable<Integer> age1 = new Integer(person1.getAge()); but that looked too ugly. The idea was to show a pattern which could easily be adapted to other Person attributes, like name, birthday as Date and so on.

SQL Delete Records within a specific Range

if you use Sql Server

delete from Table where id between 79 and 296

After your edit : you now clarified that you want :

ID (>79 AND < 296)

So use this :

delete from Table where id > 79 and id < 296

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

You should have name column as a unique constraint. here is a 3 lines of code to change your issues

  1. First find out the primary key constraints by typing this code

    \d table_name
    

    you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)

  2. Drop the constraint:

    ALTER TABLE table_name DROP CONSTRAINT some_constraint
    
  3. Add a new primary key column with existing one:

    ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
    

That's All.

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Adding to @jakentus answer, below is what worked for me:

  1. Change the file name in the models package to Logon_model.php (First letter upper case as @jakentus correctly said)

  2. Change the class name as same as file name i.e.

    class Logon_model extends CI_Model

  3. Change the name in the load method too as

    $this->load->model('Logon_model');

Hope this helps. Happy coding. :)