Programs & Examples On #Public fields

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

There's a far more simpler solution to tackle this.

The reason why you get ValueError: Index contains duplicate entries, cannot reshape is because, once you unstack "Location", then the remaining index columns "id" and "date" combinations are no longer unique.

You can avoid this by retaining the default index column (row #) and while setting the index using "id", "date" and "location", add it in "append" mode instead of the default overwrite mode.

So use,

e.set_index(['id', 'date', 'location'], append=True)

Once this is done, your index columns will still have the default index along with the set indexes. And unstack will work.

Let me know how it works out.

How to create dynamic href in react render function?

In addition to Felix's answer,

href={`/posts/${posts.id}`}

would work well too. This is nice because it's all in one string.

How to search for a string in cell array in MATLAB?

The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))

Checking Value of Radio Button Group via JavaScript?

If you are using a javascript library like jQuery, it's very easy:

alert($('input[name=gender]:checked').val());

This code will select the checked input with gender name, and gets it's value. Simple isn't it?

Live demo

An implementation of the fast Fourier transform (FFT) in C#

http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms.

postgresql - replace all instances of a string within text field

You want to use postgresql's replace function:

replace(string text, from text, to text)

for instance :

UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')

Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.

PHP 7 simpleXML

------------------in centos-------------------------

find out which package provides php-xml:

 yum provides php-xml

then from the output list,select the appropriate one, install

yum install php70u-xml-7.0.14-2.ius.centos7.x86_64

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

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

Update for Angular 2 final version

In app.module.ts:

  • Add imports:

      import { HashLocationStrategy, LocationStrategy } from '@angular/common';
    
  • And in NgModule provider, add:

      {provide: LocationStrategy, useClass: HashLocationStrategy}
    

Example (app.module.ts):

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
})
export class AppModule {}

Alternative

Use RouterModule.forRoot with the {useHash: true} argument.

Example:(from angular docs)

import { NgModule } from '@angular/core';
...

const routes: Routes = [//routes in here];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(routes, { useHash: true })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Is there a list of screen resolutions for all Android based phones and tablets?

hdpi 480x800 px Samsung S2

xhdpi 720x1280 px - Nexus 4 phone - 4.7,4.8 inches Samsung Galaxy S3 Motorola Moto G

xxhdpi 1080x1920 px - Nexus 5 phone - 4.95 inches Samsung Galaxy S4 Samsung Galaxy S5 Samsung Galaxy Note 3 - 5.7 inches LG G2 HTC One M8 HTC One M9 Sony Xperia Z1
Sony Xperia Z2 Sony Xperia Z3 Sony Xperia Z3+

xxxhdpi 1440x2560 px - Nexus 6 phablet - 6 inches Samsung S6 Samsung S6 Edge Samsung Galaxy Note 4 - 5.7 inches LG G3
LG G4

xxhdpi 1920×1200 px - Nexus 7 tablet - 7 inches Sony Z3 Tablet Compact LG G Pad 8.3 - 8.3 inches Sony Xperia Z2 Tablet - 10.1 inches

xxxhdpi 2560×1600 px - Nexus 10 tablet - 10.1 inches ~Google Nexus 9 Sony Xperia Z4 tablet Samsung Galaxy Note Pro 12.2 Samsung Galaxy Note 10.1 Samsung Galaxy Tab S 10.5 Dell Venue 8 7840

Is there a way to call a stored procedure with Dapper?

I think the answer depends on which features of stored procedures you need to use.

Stored procedures returning a result set can be run using Query; stored procedures which don't return a result set can be run using Execute - in both cases (using EXEC <procname>) as the SQL command (plus input parameters as necessary). See the documentation for more details.

As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT parameters; you could add this, or alternatively construct a more complex Query command which declared TSQL variables, executed the SP collecting OUTPUT parameters into the local variables and finallyreturned them in a result set:

DECLARE @output int

EXEC <some stored proc> @i = @output OUTPUT

SELECT @output AS output1

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

How to check if a specified key exists in a given S3 bucket using Java

Alternatively you can use Minio-Java client library, its Open Source and compatible with AWS S3 API.

You can use Minio-Java StatObject.java examples for the same.

import io.minio.MinioClient;
import io.minio.errors.MinioException;

import java.io.InputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;

import org.xmlpull.v1.XmlPullParserException;


public class GetObject {
  public static void main(String[] args)
    throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException, MinioException {
    // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY and my-bucketname are
    // dummy values, please replace them with original values.
    // Set s3 endpoint, region is calculated automatically
    MinioClient s3Client = new MinioClient("https://s3.amazonaws.com", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY");
    InputStream stream = s3Client.getObject("my-bucketname", "my-objectname");

    byte[] buf = new byte[16384];
    int bytesRead;
    while ((bytesRead = stream.read(buf, 0, buf.length)) >= 0) {
      System.out.println(new String(buf, 0, bytesRead));
    }

    stream.close();
  }
}

I hope it helps.

Disclaimer : I work for Minio

Purpose of Unions in C and C++

The most common use of union I regularly come across is aliasing.

Consider the following:

union Vector3f
{
  struct{ float x,y,z ; } ;
  float elts[3];
}

What does this do? It allows clean, neat access of a Vector3f vec;'s members by either name:

vec.x=vec.y=vec.z=1.f ;

or by integer access into the array

for( int i = 0 ; i < 3 ; i++ )
  vec.elts[i]=1.f;

In some cases, accessing by name is the clearest thing you can do. In other cases, especially when the axis is chosen programmatically, the easier thing to do is to access the axis by numerical index - 0 for x, 1 for y, and 2 for z.

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

Set markers for individual points on a line in Matplotlib

You can do:

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, style='.-')
plt.show()

This will return a graph with the data points marked with a dot

Accessing value inside nested dictionaries

You can use the get() on each dict. Make sure that you have added the None check for each access.

How do I detect a click outside an element?

All of these answers solve the problem, but I would like to contribute with a moders es6 solution that does exactly what is needed. I just hope to make someone happy with this runnable demo.

_x000D_
_x000D_
window.clickOutSide = (element, clickOutside, clickInside) => {
  document.addEventListener('click', (event) => {
    if (!element.contains(event.target)) {
      if (typeof clickInside === 'function') {
        clickOutside();
      }
    } else {
      if (typeof clickInside === 'function') {
        clickInside();
      }
    }
  });
};

window.clickOutSide(document.querySelector('.block'), () => alert('clicked outside'), () => alert('clicked inside'));
_x000D_
.block {
  width: 400px;
  height: 400px;
  background-color: red;
}
_x000D_
<div class="block"></div>
_x000D_
_x000D_
_x000D_

CRC32 C or C++ implementation

The most simple and straightforward C/C++ implementation that I found is in a link at the bottom of this page:

Web Page: http://www.barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code

Code Download Link: https://barrgroup.com/code/crc.zip

It is a simple standalone implementation with one .h and one .c file. There is support for CRC32, CRC16 and CRC_CCITT thru the use of a define. Also, the code lets the user change parameter settings like the CRC polynomial, initial/final XOR value, and reflection options if you so desire.

The license is not explicitly defined ala LGPL or similar. However the site does say that they are placing the code in the public domain for any use. The actual code files also say this.

Hope it helps!

What is the garbage collector in Java?

As objects are dynamically allocated by the new operator, you can ask how these objects are destroyed and how busy memory is freed. In other languages such as C++, you need to free manually allocated objects dynamically by the delete operator. Java has a different approach; it automatically handles deallocation. The technique is known as Garbage Collection.

It works like this: when there are no references to an object, it is assumed that this object is no longer needed and you can retrieve the memory occupied by the object. It is not necessary to explicitly destroy objects as in C++. Garbage collection occurs sporadically during program execution; It does not simply happen because there are one or more objects that are no longer used. In addition, several Java runtime implementations have different approaches to garbage collection, but most programmers do not have to worry about this when writing programs.

How to programmatically round corners and set random background colors

Copying @cimlman's comment into a top-level answer for more visibility:

PaintDrawable(Color.CYAN).apply {
  setCornerRadius(24f)
}

FYI: ShapeDrawable (and its subtype, PaintDrawable) uses default intrinsic width and height of 0. If the drawable does not show up in your usecase, you might have to set the dimensions manually:

PaintDrawable(Color.CYAN).apply {
  intrinsicWidth = -1
  intrinsicHeight = -1
  setCornerRadius(24f)
}

-1 is a magic constant which indicates that a Drawable has no intrinsic width and height of its own (Source).

Return multiple values to a method caller

In C#7 There is a new Tuple syntax:

static (string foo, int bar) GetTuple()
{
    return ("hello", 5);
}

You can return this as a record:

var result = GetTuple();
var foo = result.foo
// foo == "hello"

You can also use the new deconstructor syntax:

(string foo) = GetTuple();
// foo == "hello"

Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a Tuple<string, int> (as per the accepted answer) with Item1 and Item2 instead of foo and bar. That means that serialisation (or deserialisation) will use those property names instead.

So, for serialisation declare a record class and return that instead.

Also new in C#7 is an improved syntax for out parameters. You can now declare the out inline, which is better suited in some contexts:

if(int.TryParse("123", out int result)) {
    // Do something with result
}

However, mostly you'll use this in .NET's own libraries, rather than in you own functions.

How to run the Python program forever?

Here is the complete syntax,

#!/usr/bin/python3

import time 

def your_function():
    print("Hello, World")

while True:
    your_function()
    time.sleep(10) #make function to sleep for 10 seconds

How to go back (ctrl+z) in vi/vim

Just in normal mode press:

  • u - undo,
  • Ctrl + r - redo changes which were undone (undo the undos).

Undo and Redo

What in the world are Spring beans?

Well you understood it partially. You have to tailor the beans according to your need and inform Spring container to manage it when required, by using a methodology populalrly known as IoC (Inversion of Control) coined by Martin Fowler, also known as Dependency Injection (DI).

You wire the beans in a way, so that you do not have to take care of the instantiating or evaluate any dependency on the bean. This is popularly known as Hollywood Principle.

Google is the best tool to explore more on this in addition to the links you would get flooded with here in this question. :)

how to return index of a sorted list?

Straight out of the documentation for collections.OrderedDict:

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

Adapted to the example in the original post:

>>> l=[2,3,1,4,5]
>>> OrderedDict(sorted(enumerate(l), key=lambda x: x[1])).keys()
[2, 0, 1, 3, 4]

See http://docs.python.org/library/collections.html#collections.OrderedDict for details.

Link to reload current page

I have been using:

<a href=".">link</a>

Have yet to find a case and/or browser where it does not work as intended.

Period means the current path. You can also use .. to refer to the folder above the current path, for instance, if you have this file structure:

page1.html
folder1
    page2.html

You can then in page2.html write:

<a href="../page1.html">link to page 1</a>

EDIT:

I'm not sure if the behaviour has changed or if it was always like this, but Chrome (and maybe others) will treat periods as described above as regarding directories, not files. This means that if you are at http://example.com/foo/bar.html you are really in the directory /foo/ and a href value of . in bar.html will refer to /foo/ rather than bar.html

Think of it as navigating the file system in a terminal; you can never cd into a file :)

EDIT 2:

It seems like the behaviour of using href="." is not as predictable anymore, both Firefox and Chrome might have changed how they handle these. I wouldn't rely entirely on my original answer, but rather try both the empty string and the period in different browsers for your specific use and make sure you get the desired behaviour.

How to bind to a PasswordBox in MVVM

To solve the OP problem without breaking the MVVM, I would use custom value converter and a wrapper for the value (the password) that has to be retrieved from the password box.

public interface IWrappedParameter<T>
{
    T Value { get; }
}

public class PasswordBoxWrapper : IWrappedParameter<string>
{
    private readonly PasswordBox _source;

    public string Value
    {
        get { return _source != null ? _source.Password : string.Empty; }
    }

    public PasswordBoxWrapper(PasswordBox source)
    {
        _source = source;
    }
}

public class PasswordBoxConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Implement type and value check here...
        return new PasswordBoxWrapper((PasswordBox)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new InvalidOperationException("No conversion.");
    }
}

In the view model:

public string Username { get; set; }

public ICommand LoginCommand
{
    get
    {
        return new RelayCommand<IWrappedParameter<string>>(password => { Login(Username, password); });
    }
}

private void Login(string username, string password)
{
    // Perform login here...
}

Because the view model uses IWrappedParameter<T>, it does not need to have any knowledge about PasswordBoxWrapper nor PasswordBoxConverter. This way you can isolate the PasswordBox object from the view model and not break the MVVM pattern.

In the view:

<Window.Resources>
    <h:PasswordBoxConverter x:Key="PwdConverter" />
</Window.Resources>
...
<PasswordBox Name="PwdBox" />
<Button Content="Login" Command="{Binding LoginCommand}"
        CommandParameter="{Binding ElementName=PwdBox, Converter={StaticResource PwdConverter}}" />

AngularJS : Difference between the $observe and $watch methods

If I understand your question right you are asking what is difference if you register listener callback with $watch or if you do it with $observe.

Callback registerd with $watch is fired when $digest is executed.

Callback registered with $observe are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}").


Inside directive you can use both of them on very similar way:

    attrs.$observe('attrYouWatch', function() {
         // body
    });

or

    scope.$watch(attrs['attrYouWatch'], function() {
         // body
    });

Center an item with position: relative

Much simpler:

position: relative; 
left: 50%;
transform: translateX(-50%);

You are now centered in your parent element. You can do that vertically too.

How to handle the modal closing event in Twitter Bootstrap?

Updated for Bootstrap 3 and 4

Bootstrap 3 and Bootstrap 4 docs refer two events you can use.

hide.bs.modal: This event is fired immediately when the hide instance method has been called.
hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

And provide an example on how to use them:

$('#myModal').on('hidden.bs.modal', function () {
  // do something…
})

Legacy Bootstrap 2.3.2 answer

Bootstrap's documentation refers two events you can use.

hide: This event is fired immediately when the hide instance method has been called.
hidden: This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).

And provides an example on how to use them:

$('#myModal').on('hidden', function () {
    // do something…
})

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

SELECT Convert(varchar(10),CONVERT(date,'columnname',105),105) as "end";

OR

SELECT CONVERT(VARCHAR(10), CAST(event_enddate AS DATE), 105) AS [end];

will return the particular date in the format of 'dd-mm-yyyy'

The result would be like this..

04-07-2016

How to change the foreign key referential action? (behavior)

I had a bunch of FKs to alter, so I wrote something to make the statements for me. Figured I'd share:

SELECT

CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` DROP FOREIGN KEY `' ,rc.CONSTRAINT_NAME,'`;')
, CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` ADD CONSTRAINT `' ,rc.CONSTRAINT_NAME ,'` FOREIGN KEY (`',kcu.COLUMN_NAME,
    '`) REFERENCES `',kcu.REFERENCED_TABLE_NAME,'` (`',kcu.REFERENCED_COLUMN_NAME,'`) ON DELETE CASCADE;')

FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
    ON kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
    AND kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
WHERE DELETE_RULE = 'NO ACTION'
AND rc.CONSTRAINT_SCHEMA = 'foo'

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

Passing an array by reference in C?

Arrays are effectively passed by reference by default. Actually the value of the pointer to the first element is passed. Therefore the function or method receiving this can modify the values in the array.

void SomeMethod(Coordinate Coordinates[]){Coordinates[0].x++;};
int main(){
  Coordinate tenCoordinates[10];
  tenCoordinates[0].x=0;
  SomeMethod(tenCoordinates[]);
  SomeMethod(&tenCoordinates[0]);
  if(0==tenCoordinates[0].x - 2;){
    exit(0);
  }
  exit(-1);
}

The two calls are equivalent, and the exit value should be 0;

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

In most cases, it is enough just to hide the element, for example in this way:

export default class ErrorBoxComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isHidden: false
        }
    }

    dismiss() {
        this.setState({
            isHidden: true
        })
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Or you may render/rerender/not render via parent component like this

export default class ParentComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isErrorShown: true
        }
    }

    dismiss() {
        this.setState({
            isErrorShown: false
        })
    }

    showError() {
        if (this.state.isErrorShown) {
            return <ErrorBox 
                error={ this.state.error }
                dismiss={ this.dismiss.bind(this) }
            />
        }

        return null;
    }

    render() {

        return (
            <div>
                { this.showError() }
            </div>
        );
    }
}

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.props.dismiss();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box">
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.el.remove();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

SyntaxError: "can't assign to function call"

You wrote the assignment backward: to assign a value (or an expression) to a variable you must have that variable at the left side of the assignment operator ( = in python )

subsequent_amount = invest(initial_amount,top_company(5,year,year+1))

Adding a new array element to a JSON object

In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.

  elementToPush = [1, 2, 3]
  if (!obj.arr) this.$set(obj, "arr", [])
  obj.arr.push(elementToPush)  

(This answer may not be relevant to this particular question, but may help someone else)

Android: combining text & image on a Button or ImageButton

Probably my solution will suit for a lot of users, I hope so.

What I am suggesting it is making TextView with your style. It works for me perfectly, and has got all features, like a button.

First of all lets make button style, which you can use everywhere...I am creating button_with_hover.xml

    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="#8dbab3" />
            <gradient android:angle="-90" android:startColor="#48608F" android:endColor="#48608F"  />
        </shape>

        <!--#284682;-->
        <!--border-color: #223b6f;-->
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="#284682" />
            <solid android:color="#284682"/>
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="@color/ControlColors" />
            <gradient android:angle="-90" android:startColor="@color/ControlColors" android:endColor="@color/ControlColors" />
        </shape>
    </item>

</selector>

Secondly, Lets create a textview button.

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dip"
    android:layout_gravity="right|bottom"
    android:gravity="center"
    android:padding="12dip"
    android:background="@drawable/button_with_hover"
    android:clickable="true"
    android:drawableLeft="@android:drawable/btn_star_big_off"
    android:textColor="#ffffffff"
    android:text="Golden Gate" />

And this is a result. Then style your custom button with any colors or any other properties and margins. Good luck

enter image description here

Reset AutoIncrement in SQL Server after Delete

Issue the following command to reseed mytable to start at 1:

DBCC CHECKIDENT (mytable, RESEED, 0)

Read about it in the Books on Line (BOL, SQL help). Also be careful that you don't have records higher than the seed you are setting.

How to find the port for MS SQL Server 2008?

USE master
GO
xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc' 
GO

[Identify Port used by Named Instance of SQL Server Database Engine by Reading SQL Server Error Logs]

How to load a resource from WEB-INF directory of a web archive

Use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

How to solve java.lang.OutOfMemoryError trouble in Android

I see only two options:

  1. You have memory leaks in your application.
  2. Devices do not have enough memory when running your application.

How do I display todays date on SSRS report?

date column 1:

=formatdatetime(today)

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

example:

c++ -Wall filefork.cpp -lrt -O2

For gcc version 4.6.1, -lrt must be after filefork.cpp otherwise you get a link error.

Some older gcc version doesn't care about the position.

Android "hello world" pushnotification example

Update 2016:

GCM is being replaced with FCM

Update 2015:

Have a look at developers.android.com - Google replaced C2DM with GCM Demo Implementation / How To

Update 2014:

1) You need to check on the server what HTTP response you are getting from the Google servers. Make sure it is a 200 OK response, so you know the message was sent. If you get another response (302, etc) then the message is not being sent successfully.

2) You also need to check that the Registration ID you are using is correct. If you provide the wrong Registration ID (as a destination for the message - specifying the app, on a specific device) then the Google servers cannot successfully send it.

3) You also need to check that your app is successfully registering with the Google servers, to receive push notifications. If the registration fails, you will not receive messages.

First Answer 2014

Here is a good question you may should have a look at it: How to add a push notification in my own android app

Also here is a good blog with a really simple how to: http://blog.serverdensity.com/android-push-notifications-tutorial/

PHP check if file is an image

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_open')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}

Get the decimal part from a double

var result = number.ToString().Split(System.Globalization.NumberDecimalSeparator)[2]

Returns it as a string (but you can always cast that back to an int), and assumes the number does have a "." somewhere.

How to remove first and last character of a string?

In Kotlin

private fun removeLastChar(str: String?): String? {
    return if (str == null || str.isEmpty()) str else str.substring(0, str.length - 1)
}

Fragment MyFragment not attached to Activity

Their are quite trick solution for this and leak of fragment from activity.

So in case of getResource or anything one which is depending on activity context accessing from Fragment it is always check activity status and fragments status as follows

 Activity activity = getActivity(); 
    if(activity != null && isAdded())

         getResources().getString(R.string.no_internet_error_msg);
//Or any other depends on activity context to be live like dailog


        }
    }

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

The easiest way for me to convert a date was to stringify it then slice it.

var event = new Date("Fri Apr 05 2019 16:59:00 GMT-0700 (Pacific Daylight Time)");

let date = JSON.stringify(event)
date = date.slice(1,11)

// console.log(date) = '2019-04-05'

Http Post request with content type application/x-www-form-urlencoded not working in Spring

you should replace @RequestBody with @RequestParam, and do not accept parameters with a java entity.

Then you controller is probably like this:

@RequestMapping(value = "/patientdetails", method = RequestMethod.POST, 
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody List<PatientProfileDto> getPatientDetails(
    @RequestParam Map<String, String> name) {
   List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
   ...
   PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
   ...
   list = service.getPatient(patientProfileDto);
   return list;
}

How to overwrite the output directory in spark

The documentation for the parameter spark.files.overwrite says this: "Whether to overwrite files added through SparkContext.addFile() when the target file exists and its contents do not match those of the source." So it has no effect on saveAsTextFiles method.

You could do this before saving the file:

val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://localhost:9000"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }

Aas explained here: http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html

IE and Edge fix for object-fit: cover;

There is no rule to achieve that using CSS only, besides the object-fit (that you are currently using), which has partial support in EDGE1 so if you want to use this in IE, you have to use a object-fit polyfill in case you want to use just the element img, otherwise you have to do some workarounds.

You can see the the object-fit support here

UPDATE(2019)

You can use a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

_x000D_
_x000D_
//ES6 version
if ('objectFit' in document.documentElement.style === false) {
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('img[data-object-fit]').forEach(image => {
            (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
            image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
        })
    })
}

//ES5 version transpiled from code above with BabelJS
if ('objectFit' in document.documentElement.style === false) {
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
            (image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
            image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
        });
    });
}
_x000D_
img {
  display: inline-flex;
  width: 175px;
  height: 175px;
  margin-right: 10px;
  border: 1px solid red
}

[data-object-fit='cover'] {
  object-fit: cover
}

[data-object-fit='contain'] {
  object-fit: contain
}
_x000D_
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />
_x000D_
_x000D_
_x000D_

UPDATE(2018)

1 - EDGE has now partial support for object-fit since version 16, and by partial, it means only works in img element (future version 18 still has only partial support)

SS

How to get the text node of an element?

You can get the nodeValue of the first childNode using

$('.title')[0].childNodes[0].nodeValue

http://jsfiddle.net/TU4FB/

iOS: Compare two dates

I take it you are asking what the return value is in the comparison function.

If the dates are equal then returning NSOrderedSame

If ascending ( 2nd arg > 1st arg ) return NSOrderedAscending

If descending ( 2nd arg < 1st arg ) return NSOrderedDescending

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

The separate XML solution never worked for me and other's recently ...

I usually follow this process and something helps:

  1. Stop the server (Make sure its stopped via Task Manager, I killed javaw.exe as many times Eclipse doesn't really shut down properly)
  2. Right click the Server->'Add and Remove'. Remove the project. Finish.
  3. Right click the Server->'Add and Remove'. Add the project. Finish.
  4. Restart see if works, if not continue
  5. Double click the Server... See where its getting published (Server Path: which I think goes to a tmp# directory for me since I use an already-installed Tomcat instance I re-use, not sure if would be different if use Eclipse's internal/bundled tomcat server)
  6. Right click on Server and 'Clean' ... Last one worked for me last time (so may want to try this first), Adding/Removing project worked for me other times. If doesn't work, continue ...
  7. Delete all files from the Server Path and see if all files actually get built and published there (/WEB-INF/classes and other regular files in / webroot).
  8. Restart Eclipse and/or machine (not sure I ever needed to get to this point)

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

Cross field validation with Hibernate Validator (JSR 303)

If you’re using the Spring Framework then you can use the Spring Expression Language (SpEL) for that. I’ve wrote a small library that provides JSR-303 validator based on SpEL – it makes cross-field validations a breeze! Take a look at https://github.com/jirutka/validator-spring.

This will validate length and equality of the password fields.

@SpELAssert(value = "pass.equals(passVerify)",
            message = "{validator.passwords_not_same}")
public class MyBean {

    @Size(min = 6, max = 50)
    private String pass;

    private String passVerify;
}

You can also easily modify this to validate the password fields only when not both empty.

@SpELAssert(value = "pass.equals(passVerify)",
            applyIf = "pass || passVerify",
            message = "{validator.passwords_not_same}")
public class MyBean {

    @Size(min = 6, max = 50)
    private String pass;

    private String passVerify;
}

Fit website background image to screen size

you can do this with this plugin http://dev.andreaseberhard.de/jquery/superbgimage/

or

   background-image:url(../IMAGES/background.jpg);

   background-repeat:no-repeat;

   background-size:cover;

with no need the prefixes of browsers. it's all ready suporterd in both of browers

SQL Server: Filter output of sp_who2

based on http://web.archive.org/web/20080218124946/http://sqlserver2005.databases.aspfaq.com/how-do-i-mimic-sp-who2.html

i have created following script ,
which resolves finding active connections to any datbase using DMV this works under sql 2005 , 2008 and 2008R2

Following script uses sys.dm_exec_sessions , sys.dm_exec_requests , sys.dm_exec_connections , sys.dm_tran_locks

Declare @dbName varchar(1000)
set @dbName='abc'

;WITH DBConn(SPID,[Status],[Login],HostName,DBName,Command,LastBatch,ProgramName)
As
(
SELECT 
    SPID = s.session_id,
    Status = UPPER(COALESCE
        (
            r.status,
            ot.task_state,
            s.status, 
        '')),
    [Login] = s.login_name,
    HostName = COALESCE
        (
            s.[host_name],
            '  .'
        ),
    DBName = COALESCE
        (
            DB_NAME(COALESCE
            (
                r.database_id,
                t.database_id
            )),
            ''
        ),
    Command = COALESCE
        (
            r.Command,
            r.wait_type,
            wt.wait_type,
            r.last_wait_type,
            ''
        ),
    LastBatch = COALESCE
        (
            r.start_time,
            s.last_request_start_time
        ),
    ProgramName = COALESCE
        (
            s.program_name, 
            ''
        )
FROM
    sys.dm_exec_sessions s
LEFT OUTER JOIN
    sys.dm_exec_requests r
ON
    s.session_id = r.session_id
LEFT OUTER JOIN
    sys.dm_exec_connections c
ON
    s.session_id = c.session_id
LEFT OUTER JOIN
(
    SELECT 
        request_session_id,
        database_id = MAX(resource_database_id)
    FROM
        sys.dm_tran_locks
    GROUP BY
        request_session_id
) t
ON
    s.session_id = t.request_session_id
LEFT OUTER JOIN
    sys.dm_os_waiting_tasks wt
ON 
    s.session_id = wt.session_id
LEFT OUTER JOIN
    sys.dm_os_tasks ot
ON 
    s.session_id = ot.session_id
LEFT OUTER JOIN
(
    SELECT
        ot.session_id,
        CPU_Time = MAX(usermode_time)
    FROM
        sys.dm_os_tasks ot
    INNER JOIN
        sys.dm_os_workers ow
    ON
        ot.worker_address = ow.worker_address
    INNER JOIN
        sys.dm_os_threads oth
    ON
        ow.thread_address = oth.thread_address
    GROUP BY
        ot.session_id
) tt
ON
    s.session_id = tt.session_id
WHERE
    COALESCE
    (
        r.command,
        r.wait_type,
        wt.wait_type,
        r.last_wait_type,
        'a'
    ) >= COALESCE
    (
        '', 
        'a'
    )
)

Select * from DBConn
where DBName like '%'+@dbName+'%'

How can I use Guzzle to send a POST request in JSON?

The answer from @user3379466 can be made to work by setting $data as follows:

$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):

$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:

echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I got this error, but mine was coming from the Toasts, not a Dialog.

I have Activity and Fragments in my layout. Code for the Toast was in the Activity class. Fragments gets loaded before the Activity.

I think the Toast code was hit before the Context/Activity finished initializing. I think it was the getApplicationContext() in the command Toast.makeText(getApplicationContext(), "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();

Creating and writing lines to a file

' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")

' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close

' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
    Line = File.ReadLine
    WScript.Echo(Line)
Loop
File.Close

' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close

What does the "yield" keyword do?

The yield keyword is going to replace return in a function definition to create a generator.

def create_generator():
   for i in range(100):
   yield i
myGenerator = create_generator()
print(myGenerator)
# <generator object create_generator at 0x102dd2480>
for i in myGenerator:
   print(i) # prints 0-99

When the returned generator is first used—not in the assignment but the for loop—the function definition will execute until it reaches the yield statement. There, it will pause (see why it’s called yield) until used again. Then, it will pick up where it left off. Upon the final iteration of the generator, any code after the yield command will execute.

def create_generator():
   print("Beginning of generator")
   for i in range(4):
      yield i
   print("After yield")
print("Before assignment")

myGenerator = create_generator()

print("After assignment")
for i in myGenerator :
   print(i) # prints 0-3
"""
Before assignment
After assignment
Beginning of generator
0
1
2
After yield

The yield keyword modifies a function’s behavior to produce a generator that’s paused at each yield command during iteration. The function isn’t executed except upon iteration, which leads to improved resource management, and subsequently, a better overall performance. Use generators (and yielded functions) for creating large data sets meant for single-use iteration.

How to change the icon of .bat file programmatically?

You could use a Bat to Exe converter from here:

http://www.f2ko.de/en/b2e.php

This will convert your batch file to an executable, then you can set the icon for the converted file.

Select SQL results grouped by weeks

Base on @increddibelly answer, I applied to my query as below.

I share for whom concerned.

My table structure FamilyData(Id, nodeTime, totalEnergy)

select
   sum(totalEnergy) as TotalEnergy,
   DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)

Open Popup window using javascript

Change the window name in your two different calls:

function popitup(url,windowName) {
       newwindow=window.open(url,windowName,'height=200,width=150');
       if (window.focus) {newwindow.focus()}
       return false;
     }

windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.

class << self idiom in Ruby

First, the class << foo syntax opens up foo's singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.

a = 'foo'
class << a
  def inspect
    '"bar"'
  end
end
a.inspect   # => "bar"

a = 'foo'   # new object, new singleton class
a.inspect   # => "foo"

Now, to answer the question: class << self opens up self's singleton class, so that methods can be redefined for the current self object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods:

class String
  class << self
    def value_of obj
      obj.to_s
    end
  end
end

String.value_of 42   # => "42"

This can also be written as a shorthand:

class String
  def self.value_of obj
    obj.to_s
  end
end

Or even shorter:

def String.value_of obj
  obj.to_s
end

When inside a function definition, self refers to the object the function is being called with. In this case, class << self opens the singleton class for that object; one use of that is to implement a poor man's state machine:

class StateMachineExample
  def process obj
    process_hook obj
  end

private
  def process_state_1 obj
    # ...
    class << self
      alias process_hook process_state_2
    end
  end

  def process_state_2 obj
    # ...
    class << self
      alias process_hook process_state_1
    end
  end

  # Set up initial state
  alias process_hook process_state_1
end

So, in the example above, each instance of StateMachineExample has process_hook aliased to process_state_1, but note how in the latter, it can redefine process_hook (for self only, not affecting other StateMachineExample instances) to process_state_2. So, each time a caller calls the process method (which calls the redefinable process_hook), the behaviour changes depending on what state it's in.

Is there a CSS selector by class prefix?

CSS Attribute selectors will allow you to check attributes for a string. (in this case - a class-name)

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

(looks like it's actually at 'recommendation' status for 2.1 and 3)


Here's an outline of how I *think it works:

  • [ ] : is the container for complex selectors if you will...
  • class : 'class' is the attribute you are looking at in this case.
  • * : modifier(if any): in this case - "wildcard" indicates you're looking for ANY match.
  • test- : the value (assuming there is one) of the attribute - that contains the string "test-" (which could be anything)

So, for example:

[class*='test-'] {
  color: red;
}

You could be more specific if you have good reason, with the element too

ul[class*='test-'] > li { ... }

I've tried to find edge cases, but I see no need to use a combination of ^ and * - as * gets everything...

example: http://codepen.io/sheriffderek/pen/MaaBwp

http://caniuse.com/#feat=css-sel2

Everything above IE6 will happily obey. : )

note that:

[class] { ... }

Will select anything with a class...

What does "publicPath" in Webpack do?

the publicPath is just used for dev purpose, I was confused at first time I saw this config property, but it makes sense now that I've used webpack for a while

suppose you put all your js source file under src folder, and you config your webpack to build the source file to dist folder with output.path.

But you want to serve your static assets under a more meaningful location like webroot/public/assets, this time you can use out.publicPath='/webroot/public/assets', so that in your html, you can reference your js with <script src="/webroot/public/assets/bundle.js"></script>.

when you request webroot/public/assets/bundle.js the webpack-dev-server will find the js under the dist folder

Update:

thanks for Charlie Martin to correct my answer

original: the publicPath is just used for dev purpose, this is not just for dev purpose

No, this option is useful in the dev server, but its intention is for asynchronously loading script bundles in production. Say you have a very large single page application (for example Facebook). Facebook wouldn't want to serve all of its javascript every time you load the homepage, so it serves only whats needed on the homepage. Then, when you go to your profile, it loads some more javascript for that page with ajax. This option tells it where on your server to load that bundle from

How do I add a simple onClick event handler to a canvas element?

I recommand the following article : Hit Region Detection For HTML5 Canvas And How To Listen To Click Events On Canvas Shapes which goes through various situations.

However, it does not cover the addHitRegion API, which must be the best way (using math functions and/or comparisons is quite error prone). This approach is detailed on developer.mozilla

How to check command line parameter in ".bat" file?

The short answer - use square brackets:

if [%1]==[] goto :blank

or (when you need to handle quoted args, see the Edit below):

if [%~1]==[] goto :blank

Why? you might ask. Well, just as Jeremiah Willcock mentioned: http://ss64.com/nt/if.html - they use that! OK, but what's wrong with the quotes?

Again, short answer: they are "magical" - sometimes double (double) quotes get converted to a single (double) quote. And they need to match, for a start.

Consider this little script:

@rem argq.bat
@echo off

:loop 
if "%1"=="" goto :done
echo %1
shift
goto :loop

:done
echo Done.

Let's test it:

C:\> argq bla bla
bla
bla
Done.

Seems to work. But now, lets switch to second gear:

C:\> argq "bla bla"
bla""=="" was unexpected at this time.

Boom This didn't evaluate to true, neither did it evaluate to false. The script DIED. If you were supposed to turn off the reactor somewhere down the line, well - tough luck. You now will die like Harry Daghlian.

You may think - OK, the arguments can't contain quotes. If they do, this happens. Wrong Here's some consolation:

C:\> argq ""bla bla""
""bla
bla""
Done.

Oh yeah. Don't worry - sometimes this will work.

Let's try another script:

@rem args.bat
@echo off

:loop 
if [%1]==[] goto :done
echo %1
shift
goto :loop

:done
echo Done.

You can test yourself, that it works OK for the above cases. This is logical - quotes have nothing to do with brackets, so there's no magic here. But what about spicing the args up with brackets?

D:\>args ]bla bla[
]bla
bla[
Done.

D:\>args [bla bla]
[bla
bla]
Done.

No luck there. The brackets just can't choke cmd.exe's parser.

Let's go back to the evil quotes for a moment. The problem was there, when the argument ended with a quote:

D:\>argq "bla1 bla2"
bla2""=="" was unexpected at this time.

What if I pass just:

D:\>argq bla2"
The syntax of the command is incorrect.

The script won't run at all. Same for args.bat:

D:\>args bla2"
The syntax of the command is incorrect.

But what do I get, when the number of "-characters "matches" (i.e. - is even), in such a case:

D:\>args bla2" "bla3
bla2" "bla3
Done.

NICE - I hope you learned something about how .bat files split their command line arguments (HINT: *It's not exactly like in bash). The above argument contains a space. But the quotes are not stripped automatically.

And argq? How does it react to that? Predictably:

D:\>argq bla2" "bla3
"bla3"=="" was unexpected at this time.

So - think before you say: "Know what? Just use quotes. [Because, to me, this looks nicer]".

Edit

Recently, there were comments about this answer - well, sqare brackets "can't handle" passing quoted arguments and treating them just as if they weren't quoted.

The syntax:

if "%~1"=="" (...)

Is not some newly found virtue of the double quotes, but a display of a neat feature of stripping quotes from the argument variable, if the first and last character is a double quote.

This "technology" works just as well with square brackets:

if [%~1]==[] (...)

It was a useful thing to point this out, so I also upvote the new answer.

Finally, double quote fans, does an argument of the form "" exist in your book, or is it blank? Just askin' ;)

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

You will have to annotate your service with @Service since you have said I am using annotations for mapping

Getting a map() to return a list in Python 3.x

List-returning map function has the advantage of saving typing, especially during interactive sessions. You can define lmap function (on the analogy of python2's imap) that returns list:

lmap = lambda func, *iterable: list(map(func, *iterable))

Then calling lmap instead of map will do the job: lmap(str, x) is shorter by 5 characters (30% in this case) than list(map(str, x)) and is certainly shorter than [str(v) for v in x]. You may create similar functions for filter too.

There was a comment to the original question:

I would suggest a rename to Getting map() to return a list in Python 3.* as it applies to all Python3 versions. Is there a way to do this? – meawoppl Jan 24 at 17:58

It is possible to do that, but it is a very bad idea. Just for fun, here's how you may (but should not) do it:

__global_map = map #keep reference to the original map
lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion
map = lmap
x = [1, 2, 3]
map(str, x) #test
map = __global_map #restore the original map and don't do that again
map(str, x) #iterator

Getting an Embedded YouTube Video to Auto Play and Loop

Here is the full list of YouTube embedded player parameters.

Relevant info:

autoplay (supported players: AS3, AS2, HTML5) Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

loop (supported players: AS3, HTML5) Values: 0 or 1. Default is 0. In the case of a single video player, a setting of 1 will cause the player to play the initial video again and again. In the case of a playlist player (or custom player), the player will play the entire playlist and then start again at the first video.

Note: This parameter has limited support in the AS3 player and in IFrame embeds, which could load either the AS3 or HTML5 player. Currently, the loop parameter only works in the AS3 player when used in conjunction with the playlist parameter. To loop a single video, set the loop parameter value to 1 and set the playlist parameter value to the same video ID already specified in the Player API URL:

http://www.youtube.com/v/VIDEO_ID?version=3&loop=1&playlist=VIDEO_ID

Use the URL above in your embed code (append other parameters too).

SQL exclude a column using SELECT * [except columnA] FROM tableA?

The automated way to do this in SQL (SQL Server) is:

declare @cols varchar(max), @query varchar(max);
SELECT  @cols = STUFF
    (
        ( 
            SELECT DISTINCT '], [' + name
            FROM sys.columns
            where object_id = (
                select top 1 object_id from sys.objects
                where name = 'MyTable'
            )
            and name not in ('ColumnIDontWant1', 'ColumnIDontWant2')
            FOR XML PATH('')
        ), 1, 2, ''
    ) + ']';

SELECT @query = 'select ' + @cols + ' from MyTable';  
EXEC (@query);

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

How to get current screen width in CSS?

this can be achieved with the css calc() operator

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
        zoom:calc(100% / 480);
    }
}

Get changes from master into branch in Git

First check out to master:

git checkout master

Do all changes, hotfix and commits and push your master.

Go back to your branch, 'aq', and merge master in it:

git checkout aq
git merge master

Your branch will be up-to-date with master. A good and basic example of merge is 3.2 Git Branching - Basic Branching and Merging.

Adding text to ImageView in Android

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_weight="30" >

        <ImageButton
            android:id="@+id/imgbtnUploadPendingPods"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/hello_world"
            android:src="@drawable/upload_icon" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:paddingTop="30dp"
            android:text="@string/pendingpods"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </FrameLayout>

Should I write script in the body or the head of the html?

The problem with writing scripts at the head of a page is blocking. The browser must stop processing the page until the script is download, parsed and executed. The reason for this is pretty clear, these scripts might insert more into the page changing the result of the rendering, they also may remove things that dont need to be rendered, etc.

Some of the more modern browsers violate this rule by not blocking on the downloading the scripts (ie8 was the first) but overall the download isn't the majority of the time spent blocking.

Check out Even Faster Websites, I just finished reading it and it goes over all of the fast ways to get scripts onto a page, Including putting scripts at the bottom of the page to allow rendering to complete (better UX).

CSS @media print issues with background-color;

Do not set the background-color inside the print stylesheet. Just set the attribute in the normal css file and it works fine :)

Checkout this example: The Ultimate Print HTML Template with Header & Footer

Demo: The Ultimate Print HTML Template with Header & Footer Demo

MySQL Trigger - Storing a SELECT in a variable

As far I think I understood your question I believe that u can simply declare your variable inside "DECLARE" and then after the "begin" u can use 'select into " you variable" ' statement. the code would look like this:

DECLARE
YourVar  varchar(50);
begin 
select ID into YourVar  from table
where ...

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

When you use just "localhost" the MySQL client library tries to use a Unix domain socket for the connection instead of a TCP/IP connection. The error is telling you that the socket, called MySQL, cannot be used to make the connection, probably because it does not exist (error number 2).

From the MySQL Documentation:

On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option.

There are a few ways to solve this problem.

  1. You can just use TCP/IP instead of the Unix socket. You would do this by using 127.0.0.1 instead of localhost when you connect. The Unix socket might by faster and safer to use, though.
  2. You can change the socket in php.ini: open the MySQL configuration file my.cnf to find where MySQL creates the socket, and set PHP's mysqli.default_socket to that path. On my system it's /var/run/mysqld/mysqld.sock.
  3. Configure the socket directly in the PHP script when opening the connection. For example:

    $db = new MySQLi('localhost', 'kamil', '***', '', 0, 
                                  '/var/run/mysqld/mysqld.sock')
    

Oracle select most recent date record

i think i'd try with MAX something like this:

SELECT staff_id, max( date ) from owner.table group by staff_id

then link in your other columns:

select staff_id, site_id, pay_level, latest
from owner.table, 
(   SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date

JavaScript replace/regex

In terms of pattern interpretation, there's no difference between the following forms:

  • /pattern/
  • new RegExp("pattern")

If you want to replace a literal string using the replace method, I think you can just pass a string instead of a regexp to replace.

Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:

function reEscape(s) {
    return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}

// ...

var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);

Comparing two joda DateTime instances

DateTime inherits its equals method from AbstractInstant. It is implemented as such

public boolean equals(Object readableInstant) {     // must be to fulfil ReadableInstant contract     if (this == readableInstant) {         return true;     }     if (readableInstant instanceof ReadableInstant == false) {         return false;     }     ReadableInstant otherInstant = (ReadableInstant) readableInstant;     return         getMillis() == otherInstant.getMillis() &&         FieldUtils.equals(getChronology(), otherInstant.getChronology()); } 

Notice the last line comparing chronology. It's possible your instances' chronologies are different.

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

Django CSRF Cookie Not Set

Make sure your django session backend is configured properly in settings.py. Then try this,

class CustomMiddleware(object):
  def process_request(self,request:HttpRequest):
      get_token(request)

Add this middleware in settings.py under MIDDLEWARE_CLASSES or MIDDLEWARE depending on the django version

get_token - Returns the CSRF token required for a POST form. The token is an alphanumeric value. A new token is created if one is not already set.

What's the difference between the 'ref' and 'out' keywords?

ref is in and out.

You should use out in preference wherever it suffices for your requirements.

Disable activity slide-in animation when launching new activity?

FLAG_ACTIVITY_NO_ANIMATION may work, but wasn't doing the trick for me when combined with FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK. I'm apparently seeing the animation for creating a new task with a fresh activity stack as I navigate laterally to my other top-level views.

What did work here was calling "overridePendingTransition(0, 0);" either immediately after my startActivity() call or the onPause(). Both ways worked, but doing it after startActivity() gives me a little more control over when I want animations and when I don't.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

window.location = appurl;// fb://method/call..
!window.document.webkitHidden && setTimeout(function () {
    setTimeout(function () {
    window.location = weburl; // http://itunes.apple.com/..
    }, 100);
}, 600);

document.webkitHidden is to detect if your app is already invoked and current safari tab to going to the background, this code is from www.baidu.com

PHP Warning: Invalid argument supplied for foreach()

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

How do I return a char array from a function?

As you're using C++ you could use std::string.

How do I convert a calendar week into a date in Excel?

The following formula is suitable for every year. You don't need to adjust it anymore. The precondition is that Monday is your first day of the week.

If A2 = Year and Week = B2
=IF(ISOWEEKNUM(DATE($A$2;1;1)-WEEKDAY(DATE($A$2;1;1);2)+1)>1;DATE($A$2;1;1)-WEEKDAY(DATE($A$2;1;1);2)+1+B2*7;DATE($A$2;1;1)-WEEKDAY(DATE($A$2;1;1);2)-6+B2*7)

Style input element to fill remaining width of its container

you can try this :

_x000D_
_x000D_
div#panel {_x000D_
    border:solid;_x000D_
    width:500px;_x000D_
    height:300px;_x000D_
}_x000D_
div#content {_x000D_
 height:90%;_x000D_
 background-color:#1ea8d1; /*light blue*/_x000D_
}_x000D_
div#panel input {_x000D_
 width:100%;_x000D_
 height:10%;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
 -webkit-box-sizing: border-box;_x000D_
       -moz-box-sizing: border-box;_x000D_
            box-sizing: border-box;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
}
_x000D_
<div id="panel">_x000D_
  <div id="content"></div>_x000D_
  <input type="text" placeholder="write here..."/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I catch a ctrl-c event?

Yeah, this is a platform dependent question.

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

In a WIN32 GUI application you should handle the WM_KEYDOWN message.

Enabling WiFi on Android Emulator

The emulator does not provide virtual hardware for Wi-Fi if you use API 24 or earlier. From the Android Developers website:

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

You can disable Wi-Fi in the emulator by running the emulator with the command-line parameter -feature -Wifi.

https://developer.android.com/studio/run/emulator.html#wi-fi

What's not supported

The Android Emulator doesn't include virtual hardware for the following:

  • Bluetooth
  • NFC
  • SD card insert/eject
  • Device-attached headphones
  • USB

The watch emulator for Android Wear doesn't support the Overview (Recent Apps) button, D-pad, and fingerprint sensor.

(read more at https://developer.android.com/studio/run/emulator.html#about)

https://developer.android.com/studio/run/emulator.html#wi-fi

Passing Javascript variable to <a href >

You can also use an express framework

app.get("/:id",function(req,res)
{
  var id = req.params.id;
  res.render("home.ejs",{identity : id});
});

Express file, which receives a JS variable identity from node.js

<a href = "/any_route/<%=identity%> includes identity JS variable into your href without a trouble enter

How to type ":" ("colon") in regexp?

Be careful, - has a special meaning with regexp. In a [], you can put it without problem if it is placed at the end. In your case, ,-: is taken as from , to :.

How do I get the time difference between two DateTime objects using C#?

You want the TimeSpan struct:

TimeSpan diff = dateTime1 - dateTime2;

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.

There are various methods for getting the days, hours, minutes, seconds and milliseconds back from this structure.

If you are just interested in the difference then:

TimeSpan diff = Math.Abs(dateTime1 - dateTime2);

will give you the positive difference between the times regardless of the order.

If you have just got the time component but the times could be split by midnight then you need to add 24 hours to the span to get the actual difference:

TimeSpan diff = dateTime1 - dateTime2;
if (diff < 0)
{
    diff = diff + TimeSpan.FromDays(1);
}

Loop in Jade (currently known as "Pug") template engine

Here is a very simple jade file that have a loop in it. Jade is very sensitive about white space. After loop definition line (for) you should give an indent(tab) to stuff that want to go inside the loop. You can do this without {}:

- var arr=['one', 'two', 'three'];
- var s = 'string';
doctype html
html
    head
    body
        section= s
        - for (var i=0; i<3; i++)
            div= arr[i]

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

Calling Javascript from a html form

Remove javascript: from onclick=".., onsubmit=".. declarations

javascript: prefix is used only in href="" or similar attributes (not events related)

ASP.NET GridView RowIndex As CommandArgument

Here is a very simple way:

<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" 
                 CommandArgument='<%# Container.DataItemIndex %>' />

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.

Build unsigned APK file with Android Studio

You can click the dropdown near the run button on toolbar,

  1. Select "Edit Configurations"
  2. Click the "+"
  3. Select "Gradle"
  4. Choose your module as Gradle project
  5. In Tasks: enter assemble

Now press ok,

all you need to do is now select your configuration from the dropdown and press run button. It will take some time. Your unsigned apk is now located in

Project\app\build\outputs\apk

How do I order my SQLITE database in descending order, for an android app?

return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
                         " ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
                         , new String[] {});

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Hope my scenario can help someone else. I had the same problem with the package bcrypt. First, I have tried with npm i -g node-gyp as suggested by Anne but the problem persisted. Then I read again the error message to have a better understanding of the problem and discovered that the script fails to build the package from scratch - since a precompiled version doesn't exist. In particular, it can't find the g++ command so I solved installing the build-essential package with sudo apt install build-essential -y.

Java Constructor Inheritance

A derived class is not the the same class as its base class and you may or may not care whether any members of the base class are initialized at the time of the construction of the derived class. That is a determination made by the programmer not by the compiler.

Synchronizing a local Git repository with a remote one

Reset and sync local repository with remote branch

The command: Remember to replace origin and master with the remote and branch that you want to synchronize with.

git fetch origin && git reset --hard origin/master && git clean -f -d

Or step-by-step:

git fetch origin
git reset --hard origin/master
git clean -f -d

Your local branch is now an exact copy (commits and all) of the remote branch.

Command output:

Here is an example of running the command on a local clone of the Forge a git repository.

sharkbook:forge lbaxter$ git fetch origin && git reset --hard origin/master && git clean -f -d
HEAD is now at 356cd85 FORGE-680
Removing forge-example-plugin/
Removing plugin-container-api/
Removing plugin-container/
Removing shell/.forge_settings
sharkbook:forge lbaxter$

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

How to parse JSON Array (Not Json Object) in Android

My case Load From Server Example..

int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
            if (jsonLength != 1) {
                for (int i = 0; i < jsonLength; i++) {
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
                    JSONObject resJson = (JSONObject) jsonArray.get(i);
                    //addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
                }

Hope it help

Create a zip file and download it

I have experienced exactly the same problem. In my case, the source of it was the permissions of the folder in which I wanted to create the zip file that were all set to read only. I changed it to read and write and it worked.

If the file is not created on your local-server when you run the script, you most probably have the same problem as I did.

How do I create an array of strings in C?

If you don't want to keep track of number of strings in array and want to iterate over them, just add NULL string in the end:

char *strings[]={ "one", "two", "three", NULL };

int i=0;
while(strings[i]) {
  printf("%s\n", strings[i]);
  //do something
  i++;
};

Putting GridView data in a DataTable

user this full solution to convert gridview to datatable

 public DataTable gridviewToDataTable(GridView gv)
        {

            DataTable dtCalculate = new DataTable("TableCalculator");

            // Create Column 1: Date
            DataColumn dateColumn = new DataColumn();
            dateColumn.DataType = Type.GetType("System.DateTime");
            dateColumn.ColumnName = "date";

            // Create Column 3: TotalSales
            DataColumn loanBalanceColumn = new DataColumn();
            loanBalanceColumn.DataType = Type.GetType("System.Double");
            loanBalanceColumn.ColumnName = "loanbalance";


            DataColumn offsetBalanceColumn = new DataColumn();
            offsetBalanceColumn.DataType = Type.GetType("System.Double");
            offsetBalanceColumn.ColumnName = "offsetbalance";


            DataColumn netloanColumn = new DataColumn();
            netloanColumn.DataType = Type.GetType("System.Double");
            netloanColumn.ColumnName = "netloan";


            DataColumn interestratecolumn = new DataColumn();
            interestratecolumn.DataType = Type.GetType("System.Double");
            interestratecolumn.ColumnName = "interestrate";

            DataColumn interestrateperdaycolumn = new DataColumn();
            interestrateperdaycolumn.DataType = Type.GetType("System.Double");
            interestrateperdaycolumn.ColumnName = "interestrateperday";

            // Add the columns to the ProductSalesData DataTable
            dtCalculate.Columns.Add(dateColumn);
            dtCalculate.Columns.Add(loanBalanceColumn);
            dtCalculate.Columns.Add(offsetBalanceColumn);
            dtCalculate.Columns.Add(netloanColumn);
            dtCalculate.Columns.Add(interestratecolumn);
            dtCalculate.Columns.Add(interestrateperdaycolumn);

            foreach (GridViewRow row in gv.Rows)
            {
                DataRow dr;
                dr = dtCalculate.NewRow();

                dr["date"] = DateTime.Parse(row.Cells[0].Text);
                dr["loanbalance"] = double.Parse(row.Cells[1].Text);
                dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
                dr["netloan"] = double.Parse(row.Cells[3].Text);
                dr["interestrate"] = double.Parse(row.Cells[4].Text);
                dr["interestrateperday"] = double.Parse(row.Cells[5].Text);


                dtCalculate.Rows.Add(dr);
            }



            return dtCalculate;
        }

jquery find class and get the value

You can get value of id,name or value in this way. class name my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

When you have this problem with Chrome, you don't need an Extension.
Start Chrome from the Console:

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Maybe you have to close all Tabs in Chrome and restart it.

Python iterating through object attributes

You can use the standard Python idiom, vars():

for attr, value in vars(k).items():
    print(attr, '=', value)

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

When is it acceptable to call GC.Collect?

using(var stream = new MemoryStream())
{
   bitmap.Save(stream, ImageFormat.Png);
   techObject.Last().Image = Image.FromStream(stream);
   bitmap.Dispose();

   // Without this code, I had an OutOfMemory exception.
   GC.Collect();
   GC.WaitForPendingFinalizers();
   //
}

Determine when a ViewPager changes pages

ViewPager.setOnPageChangeListener is deprecated now. You now need to use ViewPager.addOnPageChangeListener instead.

for example,

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

cocoapods - 'pod install' takes forever

you can run

pod install --verbose 

to see what's going on behind the scenes.. at least you'll know where it's stuck at (it could be a git clone operation that's taking too long because of your slow network etc)

to have an even better idea of why it seems to be stuck (running verbose can get you something like this

-> Installing Typhoon (2.2.1)
 > GitHub download
 > Creating cache git repo (~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92)
 > Cloning to Pods folder
       $ /usr/bin/git clone https://github.com/typhoon-framework/Typhoon.git ~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92 --mirror
       Cloning into bare repository '~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92'...

is to find out the size of the git repo you're cloning.. if you're cloning from github.. you can use this format:

/repos/:user/:repo

so, for example, to find out about the above repo type

https://api.github.com/repos/typhoon-framework/Typhoon

and the returned JSON will have a size key, value. so the above returned

"size": 94014,

which is approx 90mb. no wonder it's taking forever! (btw.. by the time I wrote this.. it just finished.. ha!)


update: one common thing that cocoa pods do before it even starts downloading the dependencies listed in your podfile, is to download/update its own repo (they call it Setting up Cocoapods Master repo.. look at this:

pod install --verbose

Analyzing dependencies

Updating spec repositories
  $ /usr/bin/git rev-parse  >/dev/null 2>&1
  $ /usr/bin/git ls-remote
  From https://github.com/CocoaPods/Specs.git
  09b0e7431ab82063d467296904a85d72ed40cd73  HEAD
  ..

the bad news is that if you follow the above procedure to find out how big the cocoa pod repo is.. you'll get this: "size": 614373,.. which is a lot.

so to get a more accurate way of knowing how long it takes to just install your own repo.. you can set up the cocoa pods master repo separately by using pod setup:

$ pod help setup
Usage:

$ pod setup

  Creates a directory at `~/.cocoapods/repos` which will hold your spec-repos.
  This is where it will create a clone of the public `master` spec-repo from:

      https://github.com/CocoaPods/Specs

  If the clone already exists, it will ensure that it is up-to-date.

then running pod install

How to uninstall Apache with command line

sc delete Apache2.4

Remove service in windows

Double border with different color

You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:

_x000D_
_x000D_
.triple-border:after {_x000D_
    content: " ";_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
    background: #FFE962;_x000D_
    height: 9px;_x000D_
    padding-bottom: 8px;_x000D_
    border-bottom: 9px solid #A3C662;_x000D_
    box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
_x000D_
_x000D_

You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.

Regex: Specify "space or start of string" and "space or end of string"

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s)  #the | means or. () is a capturing group. 


/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=\s|$)          #to look ahead.

How to rename a table in SQL Server?

This is what I use:

EXEC sp_rename 'MyTable', 'MyTableNewName';

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

How to test for $null array in PowerShell

How do you want things to behave?

If you want arrays with no elements to be treated the same as unassigned arrays, use:

[array]$foo = @() #example where we'd want TRUE to be returned
@($foo).Count -eq 0

If you want a blank array to be seen as having a value (albeit an empty one), use:

[array]$foo = @() #example where we'd want FALSE to be returned
$foo.PSObject -eq $null

If you want an array which is populated with only null values to be treated as null:

[array]$foo = $null,$null
@($foo | ?{$_.PSObject}).Count -eq 0 

NB: In the above I use $_.PSObject over $_ to avoid [bool]$false, [int]0, [string]'', etc from being filtered out; since here we're focussed solely on nulls.

Passing arguments to an interactive program non-interactively

You can put the data in a file and re-direct it like this:

$ cat file.sh
#!/bin/bash

read x
read y
echo $x
echo $y

Data for the script:

$ cat data.txt
2
3

Executing the script:

$ file.sh < data.txt
2
3

I cannot access tomcat admin console?

This is all I did and restarted the server.

<tomcat-users>

  <role rolename="tomcat"/>
  <user username="tomcat" password="tomcat" roles="manager-gui"/>

</tomcat-users>

Restart android machine

I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

What Is It?

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.

When It Is Thrown

Given an array declared as:

byte[] array = new byte[4];

You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown. Remember this when you create and access an array.

Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1 (where Length is total number of items in the array) so this code doesn't work:

array[array.Length] = 0;

Moreover please note that if you have a multidimensional array then you can't use Array.Length for both dimension, you have to use Array.GetLength():

int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
    for (int j=0; j < data.GetLength(1); ++j) {
        data[i, j] = 1;
    }
}

Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color. Each item represents a pixel, indices are from (0, 0) to (imageWidth - 1, imageHeight - 1).

Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
    for (int y = 0; y <= imageHeight; ++y) {
        pixels[x, y] = backgroundColor;
    }
}

This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]:

pixels[imageWidth, imageHeight] = Color.Black;

In another scenario you may get ArgumentOutOfRangeException for this code (for example if you're using GetPixel method on a Bitmap class).

Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>(), this example adds a new entry to an existing array:

Array.Resize(ref array, array.Length + 1);

Don't forget that valid indices are from 0 to Length - 1. If you simply try to assign an item at Length you'll get IndexOutOfRangeException (this behavior may confuse you if you think they may increase with a syntax similar to Insert method of other collections).

Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:

var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });

In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.

Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:

private static string[] RomanNumbers =
    new string[] { "I", "II", "III", "IV", "V" };

public static string Romanize(int number)
{
    return RomanNumbers[number];
}

Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:

// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.IndexOf(myArray, "Debug")]);

// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);

This will fail if no items in myArray will satisfy search condition because Array.IndexOf() will return -1 and then array access will throw.

Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):

static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
    int[] result = new int[maximum + 1]; // Includes 0

    foreach (int number in numbers)
        ++result[number];

    return result;
}

Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum.

How it applies to List<T>?

Same cases as array - range of valid indexes - 0 (List's indexes always start with 0) to list.Count - accessing elements outside of this range will cause the exception.

Note that List<T> throws ArgumentOutOfRangeException for the same cases where arrays use IndexOutOfRangeException.

Unlike arrays, List<T> starts empty - so trying to access items of just created list lead to this exception.

var list = new List<int>();

Common case is to populate list with indexing (similar to Dictionary<int, T>) will cause exception:

list[0] = 42; // exception
list.Add(42); // correct

IDataReader and Columns
Imagine you're trying to read data from a database with this code:

using (var connection = CreateConnection()) {
    using (var command = connection.CreateCommand()) {
        command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";

        using (var reader = command.ExecuteReader()) {
            while (reader.Read()) {
                ProcessData(reader.GetString(2)); // Throws!
            }
        }
    }
}

GetString() will throw IndexOutOfRangeException because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).

Please note that this behavior is shared with most IDataReader implementations (SqlDataReader, OleDbDataReader and so on).

You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with

 var data = dr["Colum1"];  // Missing the n in Column1.

This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".

Others
There is another (documented) case when this exception is thrown: if, in DataView, data column name being supplied to the DataViewSort property is not valid.

How to Avoid

In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0 with GetLowerBound(0) and .Length with GetUpperBound(0) (of course if you have parameters of type System.Array, it doesn't apply for T[]). Please note that in this case, upper bound is inclusive then this code:

for (int i=0; i < array.Length; ++i) { }

Should be rewritten like this:

for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }

Please note that this is not allowed (it'll throw InvalidCastException), that's why if your parameters are T[] you're safe about custom lower bound arrays:

void foo<T>(T[] array) { }

void test() {
    // This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
    foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}

Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException or ArgumentOutOfRangeException). In the next example, wrong parameters may cause IndexOutOfRangeException, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:

static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
    if (from < 0 || from>= array.Length)
        throw new ArgumentOutOfRangeException("from");

    if (length < 0)
        throw new ArgumentOutOfRangeException("length");

    if (from + length > array.Length)
        throw new ArgumentException("...");

    for (int i=from; i < from + length; ++i)
        array[i] = function(i);
}

If function is private you may simply replace if logic with Debug.Assert():

Debug.Assert(from >= 0 && from < array.Length);

Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert(), throw a proper exception (more descriptive about the problem) or handle that like in this example:

class Table {
    public int SelectedIndex { get; set; }
    public Row[] Rows { get; set; }

    public Row SelectedRow {
        get {
            if (Rows == null)
                throw new InvalidOperationException("...");

            // No or wrong selection, here we just return null for
            // this case (it may be the reason we use this property
            // instead of direct access)
            if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
                return null;

            return Rows[SelectedIndex];
        }
}

Validate Return Values
In one of previous examples we directly used Array.IndexOf() return value. If we know it may fail then it's better to handle that case:

int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }

How to Debug

In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.

You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:

array[index] = newValue;

You found your error, check how index increases. Is it right? Check how array is allocated, is coherent with how index increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!

A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.

If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).

The VB.NET side of the story

Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.

In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.

' declares an array with space for 5 integer 
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer

So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException

For i As Integer = 0 To 4
    myArray(i) = i
Next

The VB.NET rule

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration

Custom Date Format for Bootstrap-DatePicker

I solve it editing the file bootstrap-datapicker.js.

Look for the text bellow in the file and edit the variable "Format:"

var defaults = $.fn.datepicker.defaults = {
    assumeNearbyYear: false,
    autoclose: false,
    beforeShowDay: $.noop,
    beforeShowMonth: $.noop,
    beforeShowYear: $.noop,
    beforeShowDecade: $.noop,
    beforeShowCentury: $.noop,
    calendarWeeks: false,
    clearBtn: false,
    toggleActive: false,
    daysOfWeekDisabled: [],
    daysOfWeekHighlighted: [],
    datesDisabled: [],
    endDate: Infinity,
    forceParse: true,
    format: 'dd/mm/yyyy',
    keyboardNavigation: true,
    language: 'en',
    minViewMode: 0,
    maxViewMode: 4,
    multidate: false,
    multidateSeparator: ',',
    orientation: "auto",
    rtl: false,
    startDate: -Infinity,
    startView: 0,
    todayBtn: false,
    todayHighlight: false,
    weekStart: 0,
    disableTouchKeyboard: false,
    enableOnReadonly: true,
    showOnFocus: true,
    zIndexOffset: 10,
    container: 'body',
    immediateUpdates: false,
    title: '',
    templates: {
        leftArrow: '&laquo;',
        rightArrow: '&raquo;'
    }
};

JavaScript: SyntaxError: missing ) after argument list

You have an extra closing } in your function.

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }        // <== remove this brace
    }, false);
};

You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz or .tar.gz and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

How to do tag wrapping in VS code?

As I can't comment, I'll expand on Alex's fantastic answer.

If you want the Sublime-like experience with wrapping open up the Keymap Extensions (Preferences > Keymap Extensions [Cmd+K Cmd+M]) and add the following object:

{
    "key": "alt+w",
    "command": "editor.emmet.action.wrapIndividualLinesWithAbbreviation",
    "when": "editorHasSelection && editorTextFocus"
}

Which will bind the Emmet wrap command to Alt+W when text is selected

(Sorry for OSX only instructions)

How to overlay images

Here's a JQuery Technique with semi-transparent background.

HTML

<html>
<head>
    <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <title>Image Gallery</title>
</head>
<body>
    <h1>Image Gallery</h1>

    <ul id="imageGallery">
        <li><a href="images/refferal_machine.png"><img src="images/refferal_machine.png" width="100" alt="Refferal Machine By Matthew Spiel"></a></li>
        <li><a href="images/space-juice.png"><img src="images/space-juice.png" width="100" alt="Space Juice by Mat Helme"></a></li>
        <li><a href="images/education.png"><img src="images/education.png" width="100" alt="Education by Chris Michel"></a></li>
        <li><a href="images/copy_mcrepeatsalot.png"><img src="images/copy_mcrepeatsalot.png" width="100" alt="Wanted: Copy McRepeatsalot by Chris Michel"></a></li>
        <li><a href="images/sebastian.png"><img src="images/sebastian.png" width="100" alt="Sebastian by Mat Helme"></a></li>
        <li><a href="images/skill-polish.png"><img src="images/skill-polish.png" width="100" alt="Skill Polish by Chris Michel"></a></li>
        <li><a href="images/chuck.png"><img src="images/chuck.png" width="100" alt="Chuck by Mat Helme"></a></li>
        <li><a href="images/library.png"><img src="images/library.png" width="100" alt="Library by Tyson Rosage"></a></li>
        <li><a href="images/boat.png"><img src="images/boat.png" width="100" alt="Boat by Griffin Moore"></a></li>
        <li><a href="images/illustrator_foundations.png"><img src="images/illustrator_foundations.png" width="100" alt="Illustrator Foundations by Matthew Spiel"></a></li>
        <li><a href="images/treehouse_shop.jpg"><img src="images/treehouse_shop.jpg" width="100" alt="Treehouse Shop by Eric Smith"></a></li>
    </ul>

    <script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

CSS

/** Start Coding Here **/
#overlay {
  background:rgba(0,0,0,0.7);
  width:100%;
  height:100%;
  position:absolute;
  top:0;
  left:0;
  display:none;
  text-align:center;
}

#overlay img {
 margin-top: 10%; 
}

#overlay p {
 color:white; 
}

app.js

var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
var $caption = $("<p></p>");

// 1. Capture the click event on a link to an image
$("#imageGallery a").click(function(event){
  event.preventDefault();

  var imageLocation = $(this).attr("href");

  // 1.1 Show the overlay.
  $overlay.show();

  // 1.2 Update overlay with the image linked in the link
  $image.attr("src", imageLocation);

  // 1.3 Get child's alt attribute and set caption
  var captionText = $(this).children("img").attr("alt");
  $caption.text(captionText);


 // 2. Add overlay
 $("body").append($overlay);

    // 2.1 An image to overlay
    $overlay.append($image);

    // 2.2 A caption to overlay
    $overlay.append($caption);

});

//When overlay is clicked
$overlay.click(function(){
  //Hide the overlay
  $overlay.hide();
});

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

How to disable "prevent this page from creating additional dialogs"?

You should better use jquery-confirm rather than trying to remove that checkbox.

$.confirm({
    title: 'Confirm!',
    content: 'Are you sure you want to refund invoice ?',
    confirm: function(){
       //do something 
    },
    cancel: function(){
       //do something
    }
}); 

Reading a .txt file using Scanner class in Java

  1. Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).

  2. Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:

    URL url = insertionSort.class.getResource("10_Random");
    
    File file = new File(url.toURI());
    
  3. Specify the absolute file path via command-line arguments:

    File file = new File(args[0]);
    

In Eclipse:

  1. Choose "Run configurations"
  2. Go to the "Arguments" tab
  3. Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section

Remove CSS from a Div using JQuery

You could use the removeAttr method, if you want to delete all the inline style you added manually with javascript. It's better to use CSS classes but you never know.

$("#displayPanel div").removeAttr("style")

How to put text in the upper right, or lower right corner of a "box" using css

You need to put "here" into a <div> or <span> with style="float: right".

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

I had to disable the File Publish Option "Precompile during publishing."

Android studio- "SDK tools directory is missing"

I googled this error and tried all suggestions but nothing to work. My problem is a little bit different. I'm using Ubuntu 16.04 64bit. I was set mount /tmp folder as tmpfs for increasing the performance of applications. My fstab entry was:

tmpfs /tmp tmpfs defaults,noatime,nosuid,nodev,exec,mode=1777,size=1024M 0 0

This is setting /tmp file space to 1G and this is bottleneck for android studio becouse it needs more space in /tmp folder for download SDK files. Now I removed this line and rebooted my computer and everything is working now.

I spend 3 hours for this. I hope help to others.

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

This is an old thread but I was surprised nobody mentioned grep. The -A option allows specifying a number of lines to print after a search match and the -B option includes lines before a match. The following command would output 10 lines before and 10 lines after occurrences of "my search string" in the file "mylogfile.log":

grep -A 10 -B 10 "my search string" mylogfile.log

If there are multiple matches within a large file the output can rapidly get unwieldy. Two helpful options are -n which tells grep to include line numbers and --color which highlights the matched text in the output.

If there is more than file to be searched grep allows multiple files to be listed separated by spaces. Wildcards can also be used. Putting it all together:

grep -A 10 -B 10 -n --color "my search string" *.log someOtherFile.txt

Open Sublime Text from Terminal in macOS

You can create a new alias in Terminal:

nano ~/.bash_profile

Copy this line and paste it into the editor:

alias subl='open -a "Sublime Text"'

Hit control + x, then y, then enter to save and close it.

Close all Terminal windows and open it up again.

That's it, you can now use subl filename or subl .

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

Unstaged changes left after git reset --hard

None of these methods worked for me, the only solution was to nuke the whole repo and re-clone it. This includes stashing, resetting, adding then resetting, clrf settings, case sensitivity etc. Sigh..

How to duplicate sys.stdout to a log file?

another solution using logging module:

import logging
import sys

log = logging.getLogger('stdxxx')

class StreamLogger(object):

    def __init__(self, stream, prefix=''):
        self.stream = stream
        self.prefix = prefix
        self.data = ''

    def write(self, data):
        self.stream.write(data)
        self.stream.flush()

        self.data += data
        tmp = str(self.data)
        if '\x0a' in tmp or '\x0d' in tmp:
            tmp = tmp.rstrip('\x0a\x0d')
            log.info('%s%s' % (self.prefix, tmp))
            self.data = ''


logging.basicConfig(level=logging.INFO,
                    filename='text.log',
                    filemode='a')

sys.stdout = StreamLogger(sys.stdout, '[stdout] ')

print 'test for stdout'

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

Tieme put a lot of effort into his excellent answer, but I think the core of the OP's question is how these technologies relate to PHP rather than how each technology works.

PHP is the most used language in web development besides the obvious client side HTML, CSS, and Javascript. Yet PHP has 2 major issues when it comes to real-time applications:

  1. PHP started as a very basic CGI. PHP has progressed very far since its early stage, but it happened in small steps. PHP already had many millions of users by the time it became the embed-able and flexible C library that it is today, most of whom were dependent on its earlier model of execution, so it hasn't yet made a solid attempt to escape the CGI model internally. Even the command line interface invokes the PHP library (libphp5.so on Linux, php5ts.dll on Windows, etc) as if it still a CGI processing a GET/POST request. It still executes code as if it just has to build a "page" and then end its life cycle. As a result, it has very little support for multi-thread or event-driven programming (within PHP userspace), making it currently unpractical for real-time, multi-user applications.

Note that PHP does have extensions to provide event loops (such as libevent) and threads (such as pthreads) in PHP userspace, but very, very, few of the applications use these.

  1. PHP still has significant issues with garbage collection. Although these issues have been consistently improving (likely its greatest step to end the life cycle as described above), even the best attempts at creating long-running PHP applications require being restarted on a regular basis. This also makes it unpractical for real-time applications.

PHP 7 will be a great step to fix these issues as well, and seems very promising as a platform for real-time applications.

DateTimePicker time picker in 24 hour but displaying in 12hr?

The catch is that hh is for format 12 hours and HH is for 24 hours.

24 hour format

$(function () {
    $('#customElement').datetimepicker({
        format: 'HH:mm',           
    });
});

12 hour format

$(function () {
    $('#customElement').datetimepicker({
        format: 'hh:mm',           
    });
});

How to pass parameter to function using in addEventListener?

If the this value you want is the just the object that you bound the event handler to, then addEventListener() already does that for you. When you do this:

productLineSelect.addEventListener('change', getSelection, false);

the getSelection function will already be called with this set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

function getSelection(event) {
    // this will be set to the object that the event handler was bound to
    // event is all the detailed information about the event
}

If the desired this value is some other value than the object you bound the event handler to, you can just do this:

var self = this;
productLineSelect.addEventListener('change',function() {
    getSelection(self)
},false);

By way of explanation:

  1. You save away the value of this into a local variable in your other event handler.
  2. You then create an anonymous function to pass addEventListener.
  3. In that anonymous function, you call your actual function and pass it the saved value of this.

Difference between System.DateTime.Now and System.DateTime.Today

DateTime dt = new DateTime();// gives 01/01/0001 12:00:00 AM
DateTime dt = DateTime.Now;// gives today date with current time
DateTime dt = DateTime.Today;// gives today date and 12:00:00 AM time

'gulp' is not recognized as an internal or external command

The best solution, you can manage the multiple node versions using nvm installer. then, install the required node's version using below command

nvm install version

Use below command as a working node with mentioned version alone

nvm use version

now, you can use any version node without uninstalling previous installed node.

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

For TF2.x, you can do like this.

import tensorflow as tf
with tf.compat.v1.Session() as sess:
    hello = tf.constant('hello world')
    print(sess.run(hello))

>>> b'hello world

Phonegap Cordova installation Windows

Phonegap can be a little tricky for freshers. I spent much time trying to find the optimum way for creating a robust android application which can access the phone's native features.

This link provides a step wise method for creating a Phonegap android application using windows, html and javascript.

The openssl extension is required for SSL/TLS protection

according to the composer reference there are two relevant options: disable-tls and secure-http.

nano ~/.composer/config.json (If the file does not exist or is empty, then just create it with the following content)

{
    "config": {
        "disable-tls": true,
        "secure-http": false
    }
}

then it complains much:

You are running Composer with SSL/TLS protection disabled.
Warning: Accessing getcomposer.org over http which is an insecure protocol.

but it performs the composer selfupdate (or whatever).

while one cannot simply "enable SSL in the php.ini" on Linux; PHP needs to be compiled with openSSL configured as shared library - in order to be able to access it from the PHP CLI SAPI.

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Another important difference is that the Hashtable type supports lock-free multiple readers and a single writer at the same time, while Dictionary does not.

add scroll bar to table body

These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.

jQuery.scrollTableBody (GitHub)

As long as you have a table with proper <thead>, <tbody>, and (optional) <tfoot>, all you need to do is this:

$('table').scrollTableBody();

Converting DateTime format using razor

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")

Access Database opens as read only

The main reason for this is when the database is open somewhere else.

This could be as already said by many others:

  • not being closed properly somewhere
  • already open somewhere

When recently I had the same problem although different versions, I started to search for the reason.

In my case I had an excel file that queried data from the database.

In case the excel file is opened before the database, access would give this error.

Conclusion:

Check all files/connections related to the database. An open ODBC connection or query used in excel (my case) open the mdb file and will make it readonly.

Pandas sum by groupby, but exclude certain columns

If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

columns = ['Y'+str(i) for year in range(1967, 2011)]

df.groupby('Country')[columns].agg('sum')

How can I set the current working directory to the directory of the script in Bash?

If you just need to print present working directory then you can follow this.

$ vim test

#!/bin/bash
pwd
:wq to save the test file.

Give execute permission:

chmod u+x test

Then execute the script by ./test then you can see the present working directory.

git clone: Authentication failed for <URL>

After trying almost everything on this thread and others, continuing to Google, the only thing that worked for me, in the end, was to start Visual Studio as my AD user via command line:

cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
runas /netonly /user:<comp\name.surname> devenv.exe

Original issue: [1]: https://developercommunity.visualstudio.com/content/problem/304224/git-failed-with-a-fatal-errorauthentication-failed.html

My situation is I'm on a personal machine connecting to a company's internal/local devops server (not cloud-based) that uses AD authorization. I had no issue with TFS, but with git could not get the clone to work (Git failed with a fatal error. Authentication failed for [url]) until I did that.

Accept function as parameter in PHP

Tested for PHP 5.3

As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php

What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.

The function to do check:

if( is_callable( $string_function_name ) ){
    /*perform the call*/
}

Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php

call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );

as it follows (in a similar, parameterless, way):

    function funToBeCalled(){
        print("----------------------i'm here");
    }
    function wrapCaller($fun){
        if( is_callable($fun)){
            print("called");
            call_user_func($fun);
        }else{
            print($fun." not called");
        }
    }

    wrapCaller("funToBeCalled");
    wrapCaller("cannot call me");

Here's a class explaining how to do something similar :

<?php
class HolderValuesOrFunctionsAsString{
    private $functions = array();
    private $vars = array();

    function __set($name,$data){
        if(is_callable($data))
            $this->functions[$name] = $data;
        else
            $this->vars[$name] = $data;
    }

    function __get($name){
        $t = $this->vars[$name];
        if(isset($t))
            return $t;
        else{
            $t = $this->$functions[$name];
            if( isset($t))
                return $t;
        }
    }

    function __call($method,$args=null){
        $fun = $this->functions[$method];
        if(isset($fun)){
            call_user_func_array($fun,$args);
        } else {
            // error out
            print("ERROR: Funciton not found: ". $method);
        }
    }
}
?>

and an example of usage

<?php
    /*create a sample function*/
    function sayHello($some = "all"){
    ?>
         <br>hello to <?=$some?><br>
    <?php
    }

    $obj = new HolderValuesOrFunctionsAsString;

    /*do the assignement*/
    $obj->justPrintSomething = 'sayHello'; /*note that the given
        "sayHello" it's a string ! */

    /*now call it*/
    $obj->justPrintSomething(); /*will print: "hello to all" and
        a break-line, for html purpose*/

    /*if the string assigned is not denoting a defined method
         , it's treat as a simple value*/
    $obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';

    echo $obj->justPrintSomething; /*what do you expect to print?
        just that string*/
    /*N.B.: "justPrintSomething" is treated as a variable now!
        as the __set 's override specify"*/

    /*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
     $obj->justPrintSomething("Jack Sparrow");


     /*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/

     $obj->justPrintSomething( $obj->justPrintSomething );
         /*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/

    /*in fact, "justPrintSomething" it's a name used to identify both
         a value (into the dictionary of values) or a function-name
         (into the dictionary of functions)*/
?>

How to perform grep operation on all files in a directory?

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

Best way to find the months between two dates

Here's how to do this with Pandas FWIW:

import pandas as pd
pd.date_range("1990/04/03", "2014/12/31", freq="MS")

DatetimeIndex(['1990-05-01', '1990-06-01', '1990-07-01', '1990-08-01',
               '1990-09-01', '1990-10-01', '1990-11-01', '1990-12-01',
               '1991-01-01', '1991-02-01',
               ...
               '2014-03-01', '2014-04-01', '2014-05-01', '2014-06-01',
               '2014-07-01', '2014-08-01', '2014-09-01', '2014-10-01',
               '2014-11-01', '2014-12-01'],
              dtype='datetime64[ns]', length=296, freq='MS')

Notice it starts with the month after the given start date.

Ignore Duplicates and Create New List of Unique Values in Excel

Another approach, since Excel 2016, is to use Power Query.

Howto:

  • select the data (including the field name),
  • use menu Data > From a table or a range,
  • (Excel will change your sheet into an Excel Table, which is very convenient),
  • in the Power Query Editor, right-click on ColumnA (the column header), and Remove duplicates,
  • in the menu, choose Close and load, choose where you want the result, and you're done, like this.
  • Whenever you want the result table to update, right-click it and choose Refresh.

Benefits :

  • it uses the CPU only when manually updated, which is very convenient for long lists,
  • if you're curious, this offers many other powerful options.

Drawbacks :

  • it doesn't update on the fly (you have to right-click and refresh the result table),
  • people with old version of Excel won't be able to refresh the results table.

What is the final version of the ADT Bundle?

It seems that the version "20140702" of the example link in the question was the final version, because I downloaded this file on the 12th November 2014, i.e. the version from the 2nd of July 2014 was still the latest version on 12th of November. When I try manually all the possible versions/dates between today in this date, then I always get a page with error code "404" (file not found), which indicates that no new version was released since the 12th of November.

How to merge a list of lists with same type of items to a single list of items?

Here's the C# integrated syntax version:

var items =
    from list in listOfList
    from item in list
    select item;

How to use python numpy.savetxt to write strings and float number to an ASCII file?

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 

The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

Get type of a generic parameter in Java with reflection

As pointed out by @bertolami, it's not possible to us a variable type and get its future value (the content of typeOfList variable).

Nevertheless, you can pass the class as parameter on it like this:

public final class voodoo {
    public static void chill(List<T> aListWithTypeSpiderMan, Class<T> clazz) {
        // Here I'd like to get the Class-Object 'SpiderMan'
        Class typeOfTheList = clazz;
    }

    public static void main(String... args) {
        chill(new List<SpiderMan>(), Spiderman.class );
    }
}

That's more or less what Google does when you have to pass a class variable to the constructor of ActivityInstrumentationTestCase2.

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Pycharm does not show plot

I tested in my version on PyCharm 2017.1.2. I used interactive (True) and show (block=True).

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1//2000',periods=1000))
ts = ts.cumsum()
plt.interactive(True)
ts.plot()
plt.show(block=True)

How to find a text inside SQL Server procedures / triggers?

You can find it like

SELECT DISTINCT OBJECT_NAME(id) FROM syscomments WHERE [text] LIKE '%User%'

It will list distinct stored procedure names that contain text like 'User' inside stored procedure. More info

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Retrofit 2: Get JSON from Response body

So, here is the deal:

When making

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

You are passing GsonConverterFactory.create() here. If you do it like this, Gson will automatically convert the json object you get in response to your object <ResponseBody>. Here you can pass all other converters such as Jackson, etc...

Writing to a new file if it doesn't exist, and appending to a file if it does

Notice that if the file's parent folder doesn't exist you'll get the same error:

IOError: [Errno 2] No such file or directory:

Below is another solution which handles this case:
(*) I used sys.stdout and print instead of f.write just to show another use case

# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
     os.makedirs(folder_path)

print_to_log_file(folder_path, "Some File" ,"Some Content")

Where the internal print_to_log_file just take care of the file level:

# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):

   #1) Save a reference to the original standard output       
    original_stdout = sys.stdout   
    
    #2) Choose the mode
    write_append_mode = 'a' #Append mode
    file_path = folder_path + file_name
    if (if not os.path.exists(file_path) ):
       write_append_mode = 'w' # Write mode
     
    #3) Perform action on file
    with open(file_path, write_append_mode) as f:
        sys.stdout = f  # Change the standard output to the file we created.
        print(file_path, content_to_write)
        sys.stdout = original_stdout  # Reset the standard output to its original value

Consider the following states:

'w'  --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a'  --> Append to file
'a+' --> Append to file, Create it if doesn't exist

In your case I would use a different approach and just use 'a' and 'a+'.

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

You can enable NuGet packages and update you dlls. so that it work. or you can update the package manually by going through the package manager in your vs if u know which version you require for your solution.

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

Finding the max value of an attribute in an array of objects

if you (or, someone here) are free to use lodash utility library, it has a maxBy function which would be very handy in your case.

hence you can use as such:

_.maxBy(jsonSlice, 'y');

Finding the length of an integer in C

A more verbose way would be to use this function.

int length(int n)
{
    bool stop;
    int nDigits = 0;
    int dividend = 1;
    do
    {
        stop = false;
        if (n > dividend)
        {
            nDigits = nDigits + 1;
            dividend = dividend * 10;
        }
        else {
            stop = true;
        }


    }
    while (stop == false);
    return nDigits;
}

How do you declare string constants in C?

The main disadvantage of the #define method is that the string is duplicated each time it is used, so you can end up with lots of copies of it in the executable, making it bigger.

What is the "assert" function?

In addition, you can use it to check if the dynamic allocation was successful.

Code example:

int ** p;
p = new int * [5];      // Dynamic array (size 5) of pointers to int
for (int i = 0; i < 5; ++i) {
    p[i] = new int[3]; // Each i(ptr) is now pointing to a dynamic
                       // array (size 3) of actual int values
}

assert (p);            // Check the dynamic allocation.

Similar to:

if (p == NULL) {
    cout << "dynamic allocation failed" << endl;
    exit(1);
}

OperationalError: database is locked

For me it gets resolved once I closed the django shell which was opened using python manage.py shell

Histogram with Logarithmic Scale and custom breaks

Here's a pretty ggplot2 solution:

library(ggplot2)
library(scales)  # makes pretty labels on the x-axis

breaks=c(0,1,2,3,4,5,25)

ggplot(mydata,aes(x = V3)) + 
  geom_histogram(breaks = log10(breaks)) + 
  scale_x_log10(
    breaks = breaks,
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  )

Note that to set the breaks in geom_histogram, they had to be transformed to work with scale_x_log10

Using JavaScript to display a Blob

If you want to use fetch instead:

var myImage = document.querySelector('img');

fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Source:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

What is the effect of extern "C" in C++?

In every C++ program, all non-static functions are represented in the binary file as symbols. These symbols are special text strings that uniquely identify a function in the program.

In C, the symbol name is the same as the function name. This is possible because in C no two non-static functions can have the same name.

Because C++ allows overloading and has many features that C does not — like classes, member functions, exception specifications - it is not possible to simply use the function name as the symbol name. To solve that, C++ uses so-called name mangling, which transforms the function name and all the necessary information (like the number and size of the arguments) into some weird-looking string processed only by the compiler and linker.

So if you specify a function to be extern C, the compiler doesn't performs name mangling with it and it can be directly accessed using its symbol name as the function name.

This comes handy while using dlsym() and dlopen() for calling such functions.