Programs & Examples On #Activex exe

How to use jQuery to call an ASP.NET web service?

I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...

There is a line of code to uncommment in order to have it return JSON.

Display Last Saved Date on worksheet

This might be an alternative solution. Paste the following code into the new module:

Public Function ModDate()
ModDate = 
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm") 
End Function

Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.

Paste the following code into the cell where you want to display the last modification time:

=ModDate()

I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel

Beautiful Soup and extracting a div and its contents by ID

from bs4 import BeautifulSoup
from requests_html import HTMLSession

url = 'your_url'
session = HTMLSession()
resp = session.get(url)

# if element with id "articlebody" is dynamic, else need not to render
resp.html.render()

soup = bs(resp.html.html, "lxml")
soup.find("div", {"id": "articlebody"})

Declaring an HTMLElement Typescript

In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.

It’s just syntax sugar, there is no difference between:

var el: HTMLElement = document.getElementById('content');

and:

var el = document.getElementById('content');

On the other hand, because you specify the type you get all the information of your HTMLElement object.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

In my case it was a matter of a mis-directed reference. Project referenced the output of another project but the latter did not output the file where the former was looking for.

NVIDIA NVML Driver/library version mismatch

reboot. If the problem still exist:

sudo rmmod nvidia_drm
sudo rmmod nvidia_modeset
sudo rmmod nvidia
nvidia-smi

for cent/rhel

cd /boot
mv initramfs-$(uname -r).img /boot/initramfs-$(uname -r).img.bak
dracut -vf initramfs-$(uname -r).img $(uname -r)

then

reboot

for debian/ubuntu

update-initramfs -u

if problem exist persist

apt install -y dkms && dkms install -m nvidia -v 440.82

Change 440.82 to your actual version.

tip: get the Nvidia driver version:

ls /usr/src

you will find the Nvidia driver dir such as nvidia-440.82


also you can remove all Nvidia pkg and reinstall driver again

apt purge nvidia*
apt purge *cuda*

#check
apt list -i |grep nvidia
apt list -i |grep cuda

Change an image with onclick()

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

Add a new line to the end of a JtextArea

Are you using JTextArea's append(String) method to add additional text?

JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");

Use Font Awesome Icon in Placeholder

Sometimes above all answer not woking, when you can use below trick

_x000D_
_x000D_
.form-group {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input {_x000D_
  padding-left: 1rem;_x000D_
}_x000D_
_x000D_
i {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">_x000D_
_x000D_
<form role="form">_x000D_
  <div class="form-group">_x000D_
    <input type="text" class="form-control empty" id="iconified" placeholder="search">_x000D_
    <i class="fas fa-search"></i>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Why would a JavaScript variable start with a dollar sign?

A valid JavaScript identifier shuold must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables

Adobe Reader Command Line Reference

To open a PDF at page 100 the follow works

<path to Adobe Reader> /A "page=100" "<Path To PDF file>"

If you require more than one argument separate them with &

I use the following in a batch file to open the book I'm reading to the page I was up to.

C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe /A "page=149&pagemode=none" "D:\books\MCTS(70-562) ASP.Net 3.5 Development.pdf"

The best list of command line args for Adobe Reader I have found is here.
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf

It's for version 7 but all the arguments I tried worked.

As for closing the file, I think you will need to use the SDK, or if you are opening the file from code you could close the file from code once you have finished with it.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I was facing this issue because of Firebase Crashlytics. In Targets -> Build Phases -> Run Script

I had Firebase Crashlytics written like

${PODS_ROOT}/FirebaseCrashlytics/run

I changed that and put it in double quotes

"${PODS_ROOT}/FirebaseCrashlytics/run"

Benefits of inline functions in C++?

Conclusion from another discussion here:

Are there any drawbacks with inline functions?

Apparently, There is nothing wrong with using inline functions.

But it is worth noting the following points!

  • Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. - Google Guidelines

  • The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost - Source

  • There are few situations where an inline function may not work:

    • For a function returning values; if a return statement exists.
    • For a function not returning any values; if a loop, switch or goto statement exists.
    • If a function is recursive. -Source
  • The __inline keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not __inline is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the __inline keyword to be ignored. -Source

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

SQL to find the number of distinct values in a column

This will give you BOTH the distinct column values and the count of each value. I usually find that I want to know both pieces of information.

SELECT [columnName], count([columnName]) AS CountOf
FROM [tableName]
GROUP BY [columnName]

fatal error LNK1104: cannot open file 'kernel32.lib'

Today in Visual Studio 2017 I had the same problem.

The cause in my case turned out to be a bad environment setting in NETFXSDKDir (NETFXSDKDir=C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1). It needs to be instead NETFXSDKDir=C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86. Specifically, as set in this batch file (my directory actually has 4 different files) for the Command Prompt for VS2017:

%comspec% /k "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvars32.bat"

as I am reluctant to change one of the "as installed" batch files… even more as that batch file calls another yet another:

@call "%~dp0vcvarsall.bat" x86 %*

...instead for my specific C++ command-line app, I simply added the explicit path text: ;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86 for a total string in "Library Directories" like this: $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86. (Right click on project, Properties → Configuration Properties → VC++ Directories → Library Directories.) That resolved my "fatal error LNK1104: cannot open file 'kernel32.lib'" error. I found that hint in this GitHub issue.

Note this is reproducible in Visual Studio 2017 Enterprise 2017 Version 15.1 (26403.0) even after successful "repair" install… when creating a new Visual C++ Win32 Console Application and attempting to compile.

In fact, unless a blank application is created, the default template also includes reference to <SDKDDKVer.h> and with that I get this additional error: Error (active) E1696 cannot open source file "SDKDDKVer.h". So I created an empty C++ project.

Ajax call Into MVC Controller- Url Issue

you have an type error in example of code. You forget curlybracket after success

$.ajax({
 type: "POST",
 url: '@Url.Action("Search","Controller")',
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
     alert("here" + data.d.toString());
 }
})

;

How to print pandas DataFrame without index

If you want to pretty print the data frames, then you can use tabulate package.

import pandas as pd
import numpy as np
from tabulate import tabulate

def pprint_df(dframe):
    print tabulate(dframe, headers='keys', tablefmt='psql', showindex=False)

df = pd.DataFrame({'col1': np.random.randint(0, 100, 10), 
    'col2': np.random.randint(50, 100, 10), 
    'col3': np.random.randint(10, 10000, 10)})

pprint_df(df)

Specifically, the showindex=False, as the name says, allows you to not show index. The output would look as follows:

+--------+--------+--------+
|   col1 |   col2 |   col3 |
|--------+--------+--------|
|     15 |     76 |   5175 |
|     30 |     97 |   3331 |
|     34 |     56 |   3513 |
|     50 |     65 |    203 |
|     84 |     75 |   7559 |
|     41 |     82 |    939 |
|     78 |     59 |   4971 |
|     98 |     99 |    167 |
|     81 |     99 |   6527 |
|     17 |     94 |   4267 |
+--------+--------+--------+

gcc-arm-linux-gnueabi command not found

got the same error when trying to cross compile the raspberry pi kernel on ubunto 14.04.03 64bit under VM. the solution was found here:

-Install packages used for cross compiling on the Ubuntu box.

sudo apt-get install gcc-arm-linux-gnueabi make git-core ncurses-dev

-Download the toolchain

cd ~
git clone https://github.com/raspberrypi/tools

-Add the toolchain to your path

PATH=$PATH:~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian:~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin

notice the x64 version in the path command

PHP parse/syntax errors; and how to solve them

An error message that begins Parse error: syntax error, unexpected ':' can be caused by mistakenly writing a class static reference Class::$Variable as Class:$Variable.

Difference between RUN and CMD in a Dockerfile

RUN - Install Python , your container now has python burnt into its image
CMD - python hello.py , run your favourite script

Add a prefix string to beginning of each line

Using the shell:

#!/bin/bash
prefix="something"
file="file"
while read -r line
do
 echo "${prefix}$line"
done <$file > newfile
mv newfile $file

What is the best Java email address validation method?

Another option is use the Hibernate email validator, using the annotation @Email or using the validator class programatically, like:

import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; 

class Validator {
    // code
    private boolean isValidEmail(String email) {
        EmailValidator emailValidator = new EmailValidator();
        return emailValidator.isValid(email, null);
    }

}

Extract value of attribute node via XPath

for all xml with namespace use local-name()

//*[local-name()='Parent'][@id='1']/*[local-name()='Children']/*[local-name()='child']/@name 

Math.random() versus Random.nextInt(int)

According to https://forums.oracle.com/forums/thread.jspa?messageID=6594485&#6594485 Random.nextInt(n) is both more efficient and less biased than Math.random() * n

invalid command code ., despite escaping periods, using sed

On OS X nothing helps poor builtin sed to become adequate. The solution is:

brew install gnu-sed

And then use gsed instead of sed, which will just work as expected.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

What does %s mean in a python format string?

%s indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s converts a specified value to a string using the str() function. Compare this with the %r conversion type that uses the repr() function for value conversion.

Take a look at the docs for string formatting.

Passing javascript variable to html textbox

This was a problem for me, too. One reason for doing this (in my case) was that I needed to convert a client-side event (a javascript variable being modified) to a server-side variable (for that variable to be used in php). Hence populating a form with a javascript variable (eg a sessionStorage key/value) and converting it to a $_POST variable.

<form name='formName'>
<input name='inputName'>
</form>

<script>
document.formName.inputName.value=var
</script>

How do I find ' % ' with the LIKE operator in SQL Server?

You can use ESCAPE:

WHERE columnName LIKE '%\%%' ESCAPE '\'

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

How to define a List bean in Spring?

Import the spring util namespace. Then you can define a list bean as follows:

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


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class.

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

how to completely clear localstorage

localStorage.clear();

how to completely clear sessionstorage

sessionStorage.clear();

[...] Cookies ?

var cookies = document.cookie;

for (var i = 0; i < cookies.split(";").length; ++i)
{
    var myCookie = cookies[i];
    var pos = myCookie.indexOf("=");
    var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

is there any way to get the value back after clear these ?

No, there isn't. But you shouldn't rely on this if this is related to a security question.

Vue template or render function not defined yet I am using neither?

Yet another idea to throw in to the mix... In my case, the component throwing the error was a template-less component with a custom render() function. I couldn't see why it wasn't working, until I realised that I hadn't put <script>...</script> tags around the code in the component (seemed unnecessary, since I had no template or style tags either). Not sure why this got past the compiler...?

Either way... make sure you use your <script> tags ;-)

Hexadecimal string to byte array in C

A fleshed out version of Michael Foukarakis post (since I don't have the "reputation" to add a comment to that post yet):

#include <stdio.h>
#include <string.h>

void print(unsigned char *byte_array, int byte_array_size)
{
    int i = 0;
    printf("0x");
    for(; i < byte_array_size; i++)
    {
        printf("%02x", byte_array[i]);
    }
    printf("\n");
}

int convert(const char *hex_str, unsigned char *byte_array, int byte_array_max)
{
    int hex_str_len = strlen(hex_str);
    int i = 0, j = 0;

    // The output array size is half the hex_str length (rounded up)
    int byte_array_size = (hex_str_len+1)/2;

    if (byte_array_size > byte_array_max)
    {
        // Too big for the output array
        return -1;
    }

    if (hex_str_len % 2 == 1)
    {
        // hex_str is an odd length, so assume an implicit "0" prefix
        if (sscanf(&(hex_str[0]), "%1hhx", &(byte_array[0])) != 1)
        {
            return -1;
        }

        i = j = 1;
    }

    for (; i < hex_str_len; i+=2, j++)
    {
        if (sscanf(&(hex_str[i]), "%2hhx", &(byte_array[j])) != 1)
        {
            return -1;
        }
    }

    return byte_array_size;
}

void main()
{
    char *examples[] = { "", "5", "D", "5D", "5Df", "deadbeef10203040b00b1e50", "02invalid55" };
    unsigned char byte_array[128];
    int i = 0;

    for (; i < sizeof(examples)/sizeof(char *); i++)
    {
        int size = convert(examples[i], byte_array, 128);
        if (size < 0)
        {
            printf("Failed to convert '%s'\n", examples[i]);
        }
        else if (size == 0)
        {
            printf("Nothing to convert for '%s'\n", examples[i]);
        }
        else
        {
            print(byte_array, size);
        }
    }
}

Swift: How to get substring from start to last index of character

Here's an easy and short way to get a substring if you know the index:

let s = "www.stackoverflow.com"
let result = String(s.characters.prefix(17)) // "www.stackoverflow"

It won't crash the app if your index exceeds string's length:

let s = "short"
let result = String(s.characters.prefix(17)) // "short"

Both examples are Swift 3 ready.

How to make a JTable non-editable

table.setDefaultEditor(Object.class, null);

Using the slash character in Git branch name

It is possible to have hierarchical branch names (branch names with slash). For example in my repository I have such branch(es). One caveat is that you can't have both branch 'foo' and branch 'foo/bar' in repository.

Your problem is not with creating branch with slash in name.

$ git branch foo/bar
error: unable to resolve reference refs/heads/labs/feature: Not a directory
fatal: Failed to lock ref for update: Not a directory

The above error message talks about 'labs/feature' branch, not 'foo/bar' (unless it is a mistake in copy'n'paste, i.e you edited parts of session). What is the result of git branch or git rev-parse --symbolic-full-name HEAD?

remove duplicates from sql union

Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):

select * 
    from calls c join users u
        on c.assigned_to = u.user_id 
        or c.requestor_id = u.user_id
    where u.dept = 4

android get all contacts

Try this too,

private void getContactList() {
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if ((cur != null ? cur.getCount() : 0) > 0) {
        while (cur != null && cur.moveToNext()) {
            String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
                    ContactsContract.Contacts.DISPLAY_NAME));

            if (cur.getInt(cur.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }
                pCur.close();
            }
        }
    }
    if(cur!=null){
        cur.close();
    }
}

If you need more reference means refer this link Read ContactList

Jenkins / Hudson environment variables

I kept running into this problem, but now I just add:

source /etc/profile

As the first step in my build process. Now all my subsequent rules are loaded for Jenkins to operate smoothly.

Express.js req.body undefined

Building on @kevin-xue said, the content type needs to be declared. In my instance, this was only occurring with IE9 because the XDomainRequest doesn't set a content-type, so bodyparser and expressjs were ignoring the body of the request.

I got around this by setting the content-type explicitly before passing the request through to body parser, like so:

app.use(function(req, res, next) {
    // IE9 doesn't set headers for cross-domain ajax requests
    if(typeof(req.headers['content-type']) === 'undefined'){
        req.headers['content-type'] = "application/json; charset=UTF-8";
    }
    next();
})
.use(bodyParser.json());

Comparing double values in C#

It's a standard problem due to how the computer stores floating point values. Search here for "floating point problem" and you'll find tons of information.

In short – a float/double can't store 0.1 precisely. It will always be a little off.

You can try using the decimal type which stores numbers in decimal notation. Thus 0.1 will be representable precisely.


You wanted to know the reason:

Float/double are stored as binary fractions, not decimal fractions. To illustrate:

12.34 in decimal notation (what we use) means

1 * 101 + 2 * 100 + 3 * 10-1 + 4 * 10-2

The computer stores floating point numbers in the same way, except it uses base 2: 10.01 means

1 * 21 + 0 * 20 + 0 * 2-1 + 1 * 2-2

Now, you probably know that there are some numbers that cannot be represented fully with our decimal notation. For example, 1/3 in decimal notation is 0.3333333…. The same thing happens in binary notation, except that the numbers that cannot be represented precisely are different. Among them is the number 1/10. In binary notation that is 0.000110011001100….

Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.

CSS z-index not working (position absolute)

I was struggling to figure it out how to put a div over an image like this: z-index working

No matter how I configured z-index in both divs (the image wrapper) and the section I was getting this:

z-index Not working

Turns out I hadn't set up the background of the section to be background: white;

so basically it's like this:

<div class="img-wrp">
  <img src="myimage.svg"/>
</div>
<section>
 <other content>
</section>

section{
  position: relative;
  background: white; /* THIS IS THE IMPORTANT PART NOT TO FORGET */
}
.img-wrp{
  position: absolute;
  z-index: -1; /* also worked with 0 but just to be sure */
}

Get the week start date and week end date from week number

This is my solution


    SET DATEFIRST 1;    /* change to use a different datefirst  */
    DECLARE @date DATETIME
    SET @date = CAST('2/6/2019' as date)

    SELECT  DATEADD(dd,0 - (DATEPART(dw, @date) - 1) ,@date) [dateFrom], 
            DATEADD(dd,6 - (DATEPART(dw, @date) - 1) ,@date) [dateTo]

ASP.NET MVC controller actions that return JSON or partial html

To answer the other half of the question, you can call:

return PartialView("viewname");

when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.

What is object slicing?

When a Derived class Object is assigned to Base class Object, all the members of derived class object is copied to base class object except the members which are not present in the base class. These members are Sliced away by the compiler. This is called Object Slicing.

Here is an Example:

#include<bits/stdc++.h>
using namespace std;
class Base
{
    public:
        int a;
        int b;
        int c;
        Base()
        {
            a=10;
            b=20;
            c=30;
        }
};
class Derived : public Base
{
    public:
        int d;
        int e;
        Derived()
        {
            d=40;
            e=50;
        }
};
int main()
{
    Derived d;
    cout<<d.a<<"\n";
    cout<<d.b<<"\n";
    cout<<d.c<<"\n";
    cout<<d.d<<"\n";
    cout<<d.e<<"\n";


    Base b = d;
    cout<<b.a<<"\n";
    cout<<b.b<<"\n";
    cout<<b.c<<"\n";
    cout<<b.d<<"\n";
    cout<<b.e<<"\n";
    return 0;
}

It will generate:

[Error] 'class Base' has no member named 'd'
[Error] 'class Base' has no member named 'e'

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

Benefits of using the conditional ?: (ternary) operator

The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if is a statement, it cannot return a value.

How to query a MS-Access Table from MS-Excel (2010) using VBA

All you need is a ADODB.Connection

Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset   ' Microsoft ActiveX Data Objects Library

Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"

Set rs = cnn.Execute(SQLQuery) ' Retrieve the data

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)

    In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:

    • It provides a backup of your files.
    • It gives you a visual interface for navigating your repos.
    • It gives other people a way to navigate your repos.
    • It makes repo collaboration easy (e.g., multiple people contributing to the same project).
    • It provides a lightweight issue tracking system.
  4. How does Git compare to a backup system such as Time Machine?

    Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, this is a manual process.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • Git employs a powerful branching system that allows you to work on multiple, independent lines of development simultaneously and then merge those branches together as needed.
    • Git allows you to view the line-by-line differences between different versions of your files, which makes troubleshooting easier.
    • Git forces you to describe each of your commits, which makes it significantly easier to track down a specific previous version of a given file (and potentially revert to that previous version).
    • If you ever need help with your code, having it tracked by Git and hosted on GitHub makes it much easier for someone else to look at your code.

For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.

Rails DateTime.now without Time

If you want today's date without the time, just use Date.today

How to make a redirection on page load in JSF 1.x

Edit 2

I finally found a solution by implementing my forward action like that:

private void applyForward() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    // Find where to redirect the user.
    String redirect = getTheFromOutCome();

    // Change the Navigation context.
    NavigationHandler myNav = facesContext.getApplication().getNavigationHandler();
    myNav.handleNavigation(facesContext, null, redirect);

    // Update the view root
    UIViewRoot vr = facesContext.getViewRoot();
    if (vr != null) {
        // Get the URL where to redirect the user
        String url = facesContext.getExternalContext().getRequestContextPath();
        url = url + "/" + vr.getViewId().replace(".xhtml", ".jsf");
        Object obj = facesContext.getExternalContext().getResponse();
        if (obj instanceof HttpServletResponse) {
            HttpServletResponse response = (HttpServletResponse) obj;
            try {
                // Redirect the user now.
                response.sendRedirect(response.encodeURL(url));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

It works (at least regarding my first tests), but I still don't like the way it is implemented... Any better idea?


Edit This solution does not work. Indeed, when the doForward() function is called, the JSF lifecycle has already been started, and then recreate a new request is not possible.


One idea to solve this issue, but I don't really like it, is to force the doForward() action during one of the setBindedInputHidden() method:

private boolean actionDefined = false;
private boolean actionParamDefined = false;

public void setHiddenActionParam(HtmlInputHidden hiddenActionParam) {
    this.hiddenActionParam = hiddenActionParam;
    String actionParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("actionParam");
    this.hiddenActionParam.setValue(actionParam);
    actionParamDefined = true;
    forwardAction();
}

public void setHiddenAction(HtmlInputHidden hiddenAction) {
    this.hiddenAction = hiddenAction;
    String action = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("action");
    this.hiddenAction.setValue(action);
    actionDefined = true;
    forwardAction();
}

private void forwardAction() {
    if (!actionDefined || !actionParamDefined) {
        // As one of the inputHidden was not binded yet, we do nothing...
        return;
    }
    // Now, both action and actionParam inputHidden are binded, we can execute the forward...
    doForward(null);
}

This solution does not involve any Javascript call, and works does not work.

How to create PDF files in Python

I use rst2pdf to create a pdf file, since I am more familiar with RST than with HTML. It supports embedding almost any kind of raster or vector images.

It requires reportlab, but I found reportlab is not so straight forward to use (at least for me).

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

Installing Oracle Instant Client

I was able to setup Oracle Instant Client (Basic) 11g2 and Oracle ODBC (32bit) drivers on my 32bit Windows 7 PC. Note: you'll need a 'tnsnames.ora' file because it doesn't come with one. You can Google examples and copy/paste into a text file, change the parameters for your environment.

Setting up Oracle Instant Client-Basic 11g2 (Win7 32-bit)
(I think there's another step or two if your using 64-bit)

Oracle Instant Client

  • Unzip Oracle Instant Client - Basic
  • Put contents in folder like "C:\instantclient"
  • Edit PATH evironment variable, add path to Instant Client folder to the Variable Value.
  • Add new Variable called "TNS_ADMIN" point to same folder as Instant Client.
  • I had to create a "tnsnames.ora" file because it doesn't come with one. Put it in same folder as the client.
  • reboot or use Task Manager to kill "explorer.exe" and restart it to refresh the PATH environment variables.

ODBC Drivers

  • Unzip ODBC drivers
  • Copy all files into same folder as client "C:\instantclient"
  • Use command prompt to run "odbc_install.exe" (should say it was successful)

Note: The "un-documented" things that were hanging me up where...
- All files (Client and Drivers) needed to be in the same folder (nothing in sub-folders).
- Running the ODBC driver from the command prompt will allow you to see if it installs successfully. Double-clicking the installer just flashed a box on the screen, no idea it was failing because no error dialog.

After you've done this you should be able to setup a new DSN Data Source using the Oracle ODBC driver.
-Hope this helps someone else.

JAVA How to remove trailing zeros from a double

Use a DecimalFormat object with a format string of "0.#".

How do I call a SQL Server stored procedure from PowerShell?

Here is a function that I use (slightly redacted). It allows input and output parameters. I only have uniqueidentifier and varchar types implemented, but any other types are easy to add. If you use parameterized stored procedures (or just parameterized sql...this code is easily adapted to that), this will make your life a lot easier.

To call the function, you need a connection to the SQL server (say $conn),

$res=exec-storedprocedure -storedProcName 'stp_myProc' -parameters @{Param1="Hello";Param2=50} -outparams @{ID="uniqueidentifier"} $conn

retrieve proc output from returned object

$res.data #dataset containing the datatables returned by selects

$res.outputparams.ID #output parameter ID (uniqueidentifier)

The function:

function exec-storedprocedure($storedProcName,  
        [hashtable] $parameters=@{},
        [hashtable] $outparams=@{},
        $conn,[switch]$help){ 

        function put-outputparameters($cmd, $outparams){
            foreach($outp in $outparams.Keys){
                $cmd.Parameters.Add("@$outp", (get-paramtype $outparams[$outp])).Direction=[System.Data.ParameterDirection]::Output
            }
        }
        function get-outputparameters($cmd,$outparams){
            foreach($p in $cmd.Parameters){
                if ($p.Direction -eq [System.Data.ParameterDirection]::Output){
                $outparams[$p.ParameterName.Replace("@","")]=$p.Value
                }
            }
        }

        function get-paramtype($typename,[switch]$help){
            switch ($typename){
                'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier}
                'int' {[System.Data.SqlDbType]::Int}
                'xml' {[System.Data.SqlDbType]::Xml}
                'nvarchar' {[System.Data.SqlDbType]::NVarchar}
                default {[System.Data.SqlDbType]::Varchar}
            }
        }
        if ($help){
            $msg = @"
    Execute a sql statement.  Parameters are allowed.  
    Input parameters should be a dictionary of parameter names and values.
    Output parameters should be a dictionary of parameter names and types.
    Return value will usually be a list of datarows. 

    Usage: exec-query sql [inputparameters] [outputparameters] [conn] [-help]
    "@
            Write-Host $msg
            return
        }
        $close=($conn.State -eq [System.Data.ConnectionState]'Closed')
        if ($close) {
           $conn.Open()
        }

        $cmd=new-object system.Data.SqlClient.SqlCommand($sql,$conn)
        $cmd.CommandType=[System.Data.CommandType]'StoredProcedure'
        $cmd.CommandText=$storedProcName
        foreach($p in $parameters.Keys){
            $cmd.Parameters.AddWithValue("@$p",[string]$parameters[$p]).Direction=
                  [System.Data.ParameterDirection]::Input
        }

        put-outputparameters $cmd $outparams
        $ds=New-Object system.Data.DataSet
        $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
        [Void]$da.fill($ds)
        if ($close) {
           $conn.Close()
        }
        get-outputparameters $cmd $outparams

        return @{data=$ds;outputparams=$outparams}
    }

warning about too many open figures

If you intend to knowingly keep many plots in memory, but don't want to be warned about it, you can update your options prior to generating figures.

import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})

This will prevent the warning from being emitted without changing anything about the way memory is managed.

How to remove the first and the last character of a string

You can do something like that :

"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')

This regex is a common way to have the same behaviour of the trim function used in many languages.

A possible implementation of trim function is :

function trim(string, char){
    if(!char) char = ' '; //space by default
    char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
    var regex_1 = new RegExp("^" + char + "+", "g");
    var regex_2 = new RegExp(char + "+$", "g");
    return string.replace(regex_1, '').replace(regex_2, '');
}

Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///

You can also simply do :

"/installers/".substring(1, string.length-1);

Python Accessing Nested JSON Data

In your code j is Already json data and j['places'] is list not dict.

 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = r.json()

 print j['state']
 for each in j['places']:
    print each['latitude']

How to implement the factory method pattern in C++ correctly

Factory Pattern

class Point
{
public:
  static Point Cartesian(double x, double y);
private:
};

And if you compiler does not support Return Value Optimization, ditch it, it probably does not contain much optimization at all...

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.

It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):

enter image description here

Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.

You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.

The chrome developers also do change this periodically. They changed it recently from badidea to thisisunsafe so everyone using badidea, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:

Rotate the interstitial bypass keyword

The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.

I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.

If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN field in certificates now so if just using the old subject field then even adding it to the certificate store will not result in a green padlock.

If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.

HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.

LINQ - Full Outer Join

Thank You everybody for the interesting posts!

I modified the code because in my case I needed

  • a personalized join predicate
  • a personalized union distinct comparer

For the ones interested this is my modified code (in VB, sorry)

    Module MyExtensions
        <Extension()>
        Friend Function FullOuterJoin(Of TA, TB, TResult)(ByVal a As IEnumerable(Of TA), ByVal b As IEnumerable(Of TB), ByVal joinPredicate As Func(Of TA, TB, Boolean), ByVal projection As Func(Of TA, TB, TResult), ByVal comparer As IEqualityComparer(Of TResult)) As IEnumerable(Of TResult)
            Dim joinL =
                From xa In a
                From xb In b.Where(Function(x) joinPredicate(xa, x)).DefaultIfEmpty()
                Select projection(xa, xb)
            Dim joinR =
                From xb In b
                From xa In a.Where(Function(x) joinPredicate(x, xb)).DefaultIfEmpty()
                Select projection(xa, xb)
            Return joinL.Union(joinR, comparer)
        End Function
    End Module

    Dim fullOuterJoin = lefts.FullOuterJoin(
        rights,
        Function(left, right) left.Code = right.Code And (left.Amount [...] Or left.Description.Contains [...]),
        Function(left, right) New CompareResult(left, right),
        New MyEqualityComparer
    )

    Public Class MyEqualityComparer
        Implements IEqualityComparer(Of CompareResult)

        Private Function GetMsg(obj As CompareResult) As String
            Dim msg As String = ""
            msg &= obj.Code & "_"
            [...]
            Return msg
        End Function

        Public Overloads Function Equals(x As CompareResult, y As CompareResult) As Boolean Implements IEqualityComparer(Of CompareResult).Equals
            Return Me.GetMsg(x) = Me.GetMsg(y)
        End Function

        Public Overloads Function GetHashCode(obj As CompareResult) As Integer Implements IEqualityComparer(Of CompareResult).GetHashCode
            Return Me.GetMsg(obj).GetHashCode
        End Function
    End Class

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

MySQL with Node.js

Check out the node.js module list

  • node-mysql — A node.js module implementing the MySQL protocol
  • node-mysql2 — Yet another pure JS async driver. Pipelining, prepared statements.
  • node-mysql-libmysqlclient — MySQL asynchronous bindings based on libmysqlclient

node-mysql looks simple enough:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret',
});

connection.connect(function(err) {
  // connected! (unless `err` is set)
});

Queries:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  // Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'

Can PHP cURL retrieve response headers AND body in a single request?

Just in case you can't / don't use CURLOPT_HEADERFUNCTION or other solutions;

$nextCheck = function($body) {
    return ($body && strpos($body, 'HTTP/') === 0);
};

[$headers, $body] = explode("\r\n\r\n", $result, 2);
if ($nextCheck($body)) {
    do {
        [$headers, $body] = explode("\r\n\r\n", $body, 2);
    } while ($nextCheck($body));
}

How to redirect to Index from another controller?

try:

public ActionResult Index() {
    return RedirectToAction("actionName");
    // or
    return RedirectToAction("actionName", "controllerName");
    // or
    return RedirectToAction("actionName", "controllerName", new {/* routeValues, for example: */ id = 5 });
}

and in .cshtml view:

@Html.ActionLink("linkText","actionName")

OR:

@Html.ActionLink("linkText","actionName","controllerName")

OR:

@Html.ActionLink("linkText", "actionName", "controllerName", 
    new { /* routeValues forexample: id = 6 or leave blank or use null */ }, 
    new { /* htmlAttributes forexample: @class = "my-class" or leave blank or use null */ })

Notice using null in final expression is not recommended, and is better to use a blank new {} instead of null

PHP - Get array value with a numeric index

I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function. In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.

So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].

function array_get_by_index($index, $array) {

    $i=0;
    foreach ($array as $value) {
        if($i==$index) {
            return $value;
        }
        $i++;
    }
    // may be $index exceedes size of $array. In this case NULL is returned.
    return NULL;
}

Why can I not create a wheel in python?

Update your pip first:

pip install --upgrade pip

for Python 3:

pip3 install --upgrade pip

JetBrains / IntelliJ keyboard shortcut to collapse all methods

You Can Go To setting > editor > general > code folding and check "show code folding outline" .

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

Moment JS - check if a date is today or in the future

invert isBefore method of moment to check if a date is same as today or in future like this:

!moment(yourDate).isBefore(moment(), "day");

Set background colour of cell to RGB value of data in cell

Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...

Put this function into a new module:

Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
  On Error Resume Next
  x.Interior.Color = RGB(R, G, B)
  x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function

Then use this formula in your sheet, for example in cell D2:

=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")

Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2 to C2. The font color is a contrasting white or black.

How to return a result (startActivityForResult) from a TabHost Activity?

For start Activity 2 from Activity 1 and get result, you could use startActivityForResult and implement onActivityResult in Activity 1 and use setResult in Activity2.

Intent intent = new Intent(this, Activity2.class);
intent.putExtra(NUMERO1, numero1);
intent.putExtra(NUMERO2, numero2);
//startActivity(intent);
startActivityForResult(intent, MI_REQUEST_CODE);

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

Unrecognized SSL message, plaintext connection? Exception

If you are running local using spring i'd suggest use:

@Bean
public AmazonDynamoDB amazonDynamoDB() throws IOException {
    return AmazonDynamoDBClientBuilder.standard()
            .withCredentials(
                    new AWSStaticCredentialsProvider(
                            new BasicAWSCredentials("fake", "credencial")
                    )
            )
            .withClientConfiguration(new ClientConfigurationFactory().getConfig().withProtocol(Protocol.HTTP))
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("localhost:8443", "central"))
            .build();
}

It works for me using unit test.

Hope it's help!

How to create a TextArea in Android

Its really simple, write this code in XML:

<EditText
    android:id="@+id/fname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="First Name"
/>

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Backporting Python 3 open(encoding="utf-8") to Python 2

This may do the trick:

import sys
if sys.version_info[0] > 2:
    # py3k
    pass
else:
    # py2
    import codecs
    import warnings
    def open(file, mode='r', buffering=-1, encoding=None,
             errors=None, newline=None, closefd=True, opener=None):
        if newline is not None:
            warnings.warn('newline is not supported in py2')
        if not closefd:
            warnings.warn('closefd is not supported in py2')
        if opener is not None:
            warnings.warn('opener is not supported in py2')
        return codecs.open(filename=file, mode=mode, encoding=encoding,
                    errors=errors, buffering=buffering)

Then you can keep you code in the python3 way.

Note that some APIs like newline, closefd, opener do not work

Django set default form values

If you are creating modelform from POST values initial can be assigned this way:

form = SomeModelForm(request.POST, initial={"option": "10"})

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values

Python: Remove division decimal

>>> int(2.0)

You will get the answer as 2

Kill a Process by Looking up the Port being used by it from a .BAT

Here's a command to get you started:

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO @ECHO TaskKill.exe /PID %%P

When you're confident in your batch file, remove @ECHO.

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %%P

Note that you might need to change this slightly for different OS's. For example, on Windows 7 you might need tokens=5 instead of tokens=4.

How this works

FOR /F ... %variable IN ('command') DO otherCommand %variable...

This lets you execute command, and loop over its output. Each line will be stuffed into %variable, and can be expanded out in otherCommand as many times as you like, wherever you like. %variable in actual use can only have a single-letter name, e.g. %V.

"tokens=4 delims= "

This lets you split up each line by whitespace, and take the 4th chunk in that line, and stuffs it into %variable (in our case, %%P). delims looks empty, but that extra space is actually significant.

netstat -a -n -o

Just run it and find out. According to the command line help, it "Displays all connections and listening ports.", "Displays addresses and port numbers in numerical form.", and "Displays the owning process ID associated with each connection.". I just used these options since someone else suggested it, and it happened to work :)

^|

This takes the output of the first command or program (netstat) and passes it onto a second command program (findstr). If you were using this directly on the command line, instead of inside a command string, you would use | instead of ^|.

findstr :8080

This filters any output that is passed into it, returning only lines that contain :8080.

TaskKill.exe /PID <value>

This kills a running task, using the process ID.

%%P instead of %P

This is required in batch files. If you did this on the command prompt, you would use %P instead.

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

Retrieve data from website in android app

You can use jsoup to parse any kind of web page. Here you can find the jsoup library and full source code.

Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html

To install in Eclipse:

  1. Right Click on project
  2. BuildPath
  3. Add External Archives
  4. select the .jar file

You can parse according to tag/parent/child very comfortably

Docker official registry (Docker Hub) URL

For those wanting to explicitly declare they are pulling from dockerhub when using fabric8 maven plugin, add a new property: <docker.pull.registry>registry.hub.docker.com/library</docker.pull.registry>

I arrived on this page trying to solve problem of pulling from my AWS ECR registry when building Docker images using fabric8.

How to use LocalBroadcastManager?

How to change your global broadcast to LocalBroadcast

1) Create Instance

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);

2) For registering BroadcastReceiver

Replace

registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));

With

localBroadcastManager.registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));

3) For sending broadcast message

Replace

sendBroadcast(intent);

With

localBroadcastManager.sendBroadcast(intent);

4) For unregistering broadcast message

Replace

unregisterReceiver(mybroadcast);

With

localBroadcastManager.unregisterReceiver(mybroadcast);

Set focus to field in dynamically loaded DIV

$("#header").attr('tabindex', -1).focus();

PHP compare time

To see of the curent time is greater or equal to 14:08:10 do this:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

Depending on your input sources, make sure to account for timezone.

See PHP time() and PHP strtotime()

Convert InputStream to JSONObject

This code works

BufferedReader bR = new BufferedReader(  new InputStreamReader(inputStream));
String line = "";

StringBuilder responseStrBuilder = new StringBuilder();
while((line =  bR.readLine()) != null){

    responseStrBuilder.append(line);
}
inputStream.close();

JSONObject result= new JSONObject(responseStrBuilder.toString());       

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

JavaScript for handling Tab Key press

You should be able to do this with the keyup event. To be specific, event.target should point at the selected element and event.target.href will give you the href-value of that element. See mdn for more information.

The following code is jQuery, but apart from the boilerplate code, the rest is the same in pure javascript. This is a keyup handler that is bound to every link tag.

$('a').on( 'keyup', function( e ) {
    if( e.which == 9 ) {
        console.log( e.target.href );
    }
} );

jsFiddle: http://jsfiddle.net/4PqUF/

MySQL Workbench - Connect to a Localhost

You need to install mysql server for your machine first. Once done, you will be able to add local db details to it.

For e.g. IP: 127.0.0.1
port: 3306
user: root
pass: pass of root which you have set

Here is the link on step by step guide for linux.

https://support.rackspace.com/how-to/install-mysql-server-on-the-ubuntu-operating-system/

String strip() for JavaScript?

A better polyfill from the MDN that supports removal of BOM and NBSP:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string) instead. That being said, if you are targeting an older environment without native .trim() support, you are likely to have more important performance issues to deal with.

Storing Objects in HTML5 localStorage

For Typescript users willing to set and get typed properties:

/**
 * Silly wrapper to be able to type the storage keys
 */
export class TypedStorage<T> {

    public removeItem(key: keyof T): void {
        localStorage.removeItem(key);
    }

    public getItem<K extends keyof T>(key: K): T[K] | null {
        const data: string | null =  localStorage.getItem(key);
        return JSON.parse(data);
    }

    public setItem<K extends keyof T>(key: K, value: T[K]): void {
        const data: string = JSON.stringify(value);
        localStorage.setItem(key, data);
    }
}

Example usage:

// write an interface for the storage
interface MyStore {
   age: number,
   name: string,
   address: {city:string}
}

const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();

storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok

const address: {city:string} = storage.getItem("address");

Bootstrap - Removing padding or margin when screen size is smaller

The problem here is much more complex than removing the container padding since the grid structure relies on this padding when applying negative margins for the enclosed rows.

Removing the container padding in this case will cause an x-axis overflow caused by all the rows inside of this container class, this is one of the most stupid things about the Bootstrap Grid.

Logically it should be approached by

  1. Never using the .container class for anything other than rows
  2. Make a clone of the .container class that has no padding for use with non-grid html
  3. For removing the .container padding on mobile you can manually remove it with media queries then overflow-x: hidden; which is not very reliable but works in most cases.

If you are using LESS the end result will look like this

@media (max-width: @screen-md-max) {
    .container{
        padding: 0;
        overflow-x: hidden;
    }
}

Change the media query to whatever size you want to target.

Final thoughts, I would highly recommend using the Foundation Framework Grid as its way more advanced

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

failed to open stream: HTTP wrapper does not support writeable connections

you could use fopen() function.

some example:

$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';


    $newfname = $destination_folder .'myfile.mp4'; //set your file ext

    $file = fopen ($url, "rb");

    if ($file) {
      $newf = fopen ($newfname, "a"); // to overwrite existing file

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );

      }
    }

    if ($file) {
      fclose($file);
    }

    if ($newf) {
      fclose($newf);
    }

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

Replacing NULL with 0 in a SQL server query

A Simple way is

UPDATE tbl_name SET fild_name = value WHERE fild_name IS NULL

How to get access to job parameters from ItemReader, in Spring Batch?

As was stated, your reader needs to be 'step' scoped. You can accomplish this via the @Scope("step") annotation. It should work for you if you add that annotation to your reader, like the following:

import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("foo-reader")
@Scope("step")
public final class MyReader implements ItemReader<MyData> {
  @Override
  public MyData read() throws Exception {
    //...
  }

  @Value("#{jobParameters['fileName']}")
  public void setFileName(final String name) {
    //...
  }
}

This scope is not available by default, but will be if you are using the batch XML namespace. If you are not, adding the following to your Spring configuration will make the scope available, per the Spring Batch documentation:

<bean class="org.springframework.batch.core.scope.StepScope" />

How to change shape color dynamically?

    LayerDrawable bgDrawable = (LayerDrawable) button.getBackground();
    final GradientDrawable shape = (GradientDrawable)
            bgDrawable.findDrawableByLayerId(R.id.round_button_shape);
    shape.setColor(Color.BLACK);

log4j logging hierarchy order

Hierarchy order

  1. ALL
  2. TRACE
  3. DEBUG
  4. INFO
  5. WARN
  6. ERROR
  7. FATAL
  8. OFF

Tainted canvases may not be exported

In my case I was drawing onto a canvas tag from a video. To address the tainted canvas error I had to do two things:

<video id="video_source" crossorigin="anonymous">
    <source src="http://crossdomain.example.com/myfile.mp4">
</video>
  • Ensure Access-Control-Allow-Origin header is set in the video source response (proper setup of crossdomain.example.com)
  • Set the video tag to have crossorigin="anonymous"

Are there inline functions in java?

Java9 has an "Ahead of time" compiler that does several optimizations at compile-time, rather than runtime, which can be seen as inlining.

docker: executable file not found in $PATH

to make it work add soft reference to /usr/bin:

ln -s $(which node) /usr/bin/node

ln -s $(which npm) /usr/bin/npm

Change directory in Node.js command prompt

Type .exit in command prompt window, It terminates the node repl.

Listing all the folders subfolders and files in a directory using php

In case you want to use directoryIterator

Following function is a re-implementation of @Shef answer with directoryIterator

function listFolderFiles($dir)
{
    echo '<ol>';
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            echo '<li>' . $fileInfo->getFilename();
            if ($fileInfo->isDir()) {
                listFolderFiles($fileInfo->getPathname());
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
listFolderFiles('Main Dir');

JOptionPane - input dialog box program

One solution is to actually use an integer array instead of separate test strings:

You could loop parse the response from JOptionPane.showInputDialog into the individual elements of the array.

Arrays.sort could be used to sort them to allow you to pick out the 2 highest values.

The average can be easily calculated then by adding these 2 values & dividing by 2.

int[] testScore = new int[3];

for (int i = 0; i < testScore.length; i++) {
   testScore[i] = Integer.parseInt(JOptionPane.showInputDialog("Please input mark for test " + i + ": "));
}

Arrays.sort(testScore);
System.out.println("Average: " + (testScore[1] + testScore[2])/2.0);

Clear text from textarea with selenium

In my experience, this turned out to be the most efficient

driver.find_element_by_css_selector('foo').send_keys(u'\ue009' + u'\ue003')

We are sending Ctrl + Backspace to delete all characters from the input, you can also replace backspace with delete.

EDIT: removed Keys dependency

installing apache: no VCRUNTIME140.dll

Problem: Wamp Won't Turn Green & VCRUNTIME140.dll error

Solved:)

You need C++ Redistributable for Visual Studio 2015 RC. Try to download the file, vc_redist.x64.exe from here, https://www.microsoft.com/en-us/download/details.aspx?id=48145

if you already installed then uninstalled it first

  1. I installed the vc_redist.x64.exe (if you OS is 32 bit then you should download vc_redist.x86.exe)
  2. then installed the wampserver (if you already installed then unsintalled it first)

How do you manually execute SQL commands in Ruby On Rails using NuoDB

For me, I couldn't get this to return a hash.

results = ActiveRecord::Base.connection.execute(sql)

But using the exec_query method worked.

results = ActiveRecord::Base.connection.exec_query(sql)

The "backspace" escape character '\b': unexpected behavior?

If you want a destructive backspace, you'll need something like

"\b \b"

i.e. a backspace, a space, and another backspace.

Convert a string into an int

You can also use like :

NSInteger getVal = [self.string integerValue];

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

What is the difference between active and passive FTP?

I recently run into this question in my work place so I think I should say something more here. I will use image to explain how the FTP works as an additional source for previous answer.

Active mode:

active mode


Passive mode:

enter image description here


In an active mode configuration, the server will attempt to connect to a random client-side port. So chances are, that port wouldn't be one of those predefined ports. As a result, an attempt to connect to it will be blocked by the firewall and no connection will be established.

enter image description here


A passive configuration will not have this problem since the client will be the one initiating the connection. Of course, it's possible for the server side to have a firewall too. However, since the server is expected to receive a greater number of connection requests compared to a client, then it would be but logical for the server admin to adapt to the situation and open up a selection of ports to satisfy passive mode configurations.

So it would be best for you to configure server to support passive mode FTP. However, passive mode would make your system vulnerable to attacks because clients are supposed to connect to random server ports. Thus, to support this mode, not only should your server have to have multiple ports available, your firewall should also allow connections to all those ports to pass through!

To mitigate the risks, a good solution would be to specify a range of ports on your server and then to allow only that range of ports on your firewall.

For more information, please read the official document.

Set custom HTML5 required field validation message

Use the attribute "title" in every input tag and write a message on it

"CAUTION: provisional headers are shown" in Chrome debugger

This issue will also occur while using some packages like webpack-hot-middleware and open multiple pages at the same time. webpack-hot-middleware will create a connection for each page for listening to the changes of code then to refresh the page. Each browser has a max-connections-per-server limitation which is 6 for Chrome, so if you have already opened more than 6 pages in Chrome, the new request will be hung there until you close some pages.

How to pass a function as a parameter in Java?

I know this is a rather old post but I have another slightly simpler solution. You could create another class within and make it abstract. Next make an Abstract method name it whatever you like. In the original class make a method that takes the new class as a parameter, in this method call the abstract method. It will look something like this.

public class Demo {

    public Demo(/.../){

    }

    public void view(Action a){
        a.preform();
    }

    /**
     * The Action Class is for making the Demo
     * View Custom Code
     */
    public abstract class Action {

        public Action(/.../){

        }

        abstract void preform();
    }
}

Now you can do something like this to call a method from within the class.

/...
Demo d = new Demo;
Action a = new Action() {

    @Override
    void preform() {
        //Custom Method Code Goes Here
    }
};

/.../
d.view(a)

Like I said I know its old but this way I think is a little easier. Hope it helps.

What are .NumberFormat Options In Excel VBA?

Note this was done on Excel for Mac 2011 but should be same for Windows

Macro:

Sub numberformats()
  Dim rng As Range
  Set rng = Range("A24:A35")
  For Each c In rng
    Debug.Print c.NumberFormat
  Next c
End Sub

Result:

General     General
Number      0
Currency    $#,##0.00;[Red]$#,##0.00
Accounting  _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
Date        m/d/yy
Time        [$-F400]h:mm:ss am/pm
Percentage  0.00%
Fraction    # ?/?
Scientific  0.00E+00
Text        @
Special     ;;
Custom      #,##0_);[Red](#,##0)

(I just picked a random entry for custom)

GridView - Show headers on empty data source

Use an EmptyDataTemplate like below. When your DataSource has no records, you will see your grid with headers, and the literal text or HTML that is inside the EmptyDataTemplate tags.

<asp:GridView ID="gvResults" AutoGenerateColumns="False" HeaderStyle-CssClass="tableheader" runat="server">
    <EmptyDataTemplate>
        <asp:Label ID="lblEmptySearch" runat="server">No Results Found</asp:Label>
    </EmptyDataTemplate>
    <Columns>
        <asp:BoundField DataField="ItemId" HeaderText="ID" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        ...
    </Columns>
</asp:GridView>

What is the difference between Digest and Basic Authentication?

Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.

Digest Access Authentication uses the hashing methodologies to generate the cryptographic result

How to write inline if statement for print?

Inline if-else EXPRESSION must always contain else clause, e.g:

a = 1 if b else 0

If you want to leave your 'a' variable value unchanged - assing old 'a' value (else is still required by syntax demands):

a = 1 if b else a

This piece of code leaves a unchanged when b turns to be False.

How to find out when a particular table was created in Oracle?

SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

Angular JS update input field after change

You can add ng-change directive to input fields. Have a look at the docs example.

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

looking at jQuery they in there jQuery.isArray(...) they do:

    isArray = Array.isArray || function( obj ) {
    return jQuery.type(obj) === "array";
}

this leads us to: jQuery.type:

    type = function( obj ) {
    return obj == null ?
        String( obj ) :
        class2type[ toString.call(obj) ] || "object";
}

and again we have to look in: class2type

class2type = {};

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

and in native JS:

var a, t = "Boolean Number String Function Array Date RegExp Object".split(" ");
for( a in t ) {
    class2type[ "[object " + t[a] + "]" ] = t[a].toLowerCase();
}

this ends up with:

var isArray = Array.isArray || function( obj ) {
    return toString.call(obj) === "[object Array]";
}

Html table with button on each row

Pretty sure this solves what you're looking for:

HTML:

<table>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
</table>

Javascript (using jQuery):

$(document).ready(function(){
    $('.editbtn').click(function(){
        $(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
    });
});

Edit:

Apparently I should have looked at your sample code first ;)

You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.

By using classes, you can apply the same logic to multiple elements without any conflicts.

JSFiddle sample

Which are more performant, CTE or temporary tables?

CTE has its uses - when data in the CTE is small and there is strong readability improvement as with the case in recursive tables. However, its performance is certainly no better than table variables and when one is dealing with very large tables, temporary tables significantly outperform CTE. This is because you cannot define indices on a CTE and when you have large amount of data that requires joining with another table (CTE is simply like a macro). If you are joining multiple tables with millions of rows of records in each, CTE will perform significantly worse than temporary tables.

How to "flatten" a multi-dimensional array to simple one in PHP?

Given multi-dimensional array and converting it into one-dimensional, can be done by unsetting all values which are having arrays and saving them into first dimension, for example:

function _flatten_array($arr) {
  while ($arr) {
    list($key, $value) = each($arr); 
    is_array($value) ? $arr = $value : $out[$key] = $value;
    unset($arr[$key]);
  }
  return (array)$out;
}

Using boolean values in C

This is what I use:

enum {false, true};
typedef _Bool bool;

_Bool is a built in type in C. It's intended for boolean values.

Angularjs checkbox checked by default on load and disables Select list when checked

Do it in the controller ( controller as syntax below)

controller:

vm.question= {};
vm.question.active = true;

form

<input ng-model="vm.question.active" type="checkbox" id="active" name="active">

Checking if type == list in python

This seems to work for me:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

Node.js Logging

The "logger.setLevel('ERROR');" is causing the problem. I do not understand why, but when I set it to anything other than "ALL", nothing gets printed in the file. I poked around a little bit and modified your code. It is working fine for me. I created two files.

logger.js

var log4js = require('log4js');
log4js.clearAppenders()
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('test.log'), 'test');
var logger = log4js.getLogger('test');
logger.setLevel('ERROR');

var getLogger = function() {
   return logger;
};

exports.logger = getLogger();

logger.test.js

var logger = require('./logger.js')

var log = logger.logger;

log.error("ERROR message");
log.trace("TRACE message");

When I run "node logger.test.js", I see only "ERROR message" in test.log file. If I change the level to "TRACE" then both lines are printed on test.log.

Safely limiting Ansible playbooks to a single machine?

To expand on joemailer's answer, if you want to have the pattern-matching ability to match any subset of remote machines (just as the ansible command does), but still want to make it very difficult to accidentally run the playbook on all machines, this is what I've come up with:

Same playbook as the in other answer:

# file: user.yml  (playbook)
---
- hosts: '{{ target }}'
  user: ...

Let's have the following hosts:

imac-10.local
imac-11.local
imac-22.local

Now, to run the command on all devices, you have to explicty set the target variable to "all"

ansible-playbook user.yml --extra-vars "target=all"

And to limit it down to a specific pattern, you can set target=pattern_here

or, alternatively, you can leave target=all and append the --limit argument, eg:

--limit imac-1*

ie. ansible-playbook user.yml --extra-vars "target=all" --limit imac-1* --list-hosts

which results in:

playbook: user.yml

  play #1 (office): host count=2
    imac-10.local
    imac-11.local

Ping all addresses in network, windows

for /l %%a in (254, -1, 1) do ( 
    for /l %%b in (1, 1, 254) do (
        for %%c in (20, 168) do (
            for %%e in (172, 192) do (
                ping /n 1 %%e.%%c.%%b.%%a>>ping.txt
            )
        )
    )
)
pause>nul

git - Server host key not cached

I too had the same issue when I was trying to clone a repository on my Windows 7 machine. I tried most of the answers mentioned here. None of them worked for me.

What worked for me was, running the Pageant (Putty authentication agent) program. Once the Pageant was running in the background I was able to clone, push & pull from/to the repository. This worked for me, may be because I've setup my public key such that whenever it is used for the first time a password is required & the Pageant starts up.

How to get multiple counts with one SQL query?

For MySQL, this can be shortened to:

SELECT distributor_id,
    COUNT(*) total,
    SUM(level = 'exec') ExecCount,
    SUM(level = 'personal') PersonalCount
FROM yourtable
GROUP BY distributor_id

Can Json.NET serialize / deserialize to / from a stream?

I've written an extension class to help me deserializing from JSON sources (string, stream, file).

public static class JsonHelpers
{
    public static T CreateFromJsonStream<T>(this Stream stream)
    {
        JsonSerializer serializer = new JsonSerializer();
        T data;
        using (StreamReader streamReader = new StreamReader(stream))
        {
            data = (T)serializer.Deserialize(streamReader, typeof(T));
        }
        return data;
    }

    public static T CreateFromJsonString<T>(this String json)
    {
        T data;
        using (MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(json)))
        {
            data = CreateFromJsonStream<T>(stream);
        }
        return data;
    }

    public static T CreateFromJsonFile<T>(this String fileName)
    {
        T data;
        using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
        {
            data = CreateFromJsonStream<T>(fileStream);
        }
        return data;
    }
}

Deserializing is now as easy as writing:

MyType obj1 = aStream.CreateFromJsonStream<MyType>();
MyType obj2 = "{\"key\":\"value\"}".CreateFromJsonString<MyType>();
MyType obj3 = "data.json".CreateFromJsonFile<MyType>();

Hope it will help someone else.

UEFA/FIFA scores API

UEFA internally provides their own LIVEX Api for their Broadcasting Partners. That one is perfect enough to develop the Applications by their partners for themselves.

Cleanest way to reset forms

component.html (What you named you form)

<form [formGroup]="contactForm">

(add click event (click)="clearForm())

<button (click)="onSubmit()" (click)="clearForm()" type="submit" class="btn waves-light" mdbWavesEffect>Send<i class="fa fa-paper-plane-o ml-1"></i></button>

component.ts

 clearForm() {
             this.contactForm.reset();
            }

view all code: https://ewebdesigns.com.au/angular-6-contact-form/ How to add a contact form with firebase

How to make inline plots in Jupyter Notebook larger?

Yes, play with figuresize and dpi like so (before you call your subplot):

fig=plt.figure(figsize=(12,8), dpi= 100, facecolor='w', edgecolor='k')

As @tacaswell and @Hagne pointed out, you can also change the defaults if it's not a one-off:

plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 100 # 200 e.g. is really fine, but slower

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

Why can't I shrink a transaction log file, even after backup?

I tried all the solutions listed and none of them worked. I ended up having to do a sp_detach_db, then deleting the ldf file and re-attaching the database forcing it to create a new ldf file. That worked.

How to deep watch an array in angularjs?

You can set the 3rd argument of $watch to true:

$scope.$watch('data', function (newVal, oldVal) { /*...*/ }, true);

See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Since Angular 1.1.x you can also use $watchCollection to watch shallow watch (just the "first level" of) the collection.

$scope.$watchCollection('data', function (newVal, oldVal) { /*...*/ });

See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchCollection

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Listing all extras of an Intent

Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
    Log.d("KEY", iterator.next());
}

How to write multiple conditions in Makefile.am with "else if"

I would accept ldav1s' answer if I were you, but I just want to point out that 'else if' can be written in terms of 'else's and 'if's in any language:

if HAVE_CLIENT
  libtest_LIBS = $(top_builddir)/libclient.la
else
  if HAVE_SERVER
    libtest_LIBS = $(top_builddir)/libserver.la
  else
    libtest_LIBS = 
  endif
endif

(The indentation is for clarity. Don't indent the lines, they won't work.)

Comparing two collections for equality irrespective of the order of items in them

EDIT: I realized as soon as I posed that this really only works for sets -- it will not properly deal with collections that have duplicate items. For example { 1, 1, 2 } and { 2, 2, 1 } will be considered equal from this algorithm's perspective. If your collections are sets (or their equality can be measured that way), however, I hope you find the below useful.

The solution I use is:

return c1.Count == c2.Count && c1.Intersect(c2).Count() == c1.Count;

Linq does the dictionary thing under the covers, so this is also O(N). (Note, it's O(1) if the collections aren't the same size).

I did a sanity check using the "SetEqual" method suggested by Daniel, the OrderBy/SequenceEquals method suggested by Igor, and my suggestion. The results are below, showing O(N*LogN) for Igor and O(N) for mine and Daniel's.

I think the simplicity of the Linq intersect code makes it the preferable solution.

__Test Latency(ms)__
N, SetEquals, OrderBy, Intersect    
1024, 0, 0, 0    
2048, 0, 0, 0    
4096, 31.2468, 0, 0    
8192, 62.4936, 0, 0    
16384, 156.234, 15.6234, 0    
32768, 312.468, 15.6234, 46.8702    
65536, 640.5594, 46.8702, 31.2468    
131072, 1312.3656, 93.7404, 203.1042    
262144, 3765.2394, 187.4808, 187.4808    
524288, 5718.1644, 374.9616, 406.2084    
1048576, 11420.7054, 734.2998, 718.6764    
2097152, 35090.1564, 1515.4698, 1484.223

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

Set port for php artisan.php serve

Laravel 5.8 to 8.0 and above

The SERVER_PORT environment variable will be picked up and used by Laravel. Either do:

export SERVER_PORT="8080"
php artisan serve

Or set SERVER_PORT=8080 in your .env file.

Earlier versions of Laravel:

For port 8080:

 php artisan serve --port=8080

And if you want to run it on port 80, you probably need to sudo:

sudo php artisan serve --port=80

Predicate in Java

You can view the java doc examples or the example of usage of Predicate here

Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:

 // the age column to be between 7 and 10
    AgeFilter filter = new AgeFilter(7, 10, 3);

    // set the filter.
    resultset.beforeFirst();
    resultset.setFilter(filter);

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

Syntax error: Illegal return statement in JavaScript

In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.

Example:

function a() {
    if (global_block) //syntax error is actually here - missing opening brace
       return;
    } //this unintentionally ends the function

    if (global_somethingelse) {
       //Chrome will show the error occurring here, 
       //but actually the error is in the previous statement
       return; 
    }

    //do something
}

How do I convert uint to int in C#?

I would say using tryParse, it'll return 'false' if the uint is to big for an int.
Don't forget that a uint can go much bigger than a int, as long as you going > 0

How to create an array of 20 random bytes?

Create a Random object with a seed and get the array random by doing:

public static final int ARRAY_LENGTH = 20;

byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);

What is correct media query for IPad Pro?

Too late but may this save you from headache! All of these is because we have to detect the target browser is a mobile!

Is this a mobile then combine it with min/max-(width/height)'s

So Just this seems works:

@media (hover: none) {
    /* ... */
}

If the primary input mechanism system of the device cannot hover over elements with ease or they can but not easily (for example a long touch is performed to emulate the hover) or there is no primary input mechanism at all, we use none! There are many cases that you can read from bellow links.

Described as well Also for browser Support See this from MDN

Why would one use nested classes in C++?

One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:

class Product{
    public:
        class Builder;
}
class Product::Builder {
    // Builder Implementation
}

Rather than:

class Product {}
class ProductBuilder {}

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Regex match entire words only

If you are doing it in Notepad++

[\w]+ 

Would give you the entire word, and you can add parenthesis to get it as a group. Example: conv1 = Conv2D(64, (3, 3), activation=LeakyReLU(alpha=a), padding='valid', kernel_initializer='he_normal')(inputs). I would like to move LeakyReLU into its own line as a comment, and replace the current activation. In notepad++ this can be done using the follow find command:

([\w]+)( = .+)(LeakyReLU.alpha=a.)(.+)

and the replace command becomes:

\1\2'relu'\4 \n    # \1 = LeakyReLU\(alpha=a\)\(\1\)

The spaces is to keep the right formatting in my code. :)

Inherit CSS class

You dont inherit in css, you simply add another class to the element which overrides the values

.base{    
  color:green;
  ...other props
}

.basealt{
   color:red;
}

<span class="base basealt"></span>

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

Try installing this, it's a known workaround for enabling the C++ compiler for Python 2.7.

In my experience, when pip does not find vcvarsall.bat compiler, all I do is opening a Visual Studio console as it set the path variables to call vcvarsall.bat directly and then I run pip on this command line.

DbEntityValidationException - How can I easily tell what caused the error?

Actually, this is just the validation issue, EF will validate the entity properties first before making any changes to the database. So, EF will check whether the property's value is out of range, like when you designed the table. Table_Column_UserName is varchar(20). But, in EF, you entered a value that longer than 20. Or, in other cases, if the column does not allow to be a Null. So, in the validation process, you have to set a value to the not null column, no matter whether you are going to make the change on it. I personally, like the Leniel Macaferi answer. It can show you the detail of the validation issues

What is apache's maximum url length?

The default limit for the length of the request line is 8192 bytes = 8* 1024. It you want to change the limit, you have to add or update in your tomcat server.xml the attribut maxHttpHeaderSize.

as:

<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />

In this example I set the limite to 65536 bytes= 64*1024.

Hope this will help.

Visual Studio 2017 errors on standard headers

This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.

Example:

  • EXE with C++ 17 enabled explicitly
  • Unit Test with C++ version set to "Default"

Solution: change the Unit Test to C++17 as well.

Screenshot

How to Clear Console in Java?

Try this code

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, it will clear the console.

XAMPP Apache won't start

Look in the control panel: the service has not been installed yet!

Click the (X) button to install apache in windows service and reboot, it should be working now.

Test if string is a number in Ruby on Rails

Tl;dr: Use a regex approach. It is 39x faster than the rescue approach in the accepted answer and also handles cases like "1,000"

def regex_is_number? string
  no_commas =  string.gsub(',', '')
  matches = no_commas.match(/-?\d+(?:\.\d+)?/)
  if !matches.nil? && matches.size == 1 && matches[0] == no_commas
    true
  else
    false
  end
end

--

The accepted answer by @Jakob S works for the most part, but catching exceptions can be really slow. In addition, the rescue approach fails on a string like "1,000".

Let's define the methods:

def rescue_is_number? string
  true if Float(string) rescue false
end

def regex_is_number? string
  no_commas =  string.gsub(',', '')
  matches = no_commas.match(/-?\d+(?:\.\d+)?/)
  if !matches.nil? && matches.size == 1 && matches[0] == no_commas
    true
  else
    false
  end
end

And now some test cases:

test_cases = {
  true => ["5.5", "23", "-123", "1,234,123"],
  false => ["hello", "99designs", "(123)456-7890"]
}

And a little code to run the test cases:

test_cases.each do |expected_answer, cases|
  cases.each do |test_case|
    if rescue_is_number?(test_case) != expected_answer
      puts "**rescue_is_number? got #{test_case} wrong**"
    else
      puts "rescue_is_number? got #{test_case} right"
    end

    if regex_is_number?(test_case) != expected_answer
      puts "**regex_is_number? got #{test_case} wrong**"
    else
      puts "regex_is_number? got #{test_case} right"
    end  
  end
end

Here is the output of the test cases:

rescue_is_number? got 5.5 right
regex_is_number? got 5.5 right
rescue_is_number? got 23 right
regex_is_number? got 23 right
rescue_is_number? got -123 right
regex_is_number? got -123 right
**rescue_is_number? got 1,234,123 wrong**
regex_is_number? got 1,234,123 right
rescue_is_number? got hello right
regex_is_number? got hello right
rescue_is_number? got 99designs right
regex_is_number? got 99designs right
rescue_is_number? got (123)456-7890 right
regex_is_number? got (123)456-7890 right

Time to do some performance benchmarks:

Benchmark.ips do |x|

  x.report("rescue") { test_cases.values.flatten.each { |c| rescue_is_number? c } }
  x.report("regex") { test_cases.values.flatten.each { |c| regex_is_number? c } }

  x.compare!
end

And the results:

Calculating -------------------------------------
              rescue   128.000  i/100ms
               regex     4.649k i/100ms
-------------------------------------------------
              rescue      1.348k (±16.8%) i/s -      6.656k
               regex     52.113k (± 7.8%) i/s -    260.344k

Comparison:
               regex:    52113.3 i/s
              rescue:     1347.5 i/s - 38.67x slower

Android Facebook style slide

The Facebook Android app is possibly build with Fragments. The menu is one Fragment, the in-depth Activity (Newsfeed/Events/Friends etc) is the other Fragment. Basically a tablet 'master & detail' layout on a phone.

Google Map API v3 — set bounds and center

The answers are perfect for adjust map boundaries for markers but if you like to expand Google Maps boundaries for shapes like polygons and circles, you can use following codes:

For Circles

bounds.union(circle.getBounds());

For Polygons

polygon.getPaths().forEach(function(path, index)
{
    var points = path.getArray();
    for(var p in points) bounds.extend(points[p]);
});

For Rectangles

bounds.union(overlay.getBounds());

For Polylines

var path = polyline.getPath();

var slat, blat = path.getAt(0).lat();
var slng, blng = path.getAt(0).lng();

for(var i = 1; i < path.getLength(); i++)
{
    var e = path.getAt(i);
    slat = ((slat < e.lat()) ? slat : e.lat());
    blat = ((blat > e.lat()) ? blat : e.lat());
    slng = ((slng < e.lng()) ? slng : e.lng());
    blng = ((blng > e.lng()) ? blng : e.lng());
}

bounds.extend(new google.maps.LatLng(slat, slng));
bounds.extend(new google.maps.LatLng(blat, blng));

How to do "If Clicked Else .."

You may actually mean hovering the element by not clicking, right?

jQuery('#id').click(function()
{
    // execute on click
}).hover(function()
{
    // execute on hover
});

Clarify your question then we'll be able to understand better.

Simply if an element isn't being clicked on, do a setInterval to continue the process until clicked.

var checkClick = setInterval(function()
{
    // do something when the element hasn't been clicked yet
}, 2000); // every 2 seconds

jQuery('#id').click(function()
{
    clearInterval(checkClick); // this is optional, but it will
                               // clear the interval once the element
                               // has been clicked on

    // do something else
})

How to capitalize the first letter of word in a string using Java?

public String capitalizeFirstLetter(String original) {
    if (original == null || original.length() == 0) {
        return original;
    }
    return original.substring(0, 1).toUpperCase() + original.substring(1);
}

Just... a complete solution, I see it kind of just ended up combining what everyone else ended up posting =P.

Batch script loop

DOS doesn't offer very elegant mechanisms for this, but I think you can still code a loop for 100 or 200 iterations with reasonable effort. While there's not a numeric for loop, you can use a character string as a "loop variable."

Code the loop using GOTO, and for each iteration use SET X=%X%@ to add yet another @ sign to an environment variable X; and to exit the loop, compare the value of X with a string of 100 (or 200) @ signs.

I never said this was elegant, but it should work!

where does MySQL store database files?

another way from MySQL Workbench:

enter image description here

Concat strings by & and + in VB.Net

My 2 cents:

If you are concatenating a significant amount of strings, you should be using the StringBuilder instead. IMO it's cleaner, and significantly faster.

int value under 10 convert to string two digit number

I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.

Now, you can also use String Interpolation for same solution.

Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.

String Interpolation

i.ToString("00")
01

i.ToString("000")
001

i.ToString("0000")
0001

$"Prefix_{i:00}"
Prefix_01

$"Prefix_{i:000}"
Prefix_001

$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix

pycharm running way slow

In my case, the problem was a folder in the project directory containing 300k+ files totaling 11Gb. This was just a temporary folder with images results of some computation. After moving this folder out of the project structure, the slowness disappeared. I hope this can help someone, please check your project structure to see if there is anything that is not necessary.

Application Crashes With "Internal Error In The .NET Runtime"

In my case this exception was occured when disk space was over and .NET can't allocate memory in Windows Virtual Memory.

In event log I saw this error:

Application popup: Windows - Virtual Memory Minimum Too Low : Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied.

And previous error:

The C: disk is at or near capacity. You may need to delete some files.

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

How can I get this ASP.NET MVC SelectList to work?

This is an option:

myViewData.PageOptionsDropDown = new[] 
{
 new SelectListItem { Text = "10", Value = "10" },
 new SelectListItem { Text = "15", Value = "15", Selected = true }
 new SelectListItem { Text = "25", Value = "25" },
 new SelectListItem { Text = "50", Value = "50" },
 new SelectListItem { Text = "100", Value = "100" },
 new SelectListItem { Text = "1000", Value = "1000" },
}

How to get first and last element in an array in java?

Getting first and last elements in an array in Java

int[] a = new int[]{1, 8, 5, 9, 4};

First Element: a[0]

Last Element: a[a.length-1]

python dataframe pandas drop column using int

You can simply supply columns parameter to df.drop command so you don't to specify axis in that case, like so

columns_list = [1, 2, 4] # index numbers of columns you want to delete
df = df.drop(columns=df.columns[columns_list])

For reference see columns parameter here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html?highlight=drop#pandas.DataFrame.drop

How can I create an editable dropdownlist in HTML?

HTML doesn't have a built-in editable dropdown list or combobox, but I implemented a mostly-CSS solution in an article.

You can see a full demo here but in summary, write HTML like this:

<span class="combobox withtextlist">
  <input value="Fruit">
  <span tabindex="-1" class="downarrow"></span>
  <select size="10" class="sticky">
    <option>Apple</option>
    <option>Banana</option>
    <option>Cherry</option>
    <option>Dewberry</option>
  </select>
</span>

And use CSS like this to style it (this is designed for both comboboxes, which have a down-arrow ? button, and dropdown menus which open when clicked and may be styled differently):

/* ------------------------------------------ */
/* ----- combobox / dropdown list styling     */
/* ------------------------------------------ */
.combobox {
  /* Border slightly darker than Chrome's <select>, slightly lighter than FireFox's */
  border: 1px solid #999;
  padding-right: 1.25em; /* leave room for ? */
}
.dropdown, .combobox { 
  /* "relative" and "inline-block" (or just "block") are needed
     here so that "absolute" works correctly in children */
  position: relative;
  display: inline-block;
}
.combobox > .downarrow, .dropdown > .downarrow {
  /* ? Outside normal flow, relative to container */
  display: inline-block;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  width: 1.25em;

  cursor: default;
  nav-index: -1; /* nonfunctional in most browsers */

  border-width: 0px;          /* disable by default */
  border-style: inherit; /* copy parent border */
  border-color: inherit; /* copy parent border */
}
/* Add a divider before the ? down arrow in non-dropdown comboboxes */
.combobox:not(.dropdown) > .downarrow {
  border-left-width: 1px;
}
/* Auto-down-arrow if one is not provided */
.downarrow:empty::before {
  content: '?';
}
.downarrow::before, .downarrow > *:only-child {
  text-align: center;

  /* vertical centering trick */
  position: relative;
  top: 50%;
  display: block; /* transform requires block/inline-block */
  transform: translateY(-50%);
}
.combobox > input {
  border: 0
}
.dropdown > *:last-child,
.combobox > *:last-child {
  /* Using `display:block` here has two desirable effects:
     (1) Accessibility: it lets input widgets in the dropdown to
         be selected with the tab key when the dropdown is closed. 
     (2) It lets the opacity transition work.
     But it also makes the contents visible, which is undesirable 
     before the list drops down. To compensate, use `opacity: 0`
     and disable mouse pointer events. Another side effect is that
     the user can select and copy the contents of the hidden list,
     but don't worry, the selected content is invisible. */
  display: block;
  opacity: 0;
  pointer-events: none;

  transition: 0.4s; /* fade out */
  position: absolute;
  left: 0;
  top: 100%;
  border: 1px solid #888;
  background-color: #fff;
  box-shadow: 1px 2px 4px 1px #666;
  box-shadow: 1px 2px 4px 1px #4448;
  z-index: 9999;
  min-width: 100%;
  box-sizing: border-box;
}
/* List of situations in which to show the dropdown list.
   - Focus dropdown or non-last child of it => show last-child
   - Focus .downarrow of combobox => show last-child
   - Stay open for focus in last child, unless .less-sticky
   - .sticky last child stays open on hover
   - .less-sticky stays open on hover, ignores focus in last-child */
.dropdown:focus > *:last-child,
.dropdown > *:focus ~ *:last-child,
.combobox > .downarrow:focus ~ *:last-child,
.combobox > .sticky:last-child:hover,
.dropdown > .sticky:last-child:hover,
.combobox > .less-sticky:last-child:hover,
.dropdown > .less-sticky:last-child:hover,
.combobox > *:last-child:focus:not(.less-sticky),
.dropdown > *:last-child:focus:not(.less-sticky) {
  display: block;
  opacity: 1;
  transition: 0.15s;
  pointer-events: auto;
}
/* focus-within not supported by Edge/IE. Unsupported selectors cause 
   the entire block to be ignored, so we must repeat all styles for 
   focus-within separately. */
.combobox > *:last-child:focus-within:not(.less-sticky),
.dropdown > *:last-child:focus-within:not(.less-sticky) {
  display: block;
  opacity: 1;
  transition: 0.15s;
  pointer-events: auto;
}
/* detect Edge/IE and behave if though less-sticky is on for all
   dropdowns (otherwise links won't be clickable) */
@supports (-ms-ime-align:auto) {
  .dropdown > *:last-child:hover {
    display: block;
    opacity: 1;
    pointer-events: auto;
  }
}
/* detect IE and do the same thing. */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
  .dropdown > *:last-child:hover {
    display: block;
    opacity: 1;
    pointer-events: auto;
  }
}
.dropdown:not(.sticky) > *:not(:last-child):focus,
.downarrow:focus, .dropdown:focus {
  pointer-events: none; /* Causes second click to close */
}
.downarrow:focus {
  outline: 2px solid #8BF; /* Edge/IE can't do outline transparency */
  outline: 2px solid #48F8;
}

/* ---------------------------------------------- */
/* Optional extra styling for combobox / dropdown */
/* ---------------------------------------------- */
*, *:before, *:after {
  /* See https://css-tricks.com/international-box-sizing-awareness-day/ */
  box-sizing: border-box; 
}
.combobox > *:first-child {
  display: inline-block;
  width: 100%;
  box-sizing: border-box; /* so 100% includes border & padding */
}
/* `.combobox:focus-within { outline:...}` doesn't work properly 
   in Firefox because the focus box is expanded to include the 
   (possibly hidden) drop list. As a workaround, put focus box on 
   the focused child. It is barely-visible so that it doesn't look
   TOO ugly if the child isn't the same size as the parent. It
   may be uglier if the first child is not styled as width:100% */
.combobox > *:not(:last-child):focus {
  outline: 2px solid #48F8;
}
.combobox {
  margin: 5px; 
}

You also need some JavaScript to synchronize the list with the textbox:

function parentComboBox(el) {
    for (el = el.parentNode; el != null && Array.prototype.indexOf.call(el.classList, "combobox") <= -1;)
        el = el.parentNode;
    return el;
}
// Uses jQuery
$(".combobox.withtextlist > select").change(function() { 
  var textbox = parentComboBox(this).firstElementChild;
  textbox.value = this[this.selectedIndex].text;
});
$(".combobox.withtextlist > select").keypress(function(e) {
  if (e.keyCode == 13) // Enter pressed
    parentComboBox(this).firstElementChild.focus(); // Closes the popup
});

How to use forEach in vueJs?

The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.

Native Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]

Underscore Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);

Regular expression for address field validation

As a simple one line expression recommend this,

^([a-zA-z0-9/\\''(),-\s]{2,255})$

Best way to retrieve variable values from a text file?

hbn's answer won't work out of the box if the file to load is in a subdirectory or is named with dashes.

In such a case you may consider this alternative :

exec open(myconfig.py).read()

Or the simpler but deprecated in python3 :

execfile(myconfig.py)

I guess Stephan202's warning applies to both options, though, and maybe the loop on lines is safer.

Split function in oracle to comma separated values with automatic sequence

This function returns the nth part of input string MYSTRING. Second input parameter is separator ie., SEPARATOR_OF_SUBSTR and the third parameter is Nth Part which is required.

Note: MYSTRING should end with the separator.

create or replace FUNCTION PK_GET_NTH_PART(MYSTRING VARCHAR2,SEPARATOR_OF_SUBSTR VARCHAR2,NTH_PART NUMBER)
RETURN VARCHAR2
IS
NTH_SUBSTR VARCHAR2(500);
POS1 NUMBER(4);
POS2 NUMBER(4);
BEGIN
IF NTH_PART=1 THEN
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, 1)  INTO POS1 FROM DUAL; 
SELECT SUBSTR(MYSTRING,0,POS1-1) INTO NTH_SUBSTR FROM DUAL;
ELSE
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART-1) INTO  POS1 FROM DUAL; 
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART)  INTO POS2 FROM DUAL; 
SELECT SUBSTR(MYSTRING,POS1+1,(POS2-POS1-1)) INTO NTH_SUBSTR FROM DUAL;
END IF;
RETURN NTH_SUBSTR;
END;

Hope this helps some body, you can use this function like this in a loop to get all the values separated:

SELECT REGEXP_COUNT(MYSTRING, '~', 1, 'i') INTO NO_OF_RECORDS FROM DUAL;
WHILE NO_OF_RECORDS>0
LOOP
    PK_RECORD    :=PK_GET_NTH_PART(MYSTRING,'~',NO_OF_RECORDS);
    -- do some thing
    NO_OF_RECORDS  :=NO_OF_RECORDS-1;
END LOOP;

Here NO_OF_RECORDS,PK_RECORD are temp variables.

Hope this helps.

Can I access variables from another file?

One best way is by using window.INITIAL_STATE

<script src="/firstfile.js">
    // first.js
    window.__INITIAL_STATE__ = {
      back  : "#fff",
      front : "#888",
      side  : "#369"
    };
</script>
<script src="/secondfile.js">
    //second.js
    console.log(window.__INITIAL_STATE__)
    alert (window.__INITIAL_STATE__);
</script>

How to clear text area with a button in html using javascript?

<input type="button" value="Clear" onclick="javascript: functionName();" >

you just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

Turn a single number into single digits Python

This can be done quite easily if you:

  1. Use str to convert the number into a string so that you can iterate over it.

  2. Use a list comprehension to split the string into individual digits.

  3. Use int to convert the digits back into integers.

Below is a demonstration:

>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

<select name="country" formControlName="country" id="country" 
       class="formcontrol form-control-element" [(ngModel)]="country">
   <option value="90">Turkey</option>
   <option value="1">USA</option>
   <option value="30">Greece</option>
</select>
name="country"
formControlName="country" 
[(ngModel)]="country" 

Those are the three things need to use ngModel inside a formGroup directive.

Note that same name should be used.

Getting an option text/value with JavaScript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

Redirecting to a relative URL in JavaScript

You can do a relative redirect:

window.location.href = '../'; //one level up

or

window.location.href = '/path'; //relative to domain

sql select with column name like

Blorgbeard had a great answer for SQL server. If you have a MySQL server like mine then the following will allow you to select the information from columns where the name is like some key phrase. You just have to substitute the table name, database name, and keyword.

SET @columnnames = (SELECT concat("`",GROUP_CONCAT(`COLUMN_NAME` SEPARATOR "`, `"),"`") 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='your_database' 
    AND `TABLE_NAME`='your_table'
    AND COLUMN_NAME LIKE "%keyword%");

SET @burrito = CONCAT("SELECT ",@columnnames," FROM your_table");

PREPARE result FROM @burrito;
EXECUTE result;

Equivalent to 'app.config' for a library (DLL)

As far as I'm aware, you have to copy + paste the sections you want from the library .config into the applications .config file. You only get 1 app.config per executable instance.