Programs & Examples On #Data layer

A data access layer (DAL) in computer software, is a layer of a computer program which provides simplified access to data stored in persistent storage of some kind, such as an entity-relational database.

How to auto-format code in Eclipse?

You can do with some step bellow

Step 1: press Ctr + A(windows) or cmd + A (Mac os)

Step 2: Ctr + I in windows or cmd + I in Mac os

It will auto format for you

Regards

Synchronous Requests in Node.js

See sync-request: https://github.com/ForbesLindesay/sync-request

Example:

var request = require('sync-request');
var res = request('GET', 'http://example.com');
console.log(res.getBody());

How can I list all the deleted files in a Git repository?

Show all deleted files in some_branch

git diff origin/master...origin/some_branch --name-status | grep ^D

or

git diff origin/master...origin/some_branch --name-status --diff-filter=D 

How can I set response header on express.js assets

You can also add a middleware to add CORS headers, something like this would work:

/**
 * Adds CORS headers to the response
 *
 * {@link https://en.wikipedia.org/wiki/Cross-origin_resource_sharing}
 * {@link http://expressjs.com/en/4x/api.html#res.set}
 * @param {object} request the Request object
 * @param {object} response the Response object
 * @param {function} next function to continue execution
 * @returns {void}
 * @example
 * <code>
 * const express = require('express');
 * const corsHeaders = require('./middleware/cors-headers');
 *
 * const app = express();
 * app.use(corsHeaders);
 * </code>
 */
module.exports = (request, response, next) => {
    // http://expressjs.com/en/4x/api.html#res.set
    response.set({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'DELETE,GET,PATCH,POST,PUT',
        'Access-Control-Allow-Headers': 'Content-Type,Authorization'
    });

    // intercept OPTIONS method
    if(request.method === 'OPTIONS') {
        response.send(200);
    } else {
        next();
    }
};

How to position two divs horizontally within another div

Best and simple approach with css3

#subtitle{
/*for webkit browsers*/
     display:-webkit-box;
    -webkit-box-align:center;
    -webkit-box-pack: center;
     width:100%;
}

#subleft,#subright{
     width:50%;
}

RVM is not a function, selecting rubies with 'rvm use ...' will not work

Following work for me in ubuntu 19.1

source ~/.rvm/scripts/rvm

Blue and Purple Default links, how to remove?

Hey define color #000 into as like you and modify your css as like this

.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }

or this

 li a { text-decoration: none; color:#000; }
 li a:visited { text-decoration: none; color:#000; }
 li a:hover { text-decoration: none; color:#000; }
 li a:focus { text-decoration: none; color:#000; }
 li a:hover, .navBtn:active { text-decoration: none; color:#000; }

Check if DataRow exists by column name in c#?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

Something like:

DataColumnCollection Columns = dtItems.Columns;

if (Columns.Contains(ColNameToCheck))
{
  row["ColNameToCheck"] = "Checked";
}

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

I think this one will answer your question :P

$url="https://.../api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=??desc&limit=1&grab_content&content_limit=1";

Using cURL

//  Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
var_dump(json_decode($result, true));

Using file_get_contents

$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));

Accessing

$array["threads"][13/* thread id */]["title"/* thread key */]

And

$array["threads"][13/* thread id */]["content"/* thread key */]["content"][23/* post id */]["message" /* content key */];

Visual Studio 2008 Product Key in Registry?

For 32 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY


For 64 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY


Notes:

  • Data is a GUID without dashes. Put a dash ( – ) after every 5 characters to convert to product key.
  • If PIDKEY value is empty try to look at the subfolders e.g.

    ...\Registration\1000.0x0000\PIDKEY

    or

    ...\Registration\2000.0x0000\PIDKEY

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Good examples using java.util.logging

Should declare logger like this:

private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());

so if you refactor your class name it follows.

I wrote an article about java logger with examples here.

How to show a confirm message before delete?

<a href="javascript:;" onClick="if(confirm('Are you sure you want to delete this product')){del_product(id);}else{ }" class="btn btn-xs btn-danger btn-delete" title="Del Product">Delete Product</a>

<!-- language: lang-js -->
<script>
function del_product(id){
    $('.process').css('display','block');
    $('.process').html('<img src="./images/loading.gif">');
    $.ajax({
        'url':'./process.php?action=del_product&id='+id,
        'type':"post",
        success: function(result){
            info=JSON.parse(result);
            if(result.status==1){
                setTimeout(function(){
                    $('.process').hide();
                    $('.tr_'+id).hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            } else if(result.status==0){
                setTimeout(function(){
                    $('.process').hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            }
        }
    });
}
</script>

How to remove Firefox's dotted outline on BUTTONS as well as links?

Remove dotted outline from links, button and input element.

a:focus, a:active,
button::-moz-focus-inner,
input[type="reset"]::-moz-focus-inner,
input[type="button"]::-moz-focus-inner,
input[type="submit"]::-moz-focus-inner {
    border: 0;
    outline : 0;
}

GSON - Date format

As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.

Gson gson = new GsonBuilder()
   .registerTypeAdapter(java.sql.Date.class, ser).create();

This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.

what is the basic difference between stack and queue?

STACK is a LIFO (last in, first out) list. means suppose 3 elements are inserted in stack i.e 10,20,30. 10 is inserted first & 30 is inserted last so 30 is first deleted from stack & 10 is last deleted from stack.this is an LIFO list(Last In First Out).

QUEUE is FIFO list(First In First Out).means one element is inserted first which is to be deleted first.e.g queue of peoples.

Using getResources() in non-activity class

well no need of passing the context and doing all that...simply do this

Context context = parent.getContext();

Edit: where parent is the ViewGroup

Difference between abstract class and interface in Python

Python >= 2.6 has Abstract Base Classes.

Abstract Base Classes (abbreviated ABCs) complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy. Python comes with many builtin ABCs for data structures (in the collections module), numbers (in the numbers module), and streams (in the io module). You can create your own ABC with the abc module.

There is also the Zope Interface module, which is used by projects outside of zope, like twisted. I'm not really familiar with it, but there's a wiki page here that might help.

In general, you don't need the concept of abstract classes, or interfaces in python (edited - see S.Lott's answer for details).

Using sed, how do you print the first 'N' characters of a line?

To print the N first characters you can remove the N+1 characters up to the end of line:

$ sed 's/.//5g' <<< "defn-test"
defn

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Inspired by [@JulieLerman 's DDD MSDN Mag Article 2013][1]

    public class ShippingContext : BaseContext<ShippingContext>
{
  public DbSet<Shipment> Shipments { get; set; }
  public DbSet<Shipper> Shippers { get; set; }
  public DbSet<OrderShippingDetail> Order { get; set; } //Orders table
  public DbSet<ItemToBeShipped> ItemsToBeShipped { get; set; }
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Ignore<LineItem>();
    modelBuilder.Ignore<Order>();
    modelBuilder.Configurations.Add(new ShippingAddressMap());
  }
}

public class BaseContext<TContext>
  DbContext where TContext : DbContext
{
  static BaseContext()
  {
    Database.SetInitializer<TContext>(null);
  }
  protected BaseContext() : base("DPSalesDatabase")
  {}
}   

"If you’re doing new development and you want to let Code First create or migrate your database based on your classes, you’ll need to create an “uber-model” using a DbContext that includes all of the classes and relationships needed to build a complete model that represents the database. However, this context must not inherit from BaseContext." JL

Should I use != or <> for not equal in T-SQL?

I preferred using != instead of <> because sometimes I use the <s></s> syntax to write SQL commands. Using != is more handy to avoid syntax errors in this case.

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

If you can get away with using map this is a four-line-solution:

_x000D_
_x000D_
var mystring = '1111342=Adam%20Franco&348572=Bob%20Jones';_x000D_
_x000D_
var result = mystring.match(/(&|&amp;)?([^=]+)=([^&]+)/g) || [];_x000D_
result = result.map(function(i) {_x000D_
  return i.match(/(&|&amp;)?([^=]+)=([^&]+)/);_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Ain't pretty, ain't efficient, but at least it is compact. ;)

How to uninstall Jenkins?

Keep in mind, that in Terminal you need to add backslash before space, so the proper copy/paste will be

/Library/Application\ Support/Jenkins/Uninstall.command

p.s. sorry for the late answer :)

Add all files to a commit except a single file?

git add -u
git reset -- main/dontcheckmein.txt

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

  1. Using html5 doctype at the beginning of the page.

    <!DOCTYPE html>

  2. Force IE to use the latest render mode

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

  3. If your target browser is ie8, then check your compatible settings in IE8

I blog this in details

Is it possible to use Visual Studio on macOS?

There is no native version of Visual Studio for Mac OS X.

Almost all versions of Visual Studio have a Garbage rating on Wine's application database, so Wine isn't an option either, sadly.

How can I make space between two buttons in same div?

if use Bootstrap, you can change with style like: If you want only in one page, then betwen head tags add .btn-group btn{margin-right:1rem;}

If is for all the web site add to css file

jQuery: read text file from file system

A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:

html:

<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
  <script type="text/javascript">
    function loadData() {
      // getData() will return the string of data...
      document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
    }
  </script>
</head>

<body onload='loadData()'>
  <h1>check out the data!</h1>
  <div id='data'></div>
</body>

</html>

script.js:

// function wrapper, just return the string of data (csv etc)
function getData () {
    return 'look at this line of data\n\
oh, look at this line'
}

See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\').

Move to another EditText when Soft Keyboard Next is clicked on Android

Simple way, when you have just few fields one by one:

Need to set

android:maxLines="1"

android:imeOptions="actionNext"

android:inputType="" <- Set your type of text, in other case it will be Multiline and prevent to go next

Sample:

<EditText android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:textSize="@dimen/text_large"
              android:maxLines="1"
              android:inputType="textEmailAddress"
              android:imeOptions="actionNext"
              android:layout_marginLeft="@dimen/element_margin_large"
              android:layout_marginRight="@dimen/element_margin_large"
              android:layout_marginTop="0dp"/>

Maximum packet size for a TCP connection

The packet size for a TCP setting in IP protocol(Ip4). For this field(TL), 16 bits are allocated, accordingly the max size of packet is 65535 bytes: IP protocol details

How to sum up elements of a C++ vector?

Prasoon has already offered up a host of different (and good) ways to do this, none of which need repeating here. I'd like to suggest an alternative approach for speed however.

If you're going to be doing this quite a bit, you may want to consider "sub-classing" your vector so that a sum of elements is maintained separately (not actually sub-classing vector which is iffy due to the lack of a virtual destructor - I'm talking more of a class that contains the sum and a vector within it, has-a rather than is-a, and provides the vector-like methods).

For an empty vector, the sum is set to zero. On every insertion to the vector, add the element being inserted to the sum. On every deletion, subtract it. Basically, anything that can change the underlying vector is intercepted to ensure the sum is kept consistent.

That way, you have a very efficient O(1) method for "calculating" the sum at any point in time (just return the sum currently calculated). Insertion and deletion will take slightly longer as you adjust the total and you should take this performance hit into consideration.

Vectors where the sum is needed more often than the vector is changed are the ones likely to benefit from this scheme, since the cost of calculating the sum is amortised over all accesses. Obviously, if you only need the sum every hour and the vector is changing three thousand times a second, it won't be suitable.

Something like this would suffice:

class UberVector:
    private Vector<int> vec
    private int sum

    public UberVector():
        vec = new Vector<int>()
        sum = 0

    public getSum():
        return sum

    public add (int val):
        rc = vec.add (val)
        if rc == OK:
            sum = sum + val
        return rc

    public delindex (int idx):
        val = 0
        if idx >= 0 and idx < vec.size:
            val = vec[idx]
        rc =  vec.delindex (idx)
        if rc == OK:
            sum = sum - val
        return rc

Obviously, that's pseudo-code and you may want to have a little more functionality, but it shows the basic concept.

Auto-increment on partial primary key with Entity Framework Core

To anyone who came across this question who are using SQL Server Database and still having an exception thrown even after adding the following annotation on the int primary key

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

Please check your SQL, make sure your the primary key has 'IDENTITY(startValue, increment)' next to it,

CREATE TABLE [dbo].[User]
(
    [Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY
)

This will make the database increments the id every time a new row is added, with a starting value of 1 and increments of 1.

I accidentally overlooked that in my SQL which cost me an hour of my life, so hopefully this helps someone!!!

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

How to get a table creation script in MySQL Workbench?

1 use command

show create table test.location

enter image description here

  1. right click on selected row and choose Open Value In Viewer

  2. select tab Text enter image description here

How to size an Android view based on its parent's dimensions

Try this

int parentWidth = ((parentViewType)childView.getParent()).getWidth();
int parentHeight = ((parentViewType)childView.getParent()).getHeight();

then you can use LinearLayout.LayoutParams for setting the chileView's parameters

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(childWidth,childLength);
childView.setLayoutParams(params);

How to move screen without moving cursor in Vim?

Enter vim and type:

:help z

z is the vim command for redraw, so it will redraw the file relative to where you position the cursor. The options you have are as follows:

z+ - Redraws the file with the cursor at top of the window and at first non-blank character of your line.

z- - Redraws the file with the cursor at bottom of the window and at first non-blank character of your line.

z. - Redraws the file with the cursor at centre of the window and at first non-blank character of your line.

zt - Redraws file with the cursor at top of the window.

zb - Redraws file with the cursor at bottom of the window.

zz - Redraws file with the cursor at centre of the window.

Regex match digits, comma and semicolon?

Try word.matches("^[0-9,;]+$");

Python: read all text file lines in loop

There are situations where you can't use the (quite convincing) with... for... structure. In that case, do the following:

line = self.fo.readline()
if len(line) != 0:
     if 'str' in line:
         break

This will work because the the readline() leaves a trailing newline character, where as EOF is just an empty string.

Apache: client denied by server configuration

OK I am using the wrong syntax, I should be using

Allow from 127.0.0.1
Allow from ::1
...

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

Error: The type exists in both directories

Assuming you're building a Web Application, which it appears you are given the MVC2 point, you shouldn't use the App_Code folder. It was not designed to be integrated with Web Application projects.

When you Compile in Visual Studio, all the code in your application (including in App_Code) gets compiled into an assembly. When you run your application, asp.net knows about a "special" folder called App_Code and compiles the content of it into an assembly with a unique name. Thus, anytime you run the project you'll run into this problem.

The solution:

Rename your App_Code folder to something like "Code" or "Global" (and update your now broken references) & voila, problem solved.

How can I make a CSS glass/blur effect work for an overlay?

background: rgba(255,255,255,0.5);
backdrop-filter: blur(5px);

Instead of adding another blur background to your content, you can use backdrop-filter. FYI IE 11 and Firefox may not support it. Check caniuse.

Demo:

_x000D_
_x000D_
header {_x000D_
  position: fixed;_x000D_
  width: 100%;_x000D_
  padding: 10px;_x000D_
  background: rgba(255,255,255,0.5);_x000D_
  backdrop-filter: blur(5px);_x000D_
}_x000D_
body {_x000D_
  margin: 0;_x000D_
}
_x000D_
<header>_x000D_
  Header_x000D_
</header>_x000D_
<div>_x000D_
  <img src="https://dummyimage.com/600x400/000/fff" />_x000D_
  <img src="https://dummyimage.com/600x400/000/fff" />_x000D_
  <img src="https://dummyimage.com/600x400/000/fff" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

set font size in jquery

Not saying this is better, just another way:

$("#elem")[0].style.fontSize="20px";

How do I get the current date and current time only respectively in Django?

import datetime

datetime.date.today()  # Returns 2018-01-15

datetime.datetime.now() # Returns 2018-01-15 09:00

Concatenate two slices in Go

Add dots after the second slice:

//---------------------------vvv
append([]int{1,2}, []int{3,4}...)

This is just like any other variadic function.

func foo(is ...int) {
    for i := 0; i < len(is); i++ {
        fmt.Println(is[i])
    }
}

func main() {
    foo([]int{9,8,7,6,5}...)
}

HTML-encoding lost when attribute read from input field

As far as I know there isn't any straight forward HTML Encode/Decode method in javascript.

However, what you can do, is to use JS to create an arbitrary element, set its inner text, then read it using innerHTML.

Let's say, with jQuery, this should work:

var helper = $('chalk & cheese').hide().appendTo('body');
var htmled = helper.html();
helper.remove();

Or something along these lines.

cannot find zip-align when publishing app

If you are using gradle just update ypur gradle plugin!

Change line in build.gradle from:

classpath 'com.android.tools.build:gradle:0.9.+'

to:

classpath 'com.android.tools.build:gradle:0.11.+'

It works for me.

Note that variable buildToolsVersion (for me "20.0.0") must match your version of build-tools.

Good luck :)

"date(): It is not safe to rely on the system's timezone settings..."

@Justis pointed me to the right direction, but his code did not work for me. This did:

// set the default timezone if not set at php.ini
if (!date_default_timezone_get('date.timezone')) {
    // insert here the default timezone
    date_default_timezone_set('America/New_York');
}

Documentation: http://www.php.net/manual/en/function.date-default-timezone-get.php

This solution is not only for those who does not have full system access. It is necessary for any script when you provide it to anyone else but you. You never know on what server the script will run when you distribute it to someone else.

Writing html form data to a txt file without the use of a webserver

i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.

the code is below:-

    <!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
  <input type="submit" value="SAVE">
</form>
</body>
</html>

What is the intended use-case for git stash?

I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.

You don't want to commit you experimental changes

When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?

You don't want to lose local changes with a hard reset

In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.

So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.

And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.

Git stash and GitHub

GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.

One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.

git diff > git-dif-file.diff

pop the stash

SQL Server dynamic PIVOT query?

There's my solution cleaning up the unnecesary null values

DECLARE @cols AS NVARCHAR(MAX),
@maxcols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(CodigoFormaPago) 
                from PO_FormasPago
                order by CodigoFormaPago
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

select @maxcols = STUFF((SELECT ',MAX(' + QUOTENAME(CodigoFormaPago) + ') as ' + QUOTENAME(CodigoFormaPago)
                from PO_FormasPago
                order by CodigoFormaPago
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

set @query = 'SELECT CodigoProducto, DenominacionProducto, ' + @maxcols + '
            FROM
            (
                SELECT 
                CodigoProducto, DenominacionProducto,
                ' + @cols + ' from 
                 (
                    SELECT 
                        p.CodigoProducto as CodigoProducto,
                        p.DenominacionProducto as DenominacionProducto,
                        fpp.CantidadCuotas as CantidadCuotas,
                        fpp.IdFormaPago as IdFormaPago,
                        fp.CodigoFormaPago as CodigoFormaPago
                    FROM
                        PR_Producto p
                        LEFT JOIN PR_FormasPagoProducto fpp
                            ON fpp.IdProducto = p.IdProducto
                        LEFT JOIN PO_FormasPago fp
                            ON fpp.IdFormaPago = fp.IdFormaPago
                ) xp
                pivot 
                (
                    MAX(CantidadCuotas)
                    for CodigoFormaPago in (' + @cols + ')
                ) p 
            )  xx 
            GROUP BY CodigoProducto, DenominacionProducto'

t @query;

execute(@query);

Round double value to 2 decimal places

In Swift 2.0 and Xcode 7.2:

let pi:Double = 3.14159265358979
String(format:"%.2f", pi)

Example:

enter image description here

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

Add a View:

  1. Right-Click View Folder
  2. Click Add -> View
  3. Click Create a strongly-typed view
  4. Select your User class
  5. Select List as the Scaffold template

Add a controller and action method to call the view:

public ActionResult Index()
{
    var users = DataContext.GetUsers();
    return View(users);
}

Viewing my IIS hosted site on other machines on my network

If you're hosting website on a specific port in IIS like 4321 then you'd have to allow this port through Windows Firewall too. Here're the steps that I followed along with the imanabidi's answer to get it work for me:

  1. Windows Firewall > Advanced settings
  2. Inbound Rules > New Rule
  3. Select Port > Next
  4. Specific local ports > Add the Port you want to allow
  5. Allow All Connections
  6. Enter a name and some description so that you remember it later on
  7. Done

Default passwords of Oracle 11g?

Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)

then... v. SQL> connect /as sysdba

Connected. [SQL prompt response]

vi. SQL> alter user SYS identified by "newpassword";

User altered. [SQL prompt response]

Thank you. This minimized a headache

Argparse: Required arguments listed under "optional arguments"?

One more time, building off of @RalphyZ

This one doesn't break the exposed API.

from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')

# Add back help 
optional.add_argument(
    '-h',
    '--help',
    action='help',
    default=SUPPRESS,
    help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')

Which will show the same as above and should survive future versions:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

How to check whether an array is empty using PHP?

You can use array_filter() which works great for all situations:

$ray_state = array_filter($myarray);

if (empty($ray_state)) {
    echo 'array is empty';
} else {
    echo 'array is not empty';
}

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

What are the default access modifiers in C#?

I would like to add some documentation link. Check out more detail here.

enter image description here

PHP Fatal error: Call to undefined function mssql_connect()

php.ini probably needs to read: extension=ext\php_sqlsrv_53_nts.dll

Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P

Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents
<? phpinfo(); ?> and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)

Call child component method from parent class - Angular

Angular – Call Child Component’s Method in Parent Component’s Template

You have ParentComponent and ChildComponent that looks like this.

parent.component.html

enter image description here

parent.component.ts

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  constructor() {
  }
}

child.component.html

<p>
  This is child
</p>

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor() {
  }

  doSomething() {
    console.log('do something');
  }
}

When serve, it looks like this:

enter image description here

When user focus on ParentComponent’s input element, you want to call ChildComponent’s doSomething() method.

Simply do this:

  1. Give app-child selector in parent.component.html a DOM variable name (prefix with # – hashtag), in this case we call it appChild.
  2. Assign expression value (of the method you want to call) to input element’s focus event.

enter image description here

The result:

enter image description here

LINQ query to return a Dictionary<string, string>

Use the ToDictionary method directly.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

400 BAD request HTTP error code meaning?

First check the URL it might be wrong, if it is correct then check the request body which you are sending, the possible cause is request that you are sending is missing right syntax.

To elaborate , check for special characters in the request string. If it is (special char) being used this is the root cause of this error.

try copying the request and analyze each and every tags data.

What value could I insert into a bit type column?

Your issue is in PHPMyAdmin itself. Some versions do not display the value of bit columns, even though you did set it correctly.

How can I check if my python object is a number?

Sure you can use isinstance, but be aware that this is not how Python works. Python is a duck typed language. You should not explicitly check your types. A TypeError will be raised if the incorrect type was passed.

So just assume it is an int. Don't bother checking.

Empty or Null value display in SSRS text boxes

I agree on performing the replace on the SQL side, but using the ISNULL function would be the way I'd go.

SELECT ISNULL(table.MyField, "NA") AS MyField

I usually do as much processing of data on our SQL servers and try to do as little data manipulation in SSRS as possible. This is mainly because my SQL server is considerably more powerful than my SSRS server.

Invalid application path

I still haven’t find a solution, but find a workaround.

You can manually change IIS configuration, in system32\intsrv\config\applicationHost.config. Just manually create (copy-paste) section in <sites> and <location>.

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

How to smooth a curve in the right way?

Check this out! There is a clear definition of smoothing of a 1D signal.

http://scipy-cookbook.readthedocs.io/items/SignalSmooth.html

Shortcut:

import numpy

def smooth(x,window_len=11,window='hanning'):
    """smooth the data using a window with requested size.

    This method is based on the convolution of a scaled window with the signal.
    The signal is prepared by introducing reflected copies of the signal 
    (with the window size) in both ends so that transient parts are minimized
    in the begining and end part of the output signal.

    input:
        x: the input signal 
        window_len: the dimension of the smoothing window; should be an odd integer
        window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
            flat window will produce a moving average smoothing.

    output:
        the smoothed signal

    example:

    t=linspace(-2,2,0.1)
    x=sin(t)+randn(len(t))*0.1
    y=smooth(x)

    see also: 

    numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
    scipy.signal.lfilter

    TODO: the window parameter could be the window itself if an array instead of a string
    NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
    """

    if x.ndim != 1:
        raise ValueError, "smooth only accepts 1 dimension arrays."

    if x.size < window_len:
        raise ValueError, "Input vector needs to be bigger than window size."


    if window_len<3:
        return x


    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
        raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"


    s=numpy.r_[x[window_len-1:0:-1],x,x[-2:-window_len-1:-1]]
    #print(len(s))
    if window == 'flat': #moving average
        w=numpy.ones(window_len,'d')
    else:
        w=eval('numpy.'+window+'(window_len)')

    y=numpy.convolve(w/w.sum(),s,mode='valid')
    return y




from numpy import *
from pylab import *

def smooth_demo():

    t=linspace(-4,4,100)
    x=sin(t)
    xn=x+randn(len(t))*0.1
    y=smooth(x)

    ws=31

    subplot(211)
    plot(ones(ws))

    windows=['flat', 'hanning', 'hamming', 'bartlett', 'blackman']

    hold(True)
    for w in windows[1:]:
        eval('plot('+w+'(ws) )')

    axis([0,30,0,1.1])

    legend(windows)
    title("The smoothing windows")
    subplot(212)
    plot(x)
    plot(xn)
    for w in windows:
        plot(smooth(xn,10,w))
    l=['original signal', 'signal with noise']
    l.extend(windows)

    legend(l)
    title("Smoothing a noisy signal")
    show()


if __name__=='__main__':
    smooth_demo()

Merge unequal dataframes and replace missing rows with 0

Another alternative with data.table.

EXAMPLE DATA

dt1 <- data.table(df1)
dt2 <- data.table(df2)
setkey(dt1,x)
setkey(dt2,x)

CODE

dt2[dt1,list(y=ifelse(is.na(y),0,y))]

Android Facebook integration with invalid key hash

This is how I solved this problem:

First you have to get the SHA-1 value. For that there are two ways.

To get the SHA-1 value in Android Studio.

  1. Click Gradle
  2. Click Signing Report
  3. Copy the SHA-1 value

OR

To get the SHA-1 value from the keystore file.

keytool -list -v -keystore keystore_file_name.jks -alias key0

Copy the SHA-1 value to your clipboard like this:

CD:A1:EA:A3:5C:5C:68:FB:FA:0A:6B:E5:5A:72:64:DD:26:8D:44:84

And open Hexadecimal -> Base64 string decoder to convert your SHA-1 value to Base64.

This is what Facebook requires.

Get the generated hash " ********************= " and copy the key hash to the Facebook app.

How to create multiple class objects with a loop in python?

Creating a dictionary as it has mentioned, but in this case each key has the name of the object name that you want to create. Then the value is set as the class you want to instantiate, see for example:

class MyClass:
   def __init__(self, name):
       self.name = name
       self.checkme = 'awesome {}'.format(self.name)
...

instanceNames = ['red', 'green', 'blue']

# Here you use the dictionary
holder = {name: MyClass(name=name) for name in instanceNames}

Then you just call the holder key and you will have all the properties and methods of your class available for you.

holder['red'].checkme

output:

'awesome red'

The difference between "require(x)" and "import x"

new ES6:

'import' should be used with 'export' key words to share variables/arrays/objects between js files:

export default myObject;

//....in another file

import myObject from './otherFile.js';

old skool:

'require' should be used with 'module.exports'

 module.exports = myObject;

//....in another file

var myObject = require('./otherFile.js');

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Passing a Bundle on startActivity()?

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);


Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key)

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Difference between __getattr__ vs __getattribute__

Lets see some simple examples of both __getattr__ and __getattribute__ magic methods.

__getattr__

Python will call __getattr__ method whenever you request an attribute that hasn't already been defined. In the following example my class Count has no __getattr__ method. Now in main when I try to access both obj1.mymin and obj1.mymax attributes everything works fine. But when I try to access obj1.mycurrent attribute -- Python gives me AttributeError: 'Count' object has no attribute 'mycurrent'

class Count():
    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent)  --> AttributeError: 'Count' object has no attribute 'mycurrent'

Now my class Count has __getattr__ method. Now when I try to access obj1.mycurrent attribute -- python returns me whatever I have implemented in my __getattr__ method. In my example whenever I try to call an attribute which doesn't exist, python creates that attribute and set it to integer value 0.

class Count:
    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax    

    def __getattr__(self, item):
        self.__dict__[item]=0
        return 0

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent1)

__getattribute__

Now lets see the __getattribute__ method. If you have __getattribute__ method in your class, python invokes this method for every attribute regardless whether it exists or not. So why we need __getattribute__ method? One good reason is that you can prevent access to attributes and make them more secure as shown in the following example.

Whenever someone try to access my attributes that starts with substring 'cur' python raises AttributeError exception. Otherwise it returns that attribute.

class Count:

    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax
        self.current=None

    def __getattribute__(self, item):
        if item.startswith('cur'):
            raise AttributeError
        return object.__getattribute__(self,item) 
        # or you can use ---return super().__getattribute__(item)

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)

Important: In order to avoid infinite recursion in __getattribute__ method, its implementation should always call the base class method with the same name to access any attributes it needs. For example: object.__getattribute__(self, name) or super().__getattribute__(item) and not self.__dict__[item]

IMPORTANT

If your class contain both getattr and getattribute magic methods then __getattribute__ is called first. But if __getattribute__ raises AttributeError exception then the exception will be ignored and __getattr__ method will be invoked. See the following example:

class Count(object):

    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax
        self.current=None

    def __getattr__(self, item):
            self.__dict__[item]=0
            return 0

    def __getattribute__(self, item):
        if item.startswith('cur'):
            raise AttributeError
        return object.__getattribute__(self,item)
        # or you can use ---return super().__getattribute__(item)
        # note this class subclass object

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

How to capture a JFrame's close button click event?

import javax.swing.JOptionPane;
import javax.swing.JFrame;

/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
        if (JOptionPane.showConfirmDialog(frame, 
            "Are you sure you want to close this window?", "Close Window?", 
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
            System.exit(0);
        }
    }
});

If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        s += scan.nextLine();
        System.out.println("String: " + s);

    }
}

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

Changing the color of an hr element

if u use css class then it will be taken by all 'hr' tags , but if u want for a particular 'hr' use the below code i.e, inline css

<hr style="color:#99CC99" />

if it's not working in chrome try below code:

<hr color="red" />

How to set background color of HTML element using css properties in JavaScript

You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.

Your CSS would obviously be something like:

.highlight {
    background:#ff00aa;
}

Then in JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';

How many spaces will Java String.trim() remove?

One very important thing is that a string made entirely of "white spaces" will return a empty string.

if a string sSomething = "xxxxx", where x stand for white spaces, sSomething.trim() will return an empty string.

if a string sSomething = "xxAxx", where x stand for white spaces, sSomething.trim() will return A.

if sSomething ="xxSomethingxxxxAndSomethingxElsexxx", sSomething.trim() will return SomethingxxxxAndSomethingxElse, notice that the number of x between words is not altered.

If you want a neat packeted string combine trim() with regex as shown in this post: How to remove duplicate white spaces in string using Java?.

Order is meaningless for the result but trim() first would be more efficient. Hope it helps.

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

Effective method to hide email from spam bots

One easy solution is to use HTML entities instead of actual characters. For example, the "[email protected]" will be converted into :

<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#109;&#101;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;">email me</A>

Create 3D array using Python

The right way would be

[[[0 for _ in range(n)] for _ in range(n)] for _ in range(n)]

(What you're trying to do should be written like (for NxNxN)

[[[0]*n]*n]*n

but that is not correct, see @Adaman comment why).

Get UTC time in seconds

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

What does the following Oracle error mean: invalid column index

If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.

For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.

Convert date from String to Date format in Dataframes

Use to_date with Java SimpleDateFormat.

TO_DATE(CAST(UNIX_TIMESTAMP(date, 'MM/dd/yyyy') AS TIMESTAMP))

Example:

spark.sql("""
  SELECT TO_DATE(CAST(UNIX_TIMESTAMP('08/26/2016', 'MM/dd/yyyy') AS TIMESTAMP)) AS newdate"""
).show()

+----------+
|        dt|
+----------+
|2016-08-26|
+----------+

How to check if a string array contains one string in JavaScript?

There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.

How to load npm modules in AWS Lambda?

Also in the many IDEs now, ex: VSC, you can install an extension for AWS and simply click upload from there, no effort of typing all those commands + region.

Here's an example:

enter image description here

How to sort in mongoose?

This is what i did, it works fine.

User.find({name:'Thava'}, null, {sort: { name : 1 }})

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Hide keyboard in react-native

The problem with keyboard not dismissing gets more severe if you have keyboardType='numeric', as there is no way to dismiss it.

Replacing View with ScrollView is not a correct solution, as if you have multiple textInputs or buttons, tapping on them while the keyboard is up will only dismiss the keyboard.

Correct way is to encapsulate View with TouchableWithoutFeedback and calling Keyboard.dismiss()

EDIT: You can now use ScrollView with keyboardShouldPersistTaps='handled' to only dismiss the keyboard when the tap is not handled by the children (ie. tapping on other textInputs or buttons)

If you have

<View style={{flex: 1}}>
    <TextInput keyboardType='numeric'/>
</View>

Change it to

<ScrollView contentContainerStyle={{flexGrow: 1}}
  keyboardShouldPersistTaps='handled'
>
  <TextInput keyboardType='numeric'/>
</ScrollView>

or

import {Keyboard} from 'react-native'

<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
    <View style={{flex: 1}}>
        <TextInput keyboardType='numeric'/>
    </View>
</TouchableWithoutFeedback>

EDIT: You can also create a Higher Order Component to dismiss the keyboard.

import React from 'react';
import { TouchableWithoutFeedback, Keyboard, View } from 'react-native';

const DismissKeyboardHOC = (Comp) => {
  return ({ children, ...props }) => (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
      <Comp {...props}>
        {children}
      </Comp>
    </TouchableWithoutFeedback>
  );
};
const DismissKeyboardView = DismissKeyboardHOC(View)

Simply use it like this

...
render() {
    <DismissKeyboardView>
        <TextInput keyboardType='numeric'/>
    </DismissKeyboardView>
}

NOTE: the accessible={false} is required to make the input form continue to be accessible through VoiceOver. Visually impaired people will thank you!

Upload DOC or PDF using PHP

You can use

$_FILES['filename']['error'];

If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done

1 : if file size is over limit .... You can find other options by googling

How to strip all non-alphabetic characters from string in SQL Server?

Parameterized version of G Mastros' awesome answer:

CREATE FUNCTION [dbo].[fn_StripCharacters]
(
    @String NVARCHAR(MAX), 
    @MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @MatchExpression =  '%['+@MatchExpression+']%'

    WHILE PatIndex(@MatchExpression, @String) > 0
        SET @String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, '')

    RETURN @String

END

Alphabetic only:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^a-z')

Numeric only:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^0-9')

Alphanumeric only:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^a-z0-9')

Non-alphanumeric:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', 'a-z0-9')

How to show Page Loading div until the page has finished loading?

My blog will work 100 percent.

_x000D_
_x000D_
function showLoader()_x000D_
{_x000D_
    $(".loader").fadeIn("slow");_x000D_
}_x000D_
function hideLoader()_x000D_
{_x000D_
    $(".loader").fadeOut("slow");_x000D_
}
_x000D_
.loader {_x000D_
    position: fixed;_x000D_
    left: 0px;_x000D_
    top: 0px;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    z-index: 9999;_x000D_
    background: url('pageLoader2.gif') 50% 50% no-repeat rgb(249,249,249);_x000D_
    opacity: .8;_x000D_
}
_x000D_
<div class="loader">
_x000D_
_x000D_
_x000D_

Rails where condition using NOT NIL

For Rails4:

So, what you're wanting is an inner join, so you really should just use the joins predicate:

  Foo.joins(:bar)

  Select * from Foo Inner Join Bars ...

But, for the record, if you want a "NOT NULL" condition simply use the not predicate:

Foo.includes(:bar).where.not(bars: {id: nil})

Select * from Foo Left Outer Join Bars on .. WHERE bars.id IS NOT NULL

Note that this syntax reports a deprecation (it talks about a string SQL snippet, but I guess the hash condition is changed to string in the parser?), so be sure to add the references to the end:

Foo.includes(:bar).where.not(bars: {id: nil}).references(:bar)

DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: ....) that are referenced in a string SQL snippet. For example:

Post.includes(:comments).where("comments.title = 'foo'")

Currently, Active Record recognizes the table in the string, and knows to JOIN the comments table to the query, rather than loading comments in a separate query. However, doing this without writing a full-blown SQL parser is inherently flawed. Since we don't want to write an SQL parser, we are removing this functionality. From now on, you must explicitly tell Active Record when you are referencing a table from a string:

Post.includes(:comments).where("comments.title = 'foo'").references(:comments)

How to ping an IP address

Here is a method for pinging an IP address in Java that should work on Windows and Unix systems:

import org.apache.commons.lang3.SystemUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CommandLine
{
    /**
     * @param ipAddress The internet protocol address to ping
     * @return True if the address is responsive, false otherwise
     */
    public static boolean isReachable(String ipAddress) throws IOException
    {
        List<String> command = buildCommand(ipAddress);
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        Process process = processBuilder.start();

        try (BufferedReader standardOutput = new BufferedReader(new InputStreamReader(process.getInputStream())))
        {
            String outputLine;

            while ((outputLine = standardOutput.readLine()) != null)
            {
                // Picks up Windows and Unix unreachable hosts
                if (outputLine.toLowerCase().contains("destination host unreachable"))
                {
                    return false;
                }
            }
        }

        return true;
    }

    private static List<String> buildCommand(String ipAddress)
    {
        List<String> command = new ArrayList<>();
        command.add("ping");

        if (SystemUtils.IS_OS_WINDOWS)
        {
            command.add("-n");
        } else if (SystemUtils.IS_OS_UNIX)
        {
            command.add("-c");
        } else
        {
            throw new UnsupportedOperationException("Unsupported operating system");
        }

        command.add("1");
        command.add(ipAddress);

        return command;
    }
}

Make sure to add Apache Commons Lang to your dependencies.

MSSQL Error 'The underlying provider failed on Open'

When you receive this exception, make sure to expand the detail and look at the inner exception details as it will provide details on why the login failed. In my case the connection string contained a user that did not have access to my database.

Regardless of whether you use Integrated Security (the context of the logged in Windows User) or an individual SQL account, make sure that the user has proper access under 'Security' for the database you are trying to access to prevent this issue.

Java Could not reserve enough space for object heap error

This was occuring for me and it is such an easy fix.

  1. you have to make sure that you have the correct java for your system such as 32bit or 64bit.
  2. if you have installed the correct software and it still occurs than goto

    control panelsystemadvanced system settings for Windows 8 or

    control panelsystem and securitysystemadvanced system settings for Windows 10.

  3. you must goto the {advanced tab} and then click on {Environment Variables}.
  4. you will click on {New} under the <system variables>
  5. you will create a new variable. Variable name: _JAVA_OPTIONS Variable Value: -Xmx512M

At least that is what worked for me.

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

You need Set with objects:

 Set rng = Sheet8.Range("A12")

Sheet8 is fine.

 Sheet1.[a1]

How to disable text selection using jQuery?

        $(document).ready(function(){
            $("body").css("-webkit-user-select","none");
            $("body").css("-moz-user-select","none");
            $("body").css("-ms-user-select","none");
            $("body").css("-o-user-select","none");
            $("body").css("user-select","none");
        });

Update and left outer join statements

If what you need is UPDATE from SELECT statement you can do something like this:

UPDATE suppliers    
SET city = (SELECT customers.city FROM customers

WHERE customers.customer_name = suppliers.supplier_name)

How to create a new component in Angular 4 using CLI

ng g c COMPONENTNAME

this command use for generating component using terminal this i use in angular2.

g for generate c for component

Count records for every month in a year

select count(*) 
from table_emp 
 where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'

Text not wrapping inside a div element

This may help a small percentage of people still scratching their heads. Text copied from clipboard into VSCode may have an invisible hard space character preventing wrapping. Check it with HTML inspector

string with hard spaces

How to set specific Java version to Maven

To avoid any impact to your project and to your Environment Variables, you can configure the Maven Compiler Plugin just to the project's POM, specifying the Source and Target java version

  <plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
            <source>1.7</source>
            <target>1.7</target>
        </configuration>
    </plugin>
    ...
  </plugins>

Can I safely delete contents of Xcode Derived data folder?

XCODE 10 UPDATE

On the tab:

  1. Click Xcode
  2. Preferences
  3. Locations -> Derived Data

You can access all derived data and clear by deleting them.

Google Authenticator available as a public service?

You can use my solution, posted as the answer to my question (there is full Python code and explanation):

Google Authenticator implementation in Python

It is rather easy to implement it in PHP or Perl, I think. If you have any problems with this, please let me know.

I have also posted my code on GitHub as Python module.

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Always check for the obvious too. I got this error once when I accidently grabbed the wrong resource for the server's add and remove action. It can be easy to overlook.

How to make shadow on border-bottom?

I'm a little late on the party, but its actualy possible to emulate borders using a box-shadow

_x000D_
_x000D_
.border {_x000D_
  background-color: #ededed;_x000D_
  padding: 10px;_x000D_
  margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
.border-top {_x000D_
  box-shadow: inset 0 3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-right {_x000D_
  box-shadow: inset -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-bottom {_x000D_
  box-shadow: inset 0 -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-left {_x000D_
  box-shadow: inset 3px 0 0 cornflowerblue;_x000D_
}
_x000D_
<div class="border border-top">border-top</div>_x000D_
<div class="border border-right">border-right</div>_x000D_
<div class="border border-bottom">border-bottom</div>_x000D_
<div class="border border-left">border-left</div>
_x000D_
_x000D_
_x000D_

EDIT: I understood this question wrong, but I will leave the awnser as more people might misunderstand the question and came for the awnser I supplied.

Spring cron expression for every after 30 minutes

in web app java spring what worked for me

cron="0 0/30 * * * ?"

This will trigger on for example 10:00AM then 10:30AM etc...

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task.xsd">

    <beans profile="cron">
        <bean id="executorService" class="java.util.concurrent.Executors" factory-method="newFixedThreadPool">
            <beans:constructor-arg value="5" />
        </bean>

        <task:executor id="threadPoolTaskExecutor" pool-size="5" />
        <task:annotation-driven executor="executorService" />

        <beans:bean id="expireCronJob" class="com.cron.ExpireCron"/>

        <task:scheduler id="serverScheduler" pool-size="5"/>
        <task:scheduled-tasks scheduler="serverScheduler">
            <task:scheduled ref="expireCronJob" method="runTask" cron="0 0/30 * * * ?"/> <!-- every thirty minute -->
        </task:scheduled-tasks>

    </beans>

</beans>

I dont know why but this is working on my local develop and production, but other changes if i made i have to be careful because it may work local and on develop but not on production

How to redirect to a different domain using NGINX?

You can simply write a if condition inside server {} block:

server { 

    if ($host = mydomain.com) {
        return 301 http://www.adifferentdomain.com;
    } 
}

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

Import Maven dependencies in IntelliJ IDEA

What helped me:

Navigage: Settings | Build, Execution, Deployment | Maven

Specify "Maven home directory" - the place you installed the maven

are there dictionaries in javascript like python?

Use JavaScript objects. You can access their properties like keys in a dictionary. This is the foundation of JSON. The syntax is similar to Python dictionaries. See: JSON.org

How to find longest string in the table column data

The easiest way is:

select top 1 CR
from table t
order by len(CR) desc

Note that this will only return one value if there are multiple with the same longest length.

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

Use basic authentication with jQuery and Ajax

The examples above are a bit confusing, and this is probably the best way:

$.ajaxSetup({
  headers: {
    'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
  }
});

I took the above from a combination of Rico and Yossi's answer.

The btoa function Base64 encodes a string.

Can someone give an example of cosine similarity, in a very simple, graphical way?

Here are two very short texts to compare:

  1. Julie loves me more than Linda loves me

  2. Jane likes me more than Julie loves me

We want to know how similar these texts are, purely in terms of word counts (and ignoring word order). We begin by making a list of the words from both texts:

me Julie loves Linda than more likes Jane

Now we count the number of times each of these words appears in each text:

   me   2   2
 Jane   0   1
Julie   1   1
Linda   1   0
likes   0   1
loves   2   1
 more   1   1
 than   1   1

We are not interested in the words themselves though. We are interested only in those two vertical vectors of counts. For instance, there are two instances of 'me' in each text. We are going to decide how close these two texts are to each other by calculating one function of those two vectors, namely the cosine of the angle between them.

The two vectors are, again:

a: [2, 0, 1, 1, 0, 2, 1, 1]

b: [2, 1, 1, 0, 1, 1, 1, 1]

The cosine of the angle between them is about 0.822.

These vectors are 8-dimensional. A virtue of using cosine similarity is clearly that it converts a question that is beyond human ability to visualise to one that can be. In this case you can think of this as the angle of about 35 degrees which is some 'distance' from zero or perfect agreement.

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

The page cannot be displayed because an internal server error has occurred on server

I ended up on this page running Web Apps on Azure.

The page cannot be displayed because an internal server error has occurred.

We ran into this problem because we applicationInitialization in the web.config

<applicationInitialization
    doAppInitAfterRestart="true"
    skipManagedModules="true">
    <add initializationPage="/default.aspx" hostName="myhost"/>
</applicationInitialization>

If running on Azure, have a look at site slots. You should warm up the pages on a staging slot before swapping it to the production slot.

When do I need to use a semicolon vs a slash in Oracle SQL?

From my understanding, all the SQL statement don't need forward slash as they will run automatically at the end of semicolons, including DDL, DML, DCL and TCL statements.

For other PL/SQL blocks, including Procedures, Functions, Packages and Triggers, because they are multiple line programs, Oracle need a way to know when to run the block, so we have to write a forward slash at the end of each block to let Oracle run it.

Rails find_or_create_by more than one attribute?

By passing a block to find_or_create, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.

Assuming:

class GroupMember < ActiveRecord::Base
    validates_presence_of :name
end

then

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }

will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4 and group_id 7

Absolute positioning ignoring padding of parent

Here is my best shot at it. I added another Div and made it red and changed you parent's height to 200px just to test it. The idea is the the child now becomes the grandchild and the parent becomes the grandparent. So the parent respects its parent. Hope you get my idea.

<html>
  <body>
    <div style="background-color: blue; padding: 10px; position: relative; height: 200px;">
     <div style="background-color: red;  position: relative; height: 100%;">    
        <div style="background-color: gray; position: absolute; left: 0px; right: 0px;bottom: 0px;">css sux</div>
     </div>
    </div>
  </body>
</html>

Edit:

I think what you are trying to do can't be done. Absolute position means that you are going to give it co-ordinates it must honor. What if the parent has a padding of 5px. And you absolutely position the child at top: -5px; left: -5px. How is it suppose to honor the parent and you at the same time??

My solution

If you want it to honor the parent, don't absolutely position it then.

Lambda function in list comprehensions

This question touches a very stinking part of the "famous" and "obvious" Python syntax - what takes precedence, the lambda, or the for of list comprehension.

I don't think the purpose of the OP was to generate a list of squares from 0 to 9. If that was the case, we could give even more solutions:

squares = []
for x in range(10): squares.append(x*x)
  • this is the good ol' way of imperative syntax.

But it's not the point. The point is W(hy)TF is this ambiguous expression so counter-intuitive? And I have an idiotic case for you at the end, so don't dismiss my answer too early (I had it on a job interview).

So, the OP's comprehension returned a list of lambdas:

[(lambda x: x*x) for x in range(10)]

This is of course just 10 different copies of the squaring function, see:

>>> [lambda x: x*x for _ in range(3)]
[<function <lambda> at 0x00000000023AD438>, <function <lambda> at 0x00000000023AD4A8>, <function <lambda> at 0x00000000023AD3C8>]

Note the memory addresses of the lambdas - they are all different!

You could of course have a more "optimal" (haha) version of this expression:

>>> [lambda x: x*x] * 3
[<function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>]

See? 3 time the same lambda.

Please note, that I used _ as the for variable. It has nothing to do with the x in the lambda (it is overshadowed lexically!). Get it?

I'm leaving out the discussion, why the syntax precedence is not so, that it all meant:

[lambda x: (x*x for x in range(10))]

which could be: [[0, 1, 4, ..., 81]], or [(0, 1, 4, ..., 81)], or which I find most logical, this would be a list of 1 element - a generator returning the values. It is just not the case, the language doesn't work this way.

BUT What, If...

What if you DON'T overshadow the for variable, AND use it in your lambdas???

Well, then crap happens. Look at this:

[lambda x: x * i for i in range(4)]

this means of course:

[(lambda x: x * i) for i in range(4)]

BUT it DOESN'T mean:

[(lambda x: x * 0), (lambda x: x * 1), ... (lambda x: x * 3)]

This is just crazy!

The lambdas in the list comprehension are a closure over the scope of this comprehension. A lexical closure, so they refer to the i via reference, and not its value when they were evaluated!

So, this expression:

[(lambda x: x * i) for i in range(4)]

IS roughly EQUIVALENT to:

[(lambda x: x * 3), (lambda x: x * 3), ... (lambda x: x * 3)]

I'm sure we could see more here using a python decompiler (by which I mean e.g. the dis module), but for Python-VM-agnostic discussion this is enough. So much for the job interview question.

Now, how to make a list of multiplier lambdas, which really multiply by consecutive integers? Well, similarly to the accepted answer, we need to break the direct tie to i by wrapping it in another lambda, which is getting called inside the list comprehension expression:

Before:

>>> a = [(lambda x: x * i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
2

After:

>>> a = [(lambda y: (lambda x: y * x))(i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
1

(I had the outer lambda variable also = i, but I decided this is the clearer solution - I introduced y so that we can all see which witch is which).

Edit 2019-08-30:

Following a suggestion by @josoler, which is also present in an answer by @sheridp - the value of the list comprehension "loop variable" can be "embedded" inside an object - the key is for it to be accessed at the right time. The section "After" above does it by wrapping it in another lambda and calling it immediately with the current value of i. Another way (a little bit easier to read - it produces no 'WAT' effect) is to store the value of i inside a partial object, and have the "inner" (original) lambda take it as an argument (passed supplied by the partial object at the time of the call), i.e.:

After 2:

>>> from functools import partial
>>> a = [partial(lambda y, x: y * x, i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

Great, but there is still a little twist for you! Let's say we wan't to make it easier on the code reader, and pass the factor by name (as a keyword argument to partial). Let's do some renaming:

After 2.5:

>>> a = [partial(lambda coef, x: coef * x, coef=i) for i in (1, 2)]
>>> a[0](1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() got multiple values for argument 'coef'

WAT?

>>> a[0]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'x'

Wait... We're changing the number of arguments by 1, and going from "too many" to "too few"?

Well, it's not a real WAT, when we pass coef to partial in this way, it becomes a keyword argument, so it must come after the positional x argument, like so:

After 3:

>>> a = [partial(lambda x, coef: coef * x, coef=i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

I would prefer the last version over the nested lambda, but to each their own...

Edit 2020-08-18:

Thanks to commenter dasWesen, I found out that this stuff is covered in the Python documentation: https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result - it deals with loops instead of list comprehensions, but the idea is the same - global or nonlocal variable access in the lambda function. There's even a solution - using default argument values (like for any function):

>>> a = [lambda x, coef=i: coef * x for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

This way the coef value is bound to the value of i at the time of function definition (see James Powell's talk "Top To Down, Left To Right", which also explains why mutable default values are shunned).

How to horizontally align ul to center of div?

You can check this solved your problem...

    #headermenu ul{ 
        text-align: center;
    }
    #headermenu li { 
list-style-type: none;
        display: inline-block;
    }
    #headermenu ul li a{
        float: left;
    }

http://jsfiddle.net/thirtydot/VCZgW/

Java generating Strings with placeholders

Justas answer is outdated so I'm posting up to date answer with apache text commons.

StringSubstitutor from Apache Commons Text may be used for string formatting with named placeholders: https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods. Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.

Example:

 // Build map
 Map<String, String> valuesMap = new HashMap<>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";

 // Build StringSubstitutor
 StringSubstitutor sub = new StringSubstitutor(valuesMap);

 // Replace
 String resolvedString = sub.replace(templateString);

onKeyPress Vs. onKeyUp and onKeyDown

Just wanted to share a curiosity:

when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!

For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !

Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!

Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.

About "*.d.ts" in TypeScript

I could not comment and thus am adding this as an answer.
We had some pain trying to map existing types to a javascript library.

To map a .d.ts file to its javascript file you need to give the .d.ts file the same name as the javascript file, keep them in the same folder, and point the code that needs it to the .d.ts file.

eg: test.js and test.d.ts are in the testdir/ folder, then you import it like this in a react component:

import * as Test from "./testdir/test";

The .d.ts file was exported as a namespace like this:

export as namespace Test;

export interface TestInterface1{}
export class TestClass1{}

React Native absolute positioning horizontal centre

create a full-width View with alignItems: "center" then insert desired children inside.

import React from "react";
import {View} from "react-native";

export default class AbsoluteComponent extends React.Component {
  render(){
    return(
     <View style={{position: "absolute", left: 0, right: 0, alignItems: "center"}}>
      {this.props.children}
     </View>    
    )
  }
}

you can add properties like bottom: 30 for bottom aligned component.

C# list.Orderby descending

list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();

Which works for me to show the time sorted in descending order.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

How to host material icons offline?

My recipe has three steps:

  1. to install material-design-icons package

    npm install material-design-icons
    
  2. to import material-icons.css file into .less or .scss file/ project

    @import "~/node_modules/material-design-icons/iconfont/material-icons.css";
    
  3. to include recommended code into the reactjs .js file/ project

    <i className='material-icons' style={{fontSize: '36px'}}>close</i>
    

forEach is not a function error with JavaScript array

parent.children is not an array. It is HTMLCollection and it does not have forEach method. You can convert it to the array first. For example in ES6:

Array.from(parent.children).forEach(child => {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});

sscanf in Python

There is an example in the official python docs about how to use sscanf from libc:

    # import libc
    from ctypes import CDLL
    if(os.name=="nt"):
        libc = cdll.msvcrt 
    else:
        # assuming Unix-like environment
        libc = cdll.LoadLibrary("libc.so.6")
        libc = CDLL("libc.so.6")  # alternative

    # allocate vars
    i = c_int()
    f = c_float()
    s = create_string_buffer(b'\000' * 32)

    # parse with sscanf
    libc.sscanf(b"1 3.14 Hello", "%d %f %s", byref(i), byref(f), s)

    # read the parsed values
    i.value  # 1
    f.value  # 3.14
    s.value # b'Hello'

How to create a file in a directory in java?

When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.

    String absolutePath = ...
    try{
       File file = new File(absolutePath);
       file.mkdirs() ;
       //all parent folders are created
       //now the file will be created when you start writing to it via FileOutputStream.
      }catch (Exception e){
        System.out.println("Error : "+ e.getmessage());
       }

What's the difference between compiled and interpreted language?

As other have said, compiled and interpreted are specific to an implementation of a programming language; they are not inherent in the language. For example, there are C interpreters.

However, we can (and in practice we do) classify programming languages based on its most common (sometimes canonical) implementation. For example, we say C is compiled.

First, we must define without ambiguity interpreters and compilers:

An interpreter for language X is a program (or a machine, or just some kind of mechanism in general) that executes any program p written in language X such that it performs the effects and evaluates the results as prescribed by the specification of X.

A compiler from X to Y is a program (or a machine, or just some kind of mechanism in general) that translates any program p from some language X into a semantically equivalent program p' in some language Y in such a way that interpreting p' with an interpreter for Y will yield the same results and have the same effects as interpreting p with an interpreter for X.

Notice that from a programmer point of view, CPUs are machine interpreters for their respective native machine language.

Now, we can do a tentative classification of programming languages into 3 categories depending on its most common implementation:

  • Hard Compiled languages: When the programs are compiled entirely to machine language. The only interpreter used is a CPU. Example: Usually, to run a program in C, the source code is compiled to machine language, which is then executed by a CPU.
  • Interpreted languages: When there is no compilation of any part of the original program to machine language. In other words, no new machine code is generated; only existing machine code is executed. An interpreter other than the CPU must also be used (usually a program).Example: In the canonical implementation of Python, the source code is compiled first to Python bytecode and then that bytecode is executed by CPython, an interpreter program for Python bytecode.
  • Soft Compiled languages: When an interpreter other than the CPU is used but also parts of the original program may be compiled to machine language. This is the case of Java, where the source code is compiled to bytecode first and then, the bytecode may be interpreted by the Java Interpreter and/or further compiled by the JIT compiler.

Sometimes, soft and hard compiled languages are refered to simply compiled, thus C#, Java, C, C++ are said to be compiled.

Within this categorization, JavaScript used to be an interpreted language, but that was many years ago. Nowadays, it is JIT-compiled to native machine language in most major JavaScript implementations so I would say that it falls into soft compiled languages.

How can I convert a stack trace to a string?

Here is a version that is copy-pastable directly into code:

import java.io.StringWriter; 
import java.io.PrintWriter;

//Two lines of code to get the exception into a StringWriter
StringWriter sw = new StringWriter();
new Throwable().printStackTrace(new PrintWriter(sw));

//And to actually print it
logger.info("Current stack trace is:\n" + sw.toString());

Or, in a catch block

} catch (Throwable t) {
    StringWriter sw = new StringWriter();
    t.printStackTrace(new PrintWriter(sw));
    logger.info("Current stack trace is:\n" + sw.toString());
}

Number of days between two dates in Joda-Time

DateTime  dt  = new DateTime(laterDate);        

DateTime newDate = dt.minus( new  DateTime ( previousDate ).getMillis());

System.out.println("No of days : " + newDate.getDayOfYear() - 1 );    

How to add a new schema to sql server 2008?

Best way to add schema to your existing table: Right click on the specific table-->Design --> Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.

Spark java.lang.OutOfMemoryError: Java heap space

You should configure offHeap memory settings as shown below:

val spark = SparkSession
     .builder()
     .master("local[*]")
     .config("spark.executor.memory", "70g")
     .config("spark.driver.memory", "50g")
     .config("spark.memory.offHeap.enabled",true)
     .config("spark.memory.offHeap.size","16g")   
     .appName("sampleCodeForReference")
     .getOrCreate()

Give the driver memory and executor memory as per your machines RAM availability. You can increase the offHeap size if you are still facing the OutofMemory issue.

How can I specify my .keystore file with Spring Boot and Tomcat?

If you don't want to implement your connector customizer, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer. According to the README, you only have to create your keystore, configure connector.https.*, import the library and add @ComponentScan("org.ycavatars.sboot.kit"). Then you'll have HTTPS connection.

How to fire an event when v-model changes?

You can actually simplify this by removing the v-on directives:

<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">

And use the watch method to listen for the change:

new Vue ({
    el: "#app",
    data: {
        cases: [
            { name: 'case A', status: '1' },
            { name: 'case B', status: '0' },
            { name: 'case C', status: '1' }
        ],
        activeCases: [],
        srStatus: ''
    },
    watch: {
        srStatus: function(val, oldVal) {
            for (var i = 0; i < this.cases.length; i++) {
                if (this.cases[i].status == val) {
                    this.activeCases.push(this.cases[i]);
                    alert("Fired! " + val);
                }
            }
        }
    }
});

The total number of locks exceeds the lock table size

This issue can be resolved by setting the higher values for the MySQL variable innodb_buffer_pool_size. The default value for innodb_buffer_pool_size will be 8,388,608.

To change the settings value for innodb_buffer_pool_size please see the below set.

  1. Locate the file my.cnf from the server. For Linux servers this will be mostly at /etc/my.cnf
  2. Add the line innodb_buffer_pool_size=64MB to this file
  3. Restart the MySQL server

To restart the MySQL server, you can use anyone of the below 2 options:

  1. service mysqld restart
  2. /etc/init.d/mysqld restart

Reference The total number of locks exceeds the lock table size

How to create an infinite loop in Windows batch file?

Here is an example of using the loop:

echo off
cls

:begin

set /P M=Input text to encode md5, press ENTER to exit: 
if %M%==%M1% goto end

echo.|set /p ="%M%" | openssl md5

set M1=%M%
Goto begin

This is the simple batch i use when i need to encrypt any message into md5 hash on Windows(openssl required), and the program would loyally repeat itself except given Ctrl+C or empty input.

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

Windows command for file size only

Try forfiles:

forfiles /p C:\Temp /m file1.txt /c "cmd /c echo @fsize"

The forfiles command runs command c for each file m in directory p.

The variable @fsize is replaced with the size of each file.

If the file C:\Temp\file1.txt is 27 bytes, forfiles runs this command:

cmd /c echo 27

Which prints 27 to the screen.

As a side-effect, it clears your screen as if you had run the cls command.

Algorithm for solving Sudoku

Here is a much faster solution based on hari's answer. The basic difference is that we keep a set of possible values for cells that don't have a value assigned. So when we try a new value, we only try valid values and we also propagate what this choice means for the rest of the sudoku. In the propagation step, we remove from the set of valid values for each cell the values that already appear in the row, column, or the same block. If only one number is left in the set, we know that the position (cell) has to have that value.

This method is known as forward checking and look ahead (http://ktiml.mff.cuni.cz/~bartak/constraints/propagation.html).

The implementation below needs one iteration (calls of solve) while hari's implementation needs 487. Of course my code is a bit longer. The propagate method is also not optimal.

import sys
from copy import deepcopy

def output(a):
    sys.stdout.write(str(a))

N = 9

field = [[5,1,7,6,0,0,0,3,4],
         [2,8,9,0,0,4,0,0,0],
         [3,4,6,2,0,5,0,9,0],
         [6,0,2,0,0,0,0,1,0],
         [0,3,8,0,0,6,0,4,7],
         [0,0,0,0,0,0,0,0,0],
         [0,9,0,0,0,0,0,7,8],
         [7,0,3,4,0,0,5,6,0],
         [0,0,0,0,0,0,0,0,0]]

def print_field(field):
    if not field:
        output("No solution")
        return
    for i in range(N):
        for j in range(N):
            cell = field[i][j]
            if cell == 0 or isinstance(cell, set):
                output('.')
            else:
                output(cell)
            if (j + 1) % 3 == 0 and j < 8:
                output(' |')

            if j != 8:
                output(' ')
        output('\n')
        if (i + 1) % 3 == 0 and i < 8:
            output("- - - + - - - + - - -\n")

def read(field):
    """ Read field into state (replace 0 with set of possible values) """

    state = deepcopy(field)
    for i in range(N):
        for j in range(N):
            cell = state[i][j]
            if cell == 0:
                state[i][j] = set(range(1,10))

    return state

state = read(field)


def done(state):
    """ Are we done? """

    for row in state:
        for cell in row:
            if isinstance(cell, set):
                return False
    return True


def propagate_step(state):
    """
    Propagate one step.

    @return:  A two-tuple that says whether the configuration
              is solvable and whether the propagation changed
              the state.
    """

            new_units = False

    # propagate row rule
    for i in range(N):
        row = state[i]
        values = set([x for x in row if not isinstance(x, set)])
        for j in range(N):
            if isinstance(state[i][j], set):
                state[i][j] -= values
                if len(state[i][j]) == 1:
                    val = state[i][j].pop()
                    state[i][j] = val
                    values.add(val)
                    new_units = True
                elif len(state[i][j]) == 0:
                    return False, None

    # propagate column rule
    for j in range(N):
        column = [state[x][j] for x in range(N)]
        values = set([x for x in column if not isinstance(x, set)])
        for i in range(N):
            if isinstance(state[i][j], set):
                state[i][j] -= values
                if len(state[i][j]) == 1:
                    val = state[i][j].pop()
                    state[i][j] = val
                    values.add(val)
                    new_units = True
                elif len(state[i][j]) == 0:
                    return False, None

    # propagate cell rule
    for x in range(3):
        for y in range(3):
            values = set()
            for i in range(3 * x, 3 * x + 3):
                for j in range(3 * y, 3 * y + 3):
                    cell = state[i][j]
                    if not isinstance(cell, set):
                        values.add(cell)
            for i in range(3 * x, 3 * x + 3):
                for j in range(3 * y, 3 * y + 3):
                    if isinstance(state[i][j], set):
                        state[i][j] -= values
                        if len(state[i][j]) == 1:
                            val = state[i][j].pop()
                            state[i][j] = val
                            values.add(val)
                            new_units = True
                        elif len(state[i][j]) == 0:
                            return False, None

    return True, new_units

def propagate(state):
    """ Propagate until we reach a fixpoint """
    while True:
        solvable, new_unit = propagate_step(state)
        if not solvable:
            return False
        if not new_unit:
            return True


def solve(state):
    """ Solve sudoku """

    solvable = propagate(state)

    if not solvable:
        return None

    if done(state):
        return state

    for i in range(N):
        for j in range(N):
            cell = state[i][j]
            if isinstance(cell, set):
                for value in cell:
                    new_state = deepcopy(state)
                    new_state[i][j] = value
                    solved = solve(new_state)
                    if solved is not None:
                        return solved
                return None

print_field(solve(state))

How to compile C program on command line using MinGW?

If you pasted your text into the path variable and added a whitespace before the semicolon, you should delete that and add a backslash at the end of the directory (;C:\Program Files (x86)\CodeBlocks\MinGW\bin

Wait for shell command to complete

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)

How to convert unsigned long to string

For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,

as a reference of available options see sprintf

#include <stdio.h>

    int main ()
    {
      unsigned long lval = 123;
      char buffer [50];
      sprintf (buffer, "%lu" , lval );
     }

Set the value of a variable with the result of a command in a Windows batch file

Set "dateTime="
For /F %%A In ('powershell get-date -format "{yyyyMMdd_HHmm}"') Do Set "dateTime=%%A"
echo %dateTime%
pause

enter image description here Official Microsoft docs for for command

Leave out quotes when copying from cell

It's also possible to remove these double-quotes by placing your result on the "Clean" function.

Example:

=CLEAN("1"&CHAR(9)&"SOME NOTES FOR LINE 1."&CHAR(9)&"2"&CHAR(9)&"SOME NOTES FOR LINE 2.")

The output will be pasted without the double-quotes on other programs such as Notepad++.

C++ initial value of reference to non-const must be an lvalue

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

Is there a way to instantiate a class by name in Java?

something like this should work...

String name = "Test2";//Name of the class
        Class myClass = Class.forName(name);
        Object o = myClass.newInstance();

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

In addition to the steps you have already taken, you will need to set the recovery mode to simple before you can shrink the log.

THIS IS NOT A RECOMMENDED PRACTICE for production systems... You will lose your ability to recover to a point in time from previous backups/log files.

See example B on this DBCC SHRINKFILE (Transact-SQL) msdn page for an example, and explanation.

How npm start runs a server on port 8000

npm start -- --port "port number"

Delay/Wait in a test case of Xcode UI testing

Edit:

It actually just occurred to me that in Xcode 7b4, UI testing now has expectationForPredicate:evaluatedWithObject:handler:

Original:

Another way is to spin the run loop for a set amount of time. Really only useful if you know how much (estimated) time you'll need to wait for

Obj-C: [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow: <<time to wait in seconds>>]]

Swift: NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow: <<time to wait in seconds>>))

This is not super useful if you need to test some conditions in order to continue your test. To run conditional checks, use a while loop.

Java ArrayList of Doubles

double[] arr = new double[] {1.38, 2.56, 4.3};

ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
    Collectors.toCollection( new Supplier<ArrayList<Double>>() {
      public ArrayList<Double> get() {
        return( new ArrayList<Double>() );
      }
    } ) );

Anybody knows any knowledge base open source?

Here comes another vote in favor of PHPKB knowledge base software. We came to know about PHPKB from this post on StackOverflow and bought it as recommended by Julien and Ricardo. I am glad to inform that it was a right decision. Although we had to get certain features customized according to our needs but their support team exceeded our expectations. So, I just thought of sharing the news here. We are fully satisfied with PHPKB knowledge base software.

Testing two JSON objects for equality ignoring child order in Java

I know it is usually considered only for testing but you could use the Hamcrest JSON comparitorSameJSONAs in Hamcrest JSON.

Hamcrest JSON SameJSONAs

How to remove leading zeros from alphanumeric text?

You can use the StringUtils class from Apache Commons Lang like this:

StringUtils.stripStart(yourString,"0");

How to change UINavigationBar background color from the AppDelegate

You can use [[UINavigationBar appearance] setTintColor:myColor];

Since iOS 7 you need to set [[UINavigationBar appearance] setBarTintColor:myColor]; and also [[UINavigationBar appearance] setTranslucent:NO].

[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];

Disallow Twitter Bootstrap modal window from closing

$(document).ready(function(e){

  $("#modalId").modal({
     backdrop: 'static',
     keyboard: false,
     show: false
  });

});

"backdrop:'static'" will prevent closing modal when clicking outside of it; "keyboard: false" specifies that the modal can be closed from escape key (Esc) "show: false" will hide the modal when the page has finished loading

Delete many rows from a table using id in Mysql

Hope it helps:

DELETE FROM tablename 
WHERE tablename.id = ANY (SELECT id FROM tablename WHERE id = id);

Cannot read property 'style' of undefined -- Uncaught Type Error

It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
  if (window.location.href.indexOf("test") <= -1) {_x000D_
    var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
    search_span[0].style.color = "blue";_x000D_
    search_span[0].style.fontWeight = "bold";_x000D_
    search_span[0].style.fontSize = "40px";_x000D_
_x000D_
  }_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_

Execute SQL script from command line

If you want to run the script file then use below in cmd

sqlcmd -U user -P pass  -S servername -d databasename -i "G:\Hiren\Lab_Prodution.sql"

Check if string has space in between (or anywhere)

Trim() will only remove leading or trailing spaces.

Try .Contains() to check if a string contains white space

"sossjjs sskkk".Contains(" ") // returns true

SyntaxError: non-default argument follows default argument

As the error message says, non-default argument til should not follow default argument hgt.

Changing order of parameters (function call also be adjusted accordingly) or making hgt non-default parameter will solve your problem.

def a(len1, hgt=len1, til, col=0):

->

def a(len1, hgt, til, col=0):

UPDATE

Another issue that is hidden by the SyntaxError.

os.system accepts only one string parameter.

def a(len1, hgt, til, col=0):
    system('mode con cols=%s lines=%s' % (len1, hgt))
    system('title %s' % til)
    system('color %s' % col)

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Was able to solve the issue by adding "startup" element with "useLegacyV2RuntimeActivationPolicy" attribute set.

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    <supportedRuntime version="v2.0.50727"/>
</startup>

But had to place it as the first child element of configuration tag in App.config for it to take effect.

<?xml version="1.0"?>
  <configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
      <supportedRuntime version="v2.0.50727"/>
    </startup>
  ......
....

Populate a Drop down box from a mySQL table in PHP

No need to do this:

while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;
}

You can directly do this:

while ($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row['value'] . "'>" . $row['value'] . "</option>";
    }

"R cannot be resolved to a variable"?

I had this problem and none of the other guides helped, and then I realized I didn't have the java jdk installed on my system. If you haven't done this either go download the version corresponding to the version of eclipse you installed (x86 or x64)

Notepad++ incrementally replace

i had the same problem with more than 250 lines and here is how i did it:

for example :

<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />

you put the cursor just after the "1" and you click on alt + shift and start descending with down arrow until your reach the bottom line now you see a group of selections click on erase to erase the number 1 on each line simultaneously and go to Edit -> Column Editor and select Number to Insert then put 1 in initial number field and 1 in incremented by field and check zero numbers and click ok

Congratulations you did it :)

Make absolute positioned div expand parent div height

I had a similar problem. To solve this (instead of calculate the iframe's height using the body, document or window) I created a div that wraps the whole page content (a div with an id="page" for example) and then I used its height.

Nesting queries in SQL

If it has to be "nested", this would be one way, to get your job done:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

How to instantiate, initialize and populate an array in TypeScript?

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

What does 'foo' really mean?

The sound of the french fou, (like: amour fou) [crazy] written in english, would be foo, wouldn't it. Else furchtbar -> foobar -> foo, bar -> barfoo -> barfuß (barefoot). Just fou. A foot without teeth.

I agree with all, who mentioned it means: nothing interesting, just something, usually needed to complete a statement/expression.

Axios get access to response header fields

This really helped me, thanks Nick Uraltsev for your answer.

For those of you using nodejs with cors:

...
const cors = require('cors');

const corsOptions = {
  exposedHeaders: 'Authorization',
};

app.use(cors(corsOptions));
...

In the case you are sending the response in the way of res.header('Authorization', `Bearer ${token}`).send();

Parsing jQuery AJAX response

Since you are using $.ajax, and not $.getJSON, your return type is plain text. you need to now convert data into a JSON object.

you can either do this by changing your $.ajax to $.getJSON (which is a shorthand for $.ajax, only preconfigured to fetch json).

Or you can parse the data string into JSON after you receive it, like so:

    success: function (data) {
         var obj = $.parseJSON(data);
         console.log(obj);
    },

How do I find out which DOM element has the focus?

I have found the following snippet to be useful when trying to determine which element currently has focus. Copy the following into the console of your browser, and every second it will print out the details of the current element that has focus.

setInterval(function() { console.log(document.querySelector(":focus")); }, 1000);

Feel free to modify the console.log to log out something different to help you pinpoint the exact element if printing out the whole element does not help you pinpoint the element.

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

What does $_ mean in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.

PowerShell (v6.0) online documentation for automatic variables is here.

How do I use reflection to invoke a private method?

BindingFlags.NonPublic will not return any results by itself. As it turns out, combining it with BindingFlags.Instance does the trick.

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);

jQuery How do you get an image to fade in on load?

I tried the following one but didn't work;

    <span style="display: none;" id="doneimg">
        <img alt="done" title="The process has been complated successfully..." src="@Url.Content("~/Content/App_Icons/icos/tick_icon.gif")" />
    </span>

    <script type="text/javascript">
        //$(document).ready(function () {
            $("#doneimg").bind("load", function () { $(this).fadeIn('slow'); });
        //});
    </script>

bu the following one worked just fine;

<script type="text/javascript">
        $(document).ready(function () {
            $('#doneimg').fadeIn("normal");
        });
</script>

            <span style="display: none;" id="doneimg">
                <img alt="done" title="The process has been complated successfully..." src="@Url.Content("~/Content/App_Icons/icos/tick_icon.gif")" />
            </span>