Programs & Examples On #Expression studio

How to see full absolute path of a symlink

realpath <path to the symlink file> should do the trick.

Java Initialize an int array in a constructor

private int[] data = new int[3];

This already initializes your array elements to 0. You don't need to repeat that again in the constructor.

In your constructor it should be:

data = new int[]{0, 0, 0};

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

If it is not Oracle's Java, you may not be able to tell. When I install Oracle Java 64-bit, the files go into C:\Program Files\Java, but when I install a 32-bit version, they default to C:\Program Files (x86)\Java instead. Of course, the person who installed Java could have overridden those defaults.

How to maintain state after a page refresh in React.js?

I may be late but actual code for react-create-app for react > 16 ver. After each change state is saved in sessionStorage (not localStorage) and is crypted via crypto-js. On refresh (when user demands refresh of the page by clicking refresh button) state is loaded from the storage. I also recommend not to use sourceMaps in build to avoid readablility of the key phrases.

my index.js

import React from "react";
import ReactDOM from "react-dom";
import './index.css';
import App from './containers/App';
import * as serviceWorker from './serviceWorker';
import {createStore} from "redux";
import {Provider} from "react-redux"
import {BrowserRouter} from "react-router-dom";
import rootReducer from "./reducers/rootReducer";
import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Utf8.parse("someRandomText_encryptionPhase");
const iv = CryptoJS.enc.Utf8.parse("someRandomIV");
const persistedState = loadFromSessionStorage();

let store = createStore(rootReducer, persistedState,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

function loadFromSessionStorage() {
    try {
        const serializedState = sessionStorage.getItem('state');
        if (serializedState === null) {
            return undefined;
        }
        const decrypted = CryptoJS.AES.decrypt(serializedState, key, {iv: iv}).toString(CryptoJS.enc.Utf8);
        return JSON.parse(decrypted);
    } catch {
        return undefined;
    }
}

function saveToSessionStorage(state) {
        try {
            const serializedState = JSON.stringify(state);
            const encrypted = CryptoJS.AES.encrypt(serializedState, key, {iv: iv});
            sessionStorage.setItem('state', encrypted)
        } catch (e) {
            console.log(e)
        }
}

ReactDOM.render(
    <BrowserRouter>
        <Provider store={store}>
            <App/>
        </Provider>
    </BrowserRouter>,
    document.getElementById('root')
);

store.subscribe(() => saveToSessionStorage(store.getState()));

serviceWorker.unregister();

Converting a Java Keystore into PEM Format

The keytool command will not allow you to export the private key from a key store. You have to write some Java code to do this. Open the key store, get the key you need, and save it to a file in PKCS #8 format. Save the associated certificate too.

KeyStore ks = KeyStore.getInstance("jks");
/* Load the key store. */
...
char[] password = ...;
/* Save the private key. */
FileOutputStream kos = new FileOutputStream("tmpkey.der");
Key pvt = ks.getKey("your_alias", password);
kos.write(pvt.getEncoded());
kos.flush();
kos.close();
/* Save the certificate. */
FileOutputStream cos = new FileOutputStream("tmpcert.der");
Certificate pub = ks.getCertificate("your_alias");
cos.write(pub.getEncoded());
cos.flush();
cos.close();

Use OpenSSL utilities to convert these files (which are in binary format) to PEM format.

openssl pkcs8 -inform der -nocrypt < tmpkey.der > tmpkey.pem
openssl x509 -inform der < tmpcert.der > tmpcert.pem

Storing image in database directly or as base64 data?

I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database

Swap DIV position with CSS only

assuming both elements have 50% width, here is what i used:

css:

  .parent {
    width: 100%;
    display: flex;
  }  
  .child-1 {
    width: 50%;
    margin-right: -50%;
    margin-left: 50%;
    background: #ff0;
  }
  .child-2 {
    width: 50%;
    margin-right: 50%;
    margin-left: -50%;
    background: #0f0;
  }

html:

<div class="parent">
  <div class="child-1">child1</div>
  <div class="child-2">child2</div>
</div>

example: https://jsfiddle.net/gzveri/o6umhj53/

btw, this approach works for any 2 nearby elements in a long list of elements. For example I have a long list of elements with 2 items per row and I want each 3-rd and 4-th element in the list to be swapped, so that it renders elements in a chess style, then I use these rules:

  .parent > div:nth-child(4n+3) {
    margin-right: -50%;
    margin-left: 50%;
  }
  .parent > div:nth-child(4n+4) {
    margin-right: 50%;
    margin-left: -50%;
  }

When should I use curly braces for ES6 import?

The curly braces ({}) are used to import named bindings and the concept behind it is destructuring assignment

A simple demonstration of how import statement works with an example can be found in my own answer to a similar question at When do we use '{ }' in javascript imports?.

Use a LIKE statement on SQL Server XML Datatype

You should be able to do this quite easily:

SELECT * 
FROM WebPageContent 
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'

The .value method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.

Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:

  • create a stored function which gets the XML and returns the value you're looking for as a VARCHAR()
  • define a new computed field on your table which calls this function, and make it a PERSISTED column

With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).

Marc

Wait one second in running program

Personally I think Thread.Sleep is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.

Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));

//Note Forms.Timer and Timer() have similar implementations. 

public static void DelayAction(int millisecond, Action action)
{
    var timer = new DispatcherTimer();
    timer.Tick += delegate

    {
        action.Invoke();
        timer.Stop();
    };

    timer.Interval = TimeSpan.FromMilliseconds(millisecond);
    timer.Start();
}

Using a different font with twitter bootstrap

First of all you have to include your font in your website (or your CSS, to be more specific) using an appropriate @font-face rule.
From here on there are multiple ways to proceed. One thing I would not do is to edit the bootstrap.css directly - since once you get a newer version your changes will be lost. You do however have the possibility to customize your bootstrap files (there's a customize page on their website). Just enter the name of your font with all the fallback names into the corresponding typography textbox. Of course you will have to do this whenever you get a new or updated version of your bootstrap files.
Another chance you have is to overwrite the bootstrap rules within a different stylesheet. If you do this you just have to use selectors that are as specific as (or more specific than) the bootstrap selectors.
Side note: If you care about browser support a single EOT version of your font might not be sufficient. See http://caniuse.com/eot for a support table.

Understanding the set() function

Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).

If you'd like to sort them, you can simply perform:

sorted(set(y))

which will produce a sorted list containing the set's elements. (Not a set. Again, sets are unordered.)

Otherwise, the only thing guaranteed by set is that it makes the elements unique (nothing will be there more than once).

Hope this helps!

What is javax.inject.Named annotation supposed to be used for?

Use @Named to differentiate between different objects of the same type bound in the same scope.

@Named("maxWaitTime")
public long maxWaitTimeMs;

@Named("minWaitTime")
public long minWaitTimeMs;

Without the @Named qualifier, the injector would not know which long to bind to which variable.

  • If you want to create annotations that act like @Named, use the @Qualifier annotation when creating them.

  • If you look at @Named, it is itself annotated with @Qualifier.

Form Submit Execute JavaScript Best Practice?

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

Where does git config --global get written to?

I had installed my Git in: C:\Users\_myuserfolder_\AppData\Local\Programs\Git

SQL get the last date time record

this working

SELECT distinct filename
,last_value(dates)over (PARTITION BY filename ORDER BY filename)posd
,last_value(status)over (PARTITION BY filename ORDER BY filename )poss
FROM distemp.dbo.Shmy_table

REST API error return good practices

Please stick to the semantics of protocol. Use 2xx for successful responses and 4xx , 5xx for error responses - be it your business exceptions or other. Had using 2xx for any response been the intended use case in the protocol, they would not have other status codes in the first place.

How to draw checkbox or tick mark in GitHub Markdown table?

Now emojis are supported! :white_check_mark: / :heavy_check_mark: gives a good impression and is widely supported:

Function | MySQL / MariaDB | PostgreSQL | SQLite
:------------ | :-------------| :-------------| :-------------
substr | :heavy_check_mark: |  :white_check_mark: | :heavy_check_mark:

renders to (here on older chromium 65.0.3x) :

enter image description here

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

SQL Not Like Statement not working

Just come across this, the answer is simple, use ISNULL. SQL won't return rows if the field you are testing has no value (in some of the records) when doing a text comparison search, eg:

WHERE wpp.comment NOT LIKE '%CORE%'

So, you have temporarily substitute a value in the null (empty) records by using the ISNULL command, eg

WHERE (ISNULL(wpp.comment,'')) NOT LIKE '%CORE%'

This will then show all your records that have nulls and omit any that have your matching criteria. If you wanted, you could put something in the commas to help you remember, eg

WHERE (ISNULL(wpp.comment,'some_records_have_no_value')) NOT LIKE '%CORE%'

Shortcut to comment out a block of code with sublime text

Just in case someone is using the Portuguese ABNT keyboard layout The shortcut is

Ctrl + ;

How to get relative path of a file in visual studio?

I think using this will be the easiest

new Uri("pack://application:,,/FolderIcon/" + youImageICO);

or this code will work on any machine that if your folder is in your root project if you want to change it... just change this section @"..\"

public static string bingPathToAppDir(string localPath)
{
    string currentDir = Environment.CurrentDirectory;
    DirectoryInfo directory = new DirectoryInfo(
        Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + localPath)));
    return directory.ToString();
}

Python convert csv to xlsx

Here's an example using xlsxwriter:

import os
import glob
import csv
from xlsxwriter.workbook import Workbook


for csvfile in glob.glob(os.path.join('.', '*.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'rt', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()

FYI, there is also a package called openpyxl, that can read/write Excel 2007 xlsx/xlsm files.

Hope that helps.

vertical align middle in <div>

Try this:

.main_div{
    display: table;
    width: 100%;
}
.cells {
    display: table-cell;
    vertical-align: middle;
}

Another method for centering a div:

<div id="parent">
    <div id="child">Content here</div>
</div>

#parent {position: relative;}

#child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 50px;
    height: 100px;
    margin: auto;
}

Visual Studio 2012 Web Publish doesn't copy files

I found the I could get around this problem by changing the target location from obj/[release|stage|..] to a new path outside of the solution folders completely eg c:\deployment. It seems like VS 2012 was getting confused and maybe giving up somewhere during the publish process.

Matt

Redirect all output to file in Bash

Credits to osexp2003 and j.a. …


Instead of putting:

&>> your_file.log

behind a line in:

crontab -e

I use:

#!/bin/bash
exec &>> your_file.log
…

at the beginning of a BASH script.

Advantage: You have the log definitions within your script. Good for Git etc.

Adding extra zeros in front of a number using jQuery?

By adding 100 to the number, then run a substring function from index 1 to the last position in right.

var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);

console.log(month,day);

you will got this result from the date of 2020-11-3

11,03

I hope the answer is useful

matplotlib: Group boxplots

Mock data:

df = pd.DataFrame({'Group':['A','A','A','B','C','B','B','C','A','C'],\
                  'Apple':np.random.rand(10),'Orange':np.random.rand(10)})
df = df[['Group','Apple','Orange']]

        Group    Apple     Orange
    0      A  0.465636  0.537723
    1      A  0.560537  0.727238
    2      A  0.268154  0.648927
    3      B  0.722644  0.115550
    4      C  0.586346  0.042896
    5      B  0.562881  0.369686
    6      B  0.395236  0.672477
    7      C  0.577949  0.358801
    8      A  0.764069  0.642724
    9      C  0.731076  0.302369

You can use the Seaborn library for these plots. First melt the dataframe to format data and then create the boxplot of your choice.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dd=pd.melt(df,id_vars=['Group'],value_vars=['Apple','Orange'],var_name='fruits')
sns.boxplot(x='Group',y='value',data=dd,hue='fruits')

enter image description here

1030 Got error 28 from storage engine

Check your /backup to see if you can delete an older not needed backup.

How do I uninstall a package installed using npm link?

npm link pain:

-Module name gulp-task

-Project name project-x


You want to link gulp-task:

1: Go to the gulp-task directory then do npm link this will symlink the project to your global modules

2: Go to your project project-x then do npm install make sure to remove the current node_modules directory


Now you want to remove this madness and use the real gulp-task, we have two options:

Option 1: Unlink via npm:

1: Go to your project and do npm unlink gulp-task this will remove the linked installed module

2: Go to the gulp-task directory and do npm unlink to remove symlink. Notice we didn't use the name of the module

3: celebrate


What if this didn't work, verify by locating your global installed module. My are location ls -la /usr/local/lib/node_modules/ if you are using nvm it will be a different path


Option 2: Remove the symlink like a normal linux guru

1: locate your global dependencies cd /usr/local/lib/node_modules/

2: removing symlink is simply using the rm command

rm gulp-task make sure you don't have / at the end

rm gulp-task/ is wrong

rm gulp-task ??

How to pass the button value into my onclick event function?

Maybe you can take a look at closure in JavaScript. Here is a working solution:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8" />_x000D_
        <title>Test</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <p class="button">Button 0</p>_x000D_
        <p class="button">Button 1</p>_x000D_
        <p class="button">Button 2</p>_x000D_
        <script>_x000D_
            var buttons = document.getElementsByClassName('button');_x000D_
            for (var i=0 ; i < buttons.length ; i++){_x000D_
              (function(index){_x000D_
                buttons[index].onclick = function(){_x000D_
                  alert("I am button " + index);_x000D_
                };_x000D_
              })(i)_x000D_
            }_x000D_
        </script>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Excel formula to display ONLY month and year?

First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.

How to check variable type at runtime in Go language

The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}. If you use a concrete type it will fail.

An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect package. Chaining TypeOf(x).Kind() together you can get a reflect.Kind value which is a uint type: http://golang.org/pkg/reflect/#Kind

You can then do checks for types outside of a switch block, like so:

import (
    "fmt"
    "reflect"
)

// ....

x := 42
y := float32(43.3)
z := "hello"

xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()

fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)

if xt == reflect.Int {
    println(">> x is int")
}
if yt == reflect.Float32 {
    println(">> y is float32")
}
if zt == reflect.String {
    println(">> z is string")
}

Which prints outs:

reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string

Again, this is probably not the preferred way to do it, but it's good to know alternative options.

How to use Python to login to a webpage and retrieve cookies for later usage?

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

How to set custom location for local installation of npm package?

TL;DR

You can do this by using the --prefix flag and the --global* flag.

pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower

*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

TL;DR

Every configurable attribute of npm can be set in any of six different places. In order of priority:

  • Command-Line Flags: --prefix ./vendor/node_modules
  • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
  • User Config File: $HOME/.npmrc or userconfig param
  • Global Config File: $PREFIX/etc/npmrc or userconfig param
  • Built-In Config File: path/to/npm/itself/npmrc
  • Default Config: node_modules/npmconf/config-defs.js

By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

You can run npm config list to see your current config and npm config edit to change it.

PS

In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

What is a good way to handle exceptions when trying to read a file in python?

How about this:

try:
    f = open(fname, 'rb')
except OSError:
    print "Could not open/read file:", fname
    sys.exit()

with f:
    reader = csv.reader(f)
    for row in reader:
        pass #do stuff here

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

I was getting this error today. And above answers didn't help me. I was getting this error when I try to start the SQL Server(SQLEXPRESS) service in Services(services.msc).

When I checked the error log at the location C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Log, there was an entry related TCP/IP port.

2018-06-19 20:41:52.20 spid12s TDSSNIClient initialization failed with error 0x271d, status code 0xa. Reason: Unable to initialize the TCP/IP listener. An attempt was made to access a socket in a way forbidden by its access permissions.

Recently I was running a MSSQLEXPRESS image in my docker container, which was using the same TCP/IP port, that caused this issue.

enter image description here

So, what I did is, I just reset my TCP/IP by doing the below command.

netsh int ip reset resetlog.txt

enter image description here

Once the resetting is done, I had to restart the machine and when I try to start the SQLEXPRESS service again, it started successfully. Hope it helps.

How to add an Android Studio project to GitHub

  1. Sign up and create a GitHub account in www.github.com.
  2. Download git from https://git-scm.com/downloads and install it in your system.
  3. Open the project in android studio and go to File -> Settings -> Version Control -> Git.
  4. Click on test button to test "path to Git executables". If successful message is shown everything is ok, else navigate to git.exe from where you installed git and test again.
  5. Go to File -> Settings -> Version Control -> GitHub. Enter your email and password used to create GitHub account and click on OK button.
  6. Then go to VCS -> Import into Version Control -> Share Project on GitHub. Enter Repository name, Description and click Share button.
  7. In the next window check all files inorder to add files for initial commit and click OK.
  8. Now the project will be uploaded to the GitHub repository and when uploading is finished we will get a message in android studio showing "Successfully shared project on GitHub". Click on the link provided in that message to go to GitHub repository.

How to import a jar in Eclipse

In eclipse I included a compressed jar file i.e. zip file. Eclipse allowed me to add this zip file as an external jar but when I tried to access the classes in the jar they weren't showing up.

After a lot of trial and error I found that using a zip format doesn't work. When I added a jar file then it worked for me.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.

That said, please try the following filter and see if you're getting the entries that you think you should be getting:

dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7

svn cleanup: sqlite: database disk image is malformed

After a power blackout, I ran into the database disk image is malformed error and the suggested reindex nodes command did not fix all issues due to violated constraints. Also the procedure described in http://mail-archives.apache.org/mod_mbox/subversion-users/201111.mbox/%[email protected]%3E did not resolve the problem.

Solution in my case:

  • Checkout the svn repository again into a temporary folder
  • Copy, i.e. replace, the file ".svn/wc.db" from the new checkout to the corrupt one

This may be useful, if your original svn checkout contains many modified or unversioned files and you don't want to switch to a fresh svn checkout.

nginx upload client_max_body_size issue

nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size by sending a 413 response and closing the connection.

Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.

If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large response rather than 100 Continue if Content-Length exceeds the maximum body size.

Java: Reading integers from a file into an array

You might want to do something like this (if you're in java 5 & up)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
   tall[i++] = scanner.nextInt();
}

Int to Decimal Conversion - Insert decimal point at specified location

Simple math.

double result = ((double)number) / 100.0;

Although you may want to use decimal rather than double: decimal vs double! - Which one should I use and when?

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

is there a require for json in node.js

Two of the most common

First way :

let jsonData = require('./JsonFile.json')

let jsonData = require('./JsonFile') // if we omitting .json also works

OR

import jsonData from ('./JsonFile.json')

Second way :

1) synchronously

const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))

2) asynchronously

const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
  if (err) throw err

  jsonData = JSON.parse(data)
})

Note: 1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')

2) The fs.readFile or fs.readFileSync will always re read the file, and get changes

print arraylist element?

Here is an updated solution for Java8, using lambdas and streams:

System.out.println(list.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining("\n")));

Or, without joining the list into one large string:

list.stream().forEach(System.out::println);

React.js: Identifying different inputs with one onChange handler

Deprecated solution

valueLink/checkedLink are deprecated from core React, because it is confusing some users. This answer won't work if you use a recent version of React. But if you like it, you can easily emulate it by creating your own Input component

Old answer content:

What you want to achieve can be much more easily achieved using the 2-way data binding helpers of React.

var Hello = React.createClass({
    mixins: [React.addons.LinkedStateMixin],
    getInitialState: function() {
        return {input1: 0, input2: 0};
    },

    render: function() {
        var total = this.state.input1 + this.state.input2;
        return (
            <div>{total}<br/>
                <input type="text" valueLink={this.linkState('input1')} />;
                <input type="text" valueLink={this.linkState('input2')} />;
            </div>
        );
    }

});

React.renderComponent(<Hello />, document.getElementById('content'));

Easy right?

http://facebook.github.io/react/docs/two-way-binding-helpers.html

You can even implement your own mixin

How to manage a redirect request after a jQuery Ajax call

this worked for me:

success: function(data, textStatus, xhr) {

        console.log(xhr.status);
}

on success, ajax will get the same status code the browser gets from the server and execute it.

Bootstrap 4 File Input

You can try below given snippet to display the selected file name from the file input type.

document.querySelectorAll('input[type=file]').forEach( input => {
    input.addEventListener('change', e => {
        e.target.nextElementSibling.innerText = input.files[0].name;
    });
});

Find the last element of an array while using a foreach loop in PHP

If you need to do something for every element except either the first or the last and only if there is more than one element in the array, I prefer the following solution.

I know there are many solutions above and posted months/one year before mine, but this is something I feel is fairly elegant in its own right. The check every loop is also a boolean check as opposed to a numeric "i=(count-1)" check, which may allow for less overhead.

The structure of the loop may feel awkward, but you can compare it to the ordering of thead (beginning), tfoot (end), tbody (current) in HTML table tags.

$first = true;
foreach($array as $key => $value) {
    if ($first) {
        $first = false;
        // Do what you want to do before the first element
        echo "List of key, value pairs:\n";
    } else {
        // Do what you want to do at the end of every element
        // except the last, assuming the list has more than one element
        echo "\n";
    }
    // Do what you want to do for the current element
    echo $key . ' => ' . $value;
}

For instance, in web development terms, if you want to add a border-bottom to every element except the last in an unordered list (ul), then you can instead add a border-top to every element except the first (the CSS :first-child, supported by IE7+ and Firefox/Webkit supports this logic, whereas :last-child is not supported by IE7).

You can feel free to reuse the $first variable for each and every nested loop as well and things will work just fine since every loop makes $first false during the first process of the first iteration (so breaks/exceptions won't cause issues).

$first = true;
foreach($array as $key => $subArray) {
    if ($first) {
        $string = "List of key => value array pairs:\n";
        $first = false;
    } else {
        echo "\n";
    }

    $string .= $key . '=>(';
    $first = true;
    foreach($subArray as $key => $value) {
        if ($first) {
            $first = false;
        } else {
            $string .= ', ';
        }
        $string .= $key . '=>' . $value;
    }
    $string .= ')';
}
echo $string;

Example output:

List of key => value array pairs:
key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
key3=>(v3_key1=>v3_val1)

What is the meaning of curly braces?

A dictionary is something like an array that's accessed by keys (e.g. strings,...) rather than just plain sequential numbers. It contains key/value pairs, you can look up values using a key like using a phone book: key=name, number=value.

For defining such a dictionary, you use this syntax using curly braces, see also: http://wiki.python.org/moin/SimplePrograms

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If you install the application on your device via adb install you should look for the reinstall option which should be -r. So if you do adb install -r you should be able to install without uninstalling before.

How do I declare a global variable in VBA?

If this function is in a module/class, you could just write them outside of the function, so it has Global Scope. Global Scope means the variable can be accessed by another function in the same module/class (if you use dim as declaration statement, use public if you want the variables can be accessed by all function in all modules) :

Dim iRaw As Integer
Dim iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1
End Function

Function this_can_access_global()
    iRaw = 2
    iColumn = 2
End Function

Shortcut to create properties in Visual Studio?

Start from:

private int myVar;

When you select "myVar" and right click then select "Refactor" and select "Encapsulate Field".

It will automatically create:

{
    get { return myVar; }
    set { myVar = value; }
}

Or you can shortcut it by pressing Ctrl + R + E.

why should I make a copy of a data frame in pandas

Assumed you have data frame as below

df1
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

When you would like create another df2 which is identical to df1, without copy

df2=df1
df2
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

And would like modify the df2 value only as below

df2.iloc[0,0]='changed'

df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

At the same time the df1 is changed as well

df1
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Since two df as same object, we can check it by using the id

id(df1)
140367679979600
id(df2)
140367679979600

So they as same object and one change another one will pass the same value as well.


If we add the copy, and now df1 and df2 are considered as different object, if we do the same change to one of them the other will not change.

df2=df1.copy()
id(df1)
140367679979600
id(df2)
140367674641232

df1.iloc[0,0]='changedback'
df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Good to mention, when you subset the original dataframe, it is safe to add the copy as well in order to avoid the SettingWithCopyWarning

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

To my knowledge the only difference is the scope of the effects as Strommy said. NOLOCK hint on a table and the READ UNCOMMITTED on the session.

As to problems that can occur, it's all about consistency. If you care then be aware that you could get what is called dirty reads which could influence other data being manipulated on incorrect information.

I personally don't think I have seen any problems from this but that may be more due to how I use nolock. You need to be aware that there are scenarios where it will be OK to use. Scenarios where you are mostly adding new data to a table but have another process that comes in behind to check for a data scenario. That will probably be OK since the major flow doesn't include going back and updating rows during a read.

Also I believe that these days you should look into Multi-version Concurrency Control. I believe they added it in 2005 and it helps stop the writers from blocking readers by giving readers a snapshot of the database to use. I'll include a link and leave further research to the reader:

MVCC

Database Isolation Levels

Running a command as Administrator using PowerShell?

If the current console is not elevated and the operation you're trying to do requires elevated privileges then you can start powershell with the Run as Administrator option :

PS> Start-Process powershell -Verb runAs

https://docs.microsoft.com/powershell/module/Microsoft.PowerShell.Management/Start-Process

How do I bind a List<CustomObject> to a WPF DataGrid?

You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:

<Grid>
    <DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799"  ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False"> </Grid>

C#

Public Class Test 
{
    public string m_field1_Test{get;set;}
    public string m_field2_Test { get; set; }
    public Test()
    {
        m_field1_Test = "field1";
        m_field2_Test = "field2";
    }
    public MainWindow()
    {

        listTest = new List<Test>();

        for (int i = 0; i < 10; i++)
        {
            obj = new Test();
            listTest.Add(obj);

        }

        this.MyDatagrid.ItemsSource = ListTest;

        InitializeComponent();

    }

warning: implicit declaration of function

When you get the error: implicit declaration of function it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname and look at the SYNOPSIS section at the top, as this section will list any header files that need to be included. Or try http://linux.die.net/man/ This is the online man pages they are hyperlinked and easy to search. Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,

You are using a function for which the compiler has not seen a declaration ("prototype") yet.

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

If you're using ASP.NET Core and wonder why you get this message in one of your async controller methods, make sure you return a Task rather than void - ASP.NET Core disposes injected contexts.

(I'm posting this answer as this question is high in the search results to that exception message and it's a subtle issue - maybe it's useful to people who Google for it.)

What are the differences between if, else, and else if?

An if statement follows this sort of structure:

if (condition)
{
    // executed only if "condition" is true
}
else if (other condition)
{
    // executed only if "condition" was false and "other condition" is true
}
else
{
    // executed only if both "condition" and "other condition" were false
}

The if portion is the only block that is absolutely mandatory. else if allows you to say "ok, if the previous condition was not true, then if this condition is true...". The else says "if none of the conditions above were true..."

You can have multiple else if blocks, but only one if block and only one (or zero) else blocks.

How to create a foreign key in phpmyadmin

To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab. Storage Engine Configuration

Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.

Index list

Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.

enter image description here

See attachments. I hope this could be useful for anyone.

Is there a way to cache GitHub credentials for pushing commits?

If you don't want to store your password in plaintext like Mark said, you can use a different GitHub URL for fetching than you do for pushing. In your configuration file, under [remote "origin"]:

url = git://github.com/you/projectName.git
pushurl = [email protected]:you/projectName.git

It will still ask for a password when you push, but not when you fetch, at least for open source projects.

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:

[sdl]
windowresolution=1280x960
output=opengl

Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    /home/USERNAME/.dosbox/dosbox-0.74.conf
    $ vi "$(dosbox -printconf)"
    $ dosbox
    
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf
    

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    [snip]
    ---
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
    [snip]
    
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

How to send Basic Auth with axios

The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-Security header in the response.

Adding withCredentials: true will solve that issue.

  axios.post(session_url, {
    withCredentials: true,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
  },{
    auth: {
      username: "USERNAME",
      password: "PASSWORD"
  }}).then(function(response) {
    console.log('Authenticated');
  }).catch(function(error) {
    console.log('Error on Authentication');
  });

Why don’t my SVG images scale using the CSS "width" property?

SVGs are different than bitmap images such as PNG etc. If an SVG has a viewBox - as yours appear to - then it will be scaled to fit it's defined viewport. It won't directly scale like a PNG would.

So increasing the width of the img won't make the icons any taller if the height is restricted. You'll just end up with the img horizontally centred in a wider box.

I believe your problem is that your SVGs have a fixed height defined in them. Open up the SVG files and make sure they either:

  1. have no width and height defined, or
  2. have width and height both set to "100%".

That should solve your problem. If it doesn't, post one of your SVGs into your question so we can see how it is defined.

What is REST? Slightly confused

REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.

The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:

/posts Would be how a user would access ALL the posts, for displaying.

/posts/:id Would be how a user would access and view an individual post, retrieved based on their unique id.

/posts/new Would be how you would display a form for creating a new post.

Sending a POST request to /users would be how you would actually create a new post on the database level.

Sending a PUT request to /users/:id would be how you would update the attributes of a given post, again identified by a unique id.

Sending a DELETE request to /users/:id would be how you would delete a given post, again identified by a unique id.

As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.

I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).

When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.

How can I count occurrences with groupBy?

Here is example for list of Objects

Map<String, Long> requirementCountMap = requirements.stream().collect(Collectors.groupingBy(Requirement::getRequirementType, Collectors.counting()));

Python: Generate random number between x and y which is a multiple of 5

The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.

To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.

MySQL select rows where left join is null

SELECT table1.id 
FROM table1 
LEFT JOIN table2 ON table1.id = table2.user_one
WHERE table2.user_one is NULL

Reading Excel file using node.js

There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.

Node-xlsx

Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.

node-xlsx project page

Example for parsing file

var xlsx = require('node-xlsx');

var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file

var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer

ExcelJS

Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.

exceljs project page

Code example:

// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
    .then(function() {
        // use workbook
    });

// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

Android EditText for password with android:hint

I had the same issue and found a solution :

Previous code:

    <EditText 
    android:layout_height="wrap_content"
    android:gravity="center" 
    android:inputType ="password" 
    android:layout_width="fill_parent"
    android:id="@+id/password" 
    android:hint="password" 
    android:maxLines="1">
    </EditText>

Solution:

<EditText 
android:layout_height="wrap_content"
android:gravity="center" 
android:password="true" 
android:layout_width="fill_parent"
android:id="@+id/password" 
android:hint="password" 
android:maxLines="1">
</EditText>

The previous code does not show the 'hint', but when I changed it to the last one it started showing...

hope this be helpful to someone...

Launch Image does not show up in my iOS App

The problem with the accepted answer is that if you don't set the Launch Screen File, your application will be in upscaling mode on devices such as the iPhone 6 & 6+ => blurry rendering.

Below is what I did to have a complete working solution (I'm targeting iOS 7.1 & using Xcode 8) on every device (truly, I was getting crazy about this upscaling problem)

1. Prepare your .xcassets

To simplify it, I'm using a vector .PDF file. It is very convenient and avoid creating multiple images for each resolution (1x, 2x, 3x...). I also assume here you already created your xcassets.

  • Add your launch screen image (or vector file) to your project
  • Go to your .xcassets and create a New Image Set. In the Attributes window of the Image, select Scales -> Single Scale
  • Drag and drop the vector file in the Image Set.

Create an Image Set for your .xcassets

2. Create your Launch Screen file

Create a Launch Screen file

3. Add your image to your Launch Screen file

  • Add an Image View object to your Launch Screen file (delete the labels that were automatically created). This image view should refer to the previous .xcassets Image Set. You can refer it from the Name attribute. At this stage, you should correctly see your launch screen image in your image view.
  • Add constraints to this image view to keep aspect ratio depending on the screen resolution.

Add the splash screen image to your Launch Screen file

4. Add your Launch Screen file to your target

Fianlly, in your Target General properties, refer the Launch Screen file. Target Properties and Launch Screen

Start your app, and your splash screen should be displayed. Try also on iPhone6 & iPhone6+, and your application should be correctly displayed without any upscaling (the Launch Screen file aims to do this).

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

var isProduction = (process.argv.indexOf("production")>-1);

CLI gulp production calls my production task and sets a flag for any conditionals.

How to find the maximum value in an array?

If you can change the order of the elements:

 int[] myArray = new int[]{1, 3, 8, 5, 7, };
 Arrays.sort(myArray);
 int max = myArray[myArray.length - 1];

If you can't change the order of the elements:

int[] myArray = new int[]{1, 3, 8, 5, 7, };
int max = Integer.MIN_VALUE;
for(int i = 0; i < myArray.length; i++) {
      if(myArray[i] > max) {
         max = myArray[i];
      }
}

HMAC-SHA256 Algorithm for signature calculation

This is working fine for me

I have add dependency

compile 'commons-codec:commons-codec:1.9'

ref: http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9

my function

public String encode(String key, String data) {
    try {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        return new String(Hex.encodeHex(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

How to change the commit author for one specific commit?

For the merge commit message, I found that I cannot amend it by using rebase, at least on gitlab. It shows the merge as a commit but I cannot rebase onto that #sha. I found this post is helpful.

git checkout <sha of merge>
git commit --amend # edit message
git rebase HEAD previous_branch

This three lines of code did the job for changing the merge commit message (like author).

Pointers in JavaScript?

Late answer but I have come across a way of passing primitive values by reference by means of closures. It is rather complicated to create a pointer, but it works.

function ptr(get, set) {
    return { get: get, set: set };
}

function helloWorld(namePtr) {
    console.log(namePtr.get());
    namePtr.set('jack');
    console.log(namePtr.get())
}

var myName = 'joe';
var myNamePtr = ptr(
    function () { return myName; },
    function (value) { myName = value; }
);

helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack

In ES6, the code can be shortened to use lambda expressions:

var myName = 'joe';
var myNamePtr = ptr(=> myName, v => myName = v);

helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

Reading a text file in MATLAB line by line

Just read it in to MATLAB in one block

fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);

You can then process it using logical addressing

ind50 = data{2}>=50 ;

ind50 is then an index of the rows where column 2 is greater than 50. So

data{1}(ind50)

will list all the strings for the rows of interest. Then just use fprintf to write out your data to the new file

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

How to insert strings containing slashes with sed?

In a system I am developing, the string to be replaced by sed is input text from a user which is stored in a variable and passed to sed.

As noted earlier on this post, if the string contained within the sed command block contains the actual delimiter used by sed - then sed terminates on syntax error. Consider the following example:

This works:

$ VALUE=12345
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
MyVar=12345

This breaks:

$ VALUE=12345/6
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
sed: -e expression #1, char 21: unknown option to `s'

Replacing the default delimiter is not a robust solution in my case as I did not want to limit the user from entering specific characters used by sed as the delimiter (e.g. "/").

However, escaping any occurrences of the delimiter in the input string would solve the problem. Consider the below solution of systematically escaping the delimiter character in the input string before having it parsed by sed. Such escaping can be implemented as a replacement using sed itself, this replacement is safe even if the input string contains the delimiter - this is since the input string is not part of the sed command block:

$ VALUE=$(echo ${VALUE} | sed -e "s#/#\\\/#g")
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
MyVar=12345/6

I have converted this to a function to be used by various scripts:

escapeForwardSlashes() {

     # Validate parameters
     if [ -z "$1" ]
     then
             echo -e "Error - no parameter specified!"
             return 1
     fi

     # Perform replacement
     echo ${1} | sed -e "s#/#\\\/#g"
     return 0
}

What are .tpl files? PHP, web design

Those look like Smarty templates. There should be some additional PHP scripts which actually instantiate the Smarty engine and give it the data it can use for the replaceable elements.

Formula to determine brightness of RGB color

For clarity, the formulas that use a square root need to be

sqrt(coefficient * (colour_value^2))

not

sqrt((coefficient * colour_value))^2

The proof of this lies in the conversion of a R=G=B triad to greyscale R. That will only be true if you square the colour value, not the colour value times coefficient. See Nine Shades of Greyscale

Numpy - add row to array

What is X? If it is a 2D-array, how can you then compare its row to a number: i < 3?

EDIT after OP's comment:

A = array([[0, 1, 2], [0, 2, 0]])
X = array([[0, 1, 2], [1, 2, 0], [2, 1, 2], [3, 2, 0]])

add to A all rows from X where the first element < 3:

import numpy as np
A = np.vstack((A, X[X[:,0] < 3]))

# returns: 
array([[0, 1, 2],
       [0, 2, 0],
       [0, 1, 2],
       [1, 2, 0],
       [2, 1, 2]])

How to use `@ts-ignore` for a block

If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I have one same Warning caused to com.google.gms:google-services.

The solution is to upgrade classpath com.google.gms:google-services to classpath 'com.google.gms:google-services:3.2.0' in file in build.gradle Project:

enter image description here

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.2.0'
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

In Android Studio verion 3.1 dependencies complie word is replaced to implementation

dependencies with Warning in android studio 3.1

dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:27.1.0'
            compile 'com.android.support.constraint:constraint-layout:1.0.2'
            testImplementation 'junit:junit:4.12'
            androidTestImplementation 'com.android.support.test:runner:1.0.1'
            androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    }

dependencies OK in android studio 3.1

    dependencies {
            implementation fileTree(dir: 'libs', include: ['*.jar'])
            implementation 'com.android.support:appcompat-v7:27.1.0'
            implementation 'com.android.support.constraint:constraint-layout:1.0.2'
            testImplementation 'junit:junit:4.12'
            androidTestImplementation 'com.android.support.test:runner:1.0.1'
            androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    }

Gradel generate by Android Studio 3.1 for new project.

Gradel generate by Android Studio 3.1 for new project.

Visit https://docs.gradle.org/current/userguide/dependency_management_for_java_projects.html

For details https://docs.gradle.org/current/userguide/declaring_dependencies.html

Jquery click not working with ipad

None of the upvoted solutions worked for me. Here's what eventually worked:

I moved the code which was in $(document).ready out, if it wasn't required in document ready. If it's mandatory to have it in document ready, then you move that critical code to jQuery(window).load().

HTML Form: Select-Option vs Datalist-Option

Data List is a new HTML tag in HTML5 supported browsers. It renders as a text box with some list of options. For Example for Gender Text box it will give you options as Male Female when you type 'M' or 'F' in Text Box.

<input list="Gender">
<datalist id="Gender">
  <option value="Male">
  <option value="Female> 
</datalist>

What does \0 stand for?

In C \0 is a character literal constant store into an int data type that represent the character with value of 0.

Since Objective-C is a strict superset of C this constant is retained.

How to get the current date and time of your timezone in Java?

Check this may be helpful. Works fine for me. Code also covered daylight savings

    TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
    Calendar cal = Calendar.getInstance();      
    // If needed in hours rather than milliseconds
    int LocalOffSethrs = (int) ((cal.getTimeZone().getRawOffset()) *(2.77777778 /10000000));        
    int ChinaOffSethrs = (int) ((tz.getRawOffset()) *(2.77777778 /10000000));       
    int dts = cal.getTimeZone().getDSTSavings();
    System.out.println("Local Time Zone : " + cal.getTimeZone().getDisplayName());
    System.out.println("Local Day Light Time Saving : " + dts);
    System.out.println("China Time : " + tz.getRawOffset());
    System.out.println("Local Offset Time from GMT: " + LocalOffSethrs);
    System.out.println("China Offset Time from GMT: " + ChinaOffSethrs);    
    // Adjust to GMT
    cal.add(Calendar.MILLISECOND,-(cal.getTimeZone().getRawOffset()));  
    // Adjust to Daylight Savings
    cal.add(Calendar.MILLISECOND, - cal.getTimeZone().getDSTSavings());
    // Adjust to Offset
    cal.add(Calendar.MILLISECOND, tz.getRawOffset());       
    Date dt = new Date(cal.getTimeInMillis());              
    System.out.println("After adjusting offset Acctual China Time :" + dt); 

How to find longest string in the table column data

Instead of SELECT max(len(CR)) AS Max_Length_String FROM table1

Use

SELECT (CR) FROM table1

WHERE len(CR) = (SELECT max(len(CR)) FROM table1)

How do I iterate over the words of a string?

Short and elegant

#include <vector>
#include <string>
using namespace std;

vector<string> split(string data, string token)
{
    vector<string> output;
    size_t pos = string::npos; // size_t to avoid improbable overflow
    do
    {
        pos = data.find(token);
        output.push_back(data.substr(0, pos));
        if (string::npos != pos)
            data = data.substr(pos + token.size());
    } while (string::npos != pos);
    return output;
}

can use any string as delimiter, also can be used with binary data (std::string supports binary data, including nulls)

using:

auto a = split("this!!is!!!example!string", "!!");

output:

this
is
!example!string

Custom header to HttpClient request

Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:

using Newtonsoft.Json;
...

var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("https://api.clickatell.com/rest/message"),
        Headers = { 
            { HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
            { HttpRequestHeader.Accept.ToString(), "application/json" },
            { "X-Version", "1" }
        },
        Content = new StringContent(JsonConvert.SerializeObject(svm))
    };

var response = client.SendAsync(httpRequestMessage).Result;

How do I get values from a SQL database into textboxes using C#?

using (SqlConnection connection =  new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
    SqlCommand command =
    new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
    connection.Open();

    SqlDataReader read= command.ExecuteReader();

    while (read.Read())
    {
        CustID.Text = (read["Customer_ID"].ToString());
        CustName.Text = (read["Customer_Name"].ToString());
        Add1.Text = (read["Address_1"].ToString());
        Add2.Text = (read["Address_2"].ToString());
        PostBox.Text = (read["Postcode"].ToString());
        PassBox.Text = (read["Password"].ToString());
        DatBox.Text = (read["Data_Important"].ToString());
        LanNumb.Text = (read["Landline"].ToString());
        MobNumber.Text = (read["Mobile"].ToString());
        FaultRep.Text = (read["Fault_Report"].ToString());
    }
    read.Close();
}

Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"

ReSharper "Cannot resolve symbol" even when project builds

I was just having the same issue with ReSharper 8.2 in Visual Studio 2013, and none of the usual solutions here of clearing caches, suspending ReSharper or re-installing ReSharper was working.

In my case I ended up solving it as follows... I looked at one of the symbols that it couldn't resolve and noted it was in System.Web.Http.dll. I then found that this was in the Microsoft.AspNet.WebApi.Core NuGet package. I used the package manager console to try and uninstall that package, except of course it told me that it couldn't due to other dependencies.

So I uninstalled each dependency up to and including Microsoft.AspNet.WebApi.Core, and then re-installed each package again in the reverse order. ReSharper picked everything up correctly as it was installed, and now seems fine.

macOS on VMware doesn't recognize iOS device

Here is another thing to try (I'm using Windows 10):

  1. Stop the VM.
  2. Open Start.
  3. Type "Services".
  4. Find VMWare USB Arbitration Service and start it.
  5. Connect your device and hopefully, it will be detected.

This is what worked for me. I have no idea why the service wasn't started in the first place and it used to work fine with my IPhone 7. Good luck.

Python 2.6: Class inside a Class?

I think you are confusing objects and classes. A class inside a class looks like this:

class Foo(object):
    class Bar(object):
        pass

>>> foo = Foo()
>>> bar = Foo.Bar()

But it doesn't look to me like that's what you want. Perhaps you are after a simple containment hierarchy:

class Player(object):
    def __init__(self, ... airplanes ...) # airplanes is a list of Airplane objects
        ...
        self.airplanes = airplanes
        ...

class Airplane(object):
    def __init__(self, ... flights ...) # flights is a list of Flight objects
        ...
        self.flights = flights
        ...

class Flight(object):
    def __init__(self, ... duration ...)
        ...
        self.duration = duration
        ...

Then you can build and use the objects thus:

player = Player(...[
    Airplane(... [
        Flight(...duration=10...),
        Flight(...duration=15...),
        ] ... ),
    Airplane(...[
        Flight(...duration=20...),
        Flight(...duration=11...),
        Flight(...duration=25...),
        ]...),
    ])

player.airplanes[5].flights[6].duration = 5

How do I create dynamic variable names inside a loop?

Try this

window['marker'+i] = "some stuff"; 

java howto ArrayList push, pop, shift, and unshift

maybe you want to take a look java.util.Stack class. it has push, pop methods. and implemented List interface.

for shift/unshift, you can reference @Jon's answer.

however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.

make a header full screen (width) css

html:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"
</head>
<body>
<ul class="menu">
    <li><a href="#">My Dashboard</a>
        <ul>
            <li><a href="#" class="learn">Learn</a></li>
            <li><a href="#" class="teach">Teach</a></li>
            <li><a href="#" class="Mylibrary">My Library</a></li>
        </ul>
    </li>
    <li><a href="#">Likes</a>
        <ul>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
        </ul>
</li>
    <li><a href="#">Views</a>
        <ul>
            <li><a href="#" class="documents">Documents</a></li>
            <li><a href="#" class="messages">Messages</a></li>
            <li><a href="#" class="signout">Videos</a></li>
        </ul>
    </li>
        <li><a href="#">account</a>
        <ul>
            <li><a href="#" class="SI">Sign In</a></li>
            <li><a href="#" class="Reg">Register</a></li>
            <li><a href="#" class="Deactivate">Deactivate</a></li>
        </ul>
    </li>
    <li><a href="#">Uploads</a>
        <ul>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
        </ul>
    </li>
    <li><a href="#">Videos</a>
    <ul>
            <li><a href="#" class="Add">Add</a></li>
            <li><a href="#" class="delete">Delete</a></li>
    </ul>
    </li>
    <li><a href="#">Documents</a>
    <ul>
            <li><a href="#" class="Add">Upload</a></li>
            <li><a href="#" class="delete">Download</a></li>
    </ul>
    </li>
</ul>
</body>
</html>

css:

.menu,
.menu ul,
.menu li,
.menu a {
    margin: 0;
    padding: 0;
    border: none;
    outline: none;
}
body{
    max-width:110%;
    margin-left:0;
}
.menu {
    height: 40px;
    width:110%;
    margin-left:-4px;
    margin-top:-10px;

    background: #4c4e5a;
    background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);

    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
}
.menu li {
    position: relative;
    list-style: none;
    float: left;
    display: block;
    height: 40px;
}
.menu li a {
    display: block;
    padding: 0 14px;
    margin: 6px 0;
    line-height: 28px;
    text-decoration: none;

    border-left: 1px solid #393942;
    border-right: 1px solid #4f5058;

    font-family: Helvetica, Arial, sans-serif;
    font-weight: bold;
    font-size: 13px;

    color: #f3f3f3;
    text-shadow: 1px 1px 1px rgba(0,0,0,.6);

    -webkit-transition: color .2s ease-in-out;
    -moz-transition: color .2s ease-in-out;
    -o-transition: color .2s ease-in-out;
    -ms-transition: color .2s ease-in-out;
    transition: color .2s ease-in-out;
}

.menu li:first-child a { border-left: none; }
.menu li:last-child a{ border-right: none; }

.menu li:hover > a { color: #8fde62; }
.menu ul {
    position: absolute;
    top: 40px;
    left: 0;

    opacity: 0;
    background: #1f2024;

    -webkit-border-radius: 0 0 5px 5px;
    -moz-border-radius: 0 0 5px 5px;
    border-radius: 0 0 5px 5px;

    -webkit-transition: opacity .25s ease .1s;
    -moz-transition: opacity .25s ease .1s;
    -o-transition: opacity .25s ease .1s;
    -ms-transition: opacity .25s ease .1s;
    transition: opacity .25s ease .1s;
}

.menu li:hover > ul { opacity: 1; }

.menu ul li {
    height: 0;
    overflow: hidden;
    padding: 0;

    -webkit-transition: height .25s ease .1s;
    -moz-transition: height .25s ease .1s;
    -o-transition: height .25s ease .1s;
    -ms-transition: height .25s ease .1s;
    transition: height .25s ease .1s;
}

.menu li:hover > ul li {
    height: 36px;
    overflow: visible;
    padding: 0;
}

.menu ul li a {
    width: 100px;
    padding: 4px 0 4px 40px;
    margin: 0;

    border: none;
    border-bottom: 1px solid #353539;
}

.menu ul li:last-child a { border: none; }

demo here

try also resizing the browser tab to see it in action

Get the current cell in Excel VB

Have you tried:

For one cell:

ActiveCell.Select

For multiple selected cells:

Selection.Range

For example:

Dim rng As Range
Set rng = Range(Selection.Address)

Cloning a private Github repo

I have a company (private) account and 2-Factor-Authentication enabled, so I had to combine a few posts to make it work as below. (Jotting down so it may be useful to someone with the same situation)

Initially it was the Fatal Error. 
fatal: repository 'https:
...
remote: Repository not found.
fatal: repository 'https:

Installed the credential manager and updated GIT as mentioned here: https://codeshare.co.uk/blog/how-to-solve-the-github-error-fatal-httprequestexception-encountered/

That did not solve the problem as the issue moved to the below when I tried using the clone command as follows:

$ git clone https://<username>:<password>@github.com/<ORG_NAME>/<PROJECT-NAME>.git

remote: Invalid username or password.
fatal: Authentication failed for 'https://

My password had $ symbol in it and for some reason GIT command line / GIT Bash did not like it. I can see this on the error returned text did not have the $ symbol in it.

fatal: Authentication failed for 'https://<username>:<password-missing-$-symbol>@github.com/<ORG_NAME>/<PROJECT-NAME>.git'

I had to reference this site: https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage

Please note: If an incorrect password is stored for your account in Windows Credential Manager it will also add to the problem. I removed the github credential stored this way before moving to the step below.

$ git config --global credential.helper cache
$ git clone https://<username>:<password>@github.com/<ORG_NAME>/<PROJECT-NAME>.git

Now the Windows Credential manager popped-up. I typed my username and password in the text-boxes (This accepted my password that had the $ symbol) and prompted me for a 2-Factor Authentication code. I typed in the authentication code from Google Authenticator, and the clone started perfectly.

PHP - regex to allow letters and numbers only

try this way .eregi("[^A-Za-z0-9.]", $value)

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

How to change background Opacity when bootstrap modal is open

You can override the modal-backdrop opacity in your stylesheet [take note of the .in class]

.modal-backdrop.in {
    opacity: 0.9;
}

http://jsfiddle.net/ThisIsMarkSantiago/r0gwn005/1/

ERROR! MySQL manager or server PID file could not be found! QNAP

I have the same problem. I found the file {username}.local.err instead of {username}.local.pid inside /usr/local/mysql, then i changed the name *.err to *.pid and it works fine.
Starting MySQL. SUCCESS!

My OS El Capitan 10.11.5

How do I revert my changes to a git submodule?

If you want to discard all changes in the entire repository along with sub modules, you can use

git restore . --recurse-submodules

This will undo all changes made in repository and in sub modules.

What is DOM Event delegation?

dom event delegation is something different from the computer science definition.

It refers to handling bubbling events from many elements, like table cells, from a parent object, like the table. It can keep the code simpler, especially when adding or removing elements, and saves some memory.

C# Linq Where Date Between 2 Dates

If someone interested to know how to work with 2 list and between dates

var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))

SQL Switch/Case in 'where' clause

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
@locationID = 
  CASE @locationType
      WHEN 'location' THEN account_location
      WHEN 'area' THEN xxx_location_area 
      WHEN 'division' THEN xxx_location_division 
  END

C# Telnet Library

I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.

You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh

You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.

Python webbrowser.open() to open Chrome browser

Here's a somewhat robust way to get the path to Chrome.

(Note that you should do this only if you specifically need Chrome, and not the default browser, or Chromium, or something else.)

def try_find_chrome_path():
    result = None
    if _winreg:
        for subkey in ['ChromeHTML\\shell\\open\\command', 'Applications\\chrome.exe\\shell\\open\\command']:
            try: result = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
            except WindowsError: pass
            if result is not None:
                result_split = shlex.split(result, False, True)
                result = result_split[0] if result_split else None
                if os.path.isfile(result):
                    break
                result = None
    else:
        expected = "google-chrome" + (".exe" if os.name == 'nt' else "")
        for parent in os.environ.get('PATH', '').split(os.pathsep):
            path = os.path.join(parent, expected)
            if os.path.isfile(path):
                result = path
                break
    return result

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

jQuery datepicker set selected date, on the fly

Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

Facebook Oauth Logout

I can programmatically log user out Facebook by redirecting user to

https://www.facebook.com/logout.php?next=YOUR_REDIRECT_URL&access_token=USER_ACCESS_TOKEN

The URL supplied in the next parameter must be a URL with the same base domain as your application as defined in your app's settings.

More details: https://developers.facebook.com/docs/authentication

How do you connect to multiple MySQL databases on a single webpage?

Instead of mysql_connect use mysqli_connect.

mysqli is provide a functionality for connect multiple database at a time.

$Db1 = new mysqli($hostname,$username,$password,$db_name1); 
// this is connection 1 for DB 1

$Db2 = new mysqli($hostname,$username,$password,$db_name2); 
// this is connection 2 for DB 2

Angular 1 - get current URL parameters

Better would have been generate url like

app.dev/backend?type=surveys&id=2

and then use

var type=$location.search().type;
var id=$location.search().id;

and inject $location in controller.

How do I use tools:overrideLibrary in a build.gradle file?

Use overrideLibrary when the minSdk is declared in build.gradle instead of in AndroidManifest.xml

If you are using Android Studio:

add <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/> to your manifest, don't forget to include xmlns:tools="http://schemas.android.com/tools" too.

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

How to send email in ASP.NET C#

Try the following :

try
{
    var fromEmailAddress =  ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
    var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
    var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
    var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
    var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();

    string body = "Your registration has been done successfully. Thank you.";
    MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(ud.LoginId, ud.FullName));
    message.Subject = "Thank You For Your Registration";
    message.IsBodyHtml = true;
    message.Body = body;

    var client = new SmtpClient();
    client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
    client.Host = smtpHost;
    client.EnableSsl = true;
    client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
    client.Send(message);
}
catch (Exception ex)
{
    throw (new Exception("Mail send failed to loginId " + ud.LoginId + ", though registration done."));
}

And then in you web.config add the following in between

<!--Email Config-->
<add key="FromEmailAddress" value="sender emailaddress"/>
<add key="FromEmailDisplayName" value="Display Name"/>
<add key="FromEmailPassword" value="sender Password"/>
<add key="SMTPHost" value="smtp-proxy.tm.net.my"/>
<add key="SMTPPort" value="smptp Port"/>

Move all files except one

ls ~/Linux/Old/ | grep -v Tux.png | xargs -i {} mv ~/Linux/New/'

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I have faced the same issue. I almost wasted almost couple of weeks to resolved this issue. Finally I had on doubt on myself and tried to create another project by copy and paste some startup files like SplashScreen & LoginScreen.

But with the same code still i was getting SPAN_EXCLUSIVE_EXCLUSIVE.

Then i have removed the handler code from splash screen and tried again and Wow its working. I am not getting SPAN_EXCLUSIVE_EXCLUSIVE issue in logcat.

I wondering, why it is? till the time did not get any other solution but by removing handler from splash screen it is working.

Try and update here if it is resolved or not.

Trigger a keypress/keydown/keyup event in JS/jQuery?

You can trigger any of the events with a direct call to them, like this:

$(function() {
    $('item').keydown();
    $('item').keypress();
    $('item').keyup();
    $('item').blur();
});

Does that do what you're trying to do?

You should probably also trigger .focus() and potentially .change()

If you want to trigger the key-events with specific keys, you can do so like this:

$(function() {
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('item').trigger(e);
});

There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.

Using Cookie in Asp.Net Mvc 4

We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

The error usually gets introduced while creation of CSV. Try using Linux for saving the CSV as a TextCSV. Libre Office in Ubuntu can enforce the encoding to be UTF-8, worked for me. I wasted a lot of time trying this on Mac OS. Linux is the key. I've tested on Ubuntu.

Good Luck

Entity Framework code first unique column

Solution for EF4.3

Unique UserName

Add data annotation over column as:

 [Index(IsUnique = true)]
 [MaxLength(255)] // for code-first implementations
 public string UserName{get;set;}

Unique ID , I have added decoration [Key] over my column and done. Same solution as described here: https://msdn.microsoft.com/en-gb/data/jj591583.aspx

IE:

[Key]
public int UserId{get;set;}

Alternative answers

using data annotation

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("UserId")]

using mapping

  mb.Entity<User>()
            .HasKey(i => i.UserId);
        mb.User<User>()
          .Property(i => i.UserId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
          .HasColumnName("UserId");

html "data-" attribute as javascript parameter

you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object

<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">

<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) { 
    // 
}
</script>

that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing

maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute

<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">

there are probably more terse ways of doing that, if you already know certain things about the order of the data

<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

How to set downloading file name in ASP.NET Web API

This should do:

Response.AddHeader("Content-Disposition", "attachment;filename="+ YourFilename)

Simple working Example of json.net in VB.net

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

How do I update a Python package?

Open Command prompt or terminal and use below syntax

pip install --upgrade [package]==[specific version or latest version]

For Example

pip install --upgrade numpy==1.19.1

How to use forEach in vueJs?

You can also use .map() as:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });

Good examples of python-memcache (memcached) being used in Python?

A good rule of thumb: use the built-in help system in Python. Example below...

jdoe@server:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)

------------------------------------------
NAME
    memcache - client module for memcached (memory cache daemon)

FILE
    /usr/lib/python2.7/dist-packages/memcache.py

MODULE DOCS
    http://docs.python.org/library/memcache

DESCRIPTION
    Overview
    ========

    See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

    Usage summary
    =============
...
------------------------------------------

What exactly is node.js used for?

Node.js is used for easily building fast, scalable network applications

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

What is difference between functional and imperative programming languages?

There seem to be many opinions about what functional programs and what imperative programs are.

I think functional programs can most easily be described as "lazy evaluation" oriented. Instead of having a program counter iterate through instructions, the language by design takes a recursive approach.

In a functional language, the evaluation of a function would start at the return statement and backtrack, until it eventually reaches a value. This has far reaching consequences with regards to the language syntax.

Imperative: Shipping the computer around

Below, I've tried to illustrate it by using a post office analogy. The imperative language would be mailing the computer around to different algorithms, and then have the computer returned with a result.

Functional: Shipping recipes around

The functional language would be sending recipes around, and when you need a result - the computer would start processing the recipes.

This way, you ensure that you don't waste too many CPU cycles doing work that is never used to calculate the result.

When you call a function in a functional language, the return value is a recipe that is built up of recipes which in turn is built of recipes. These recipes are actually what's known as closures.

// helper function, to illustrate the point
function unwrap(val) {
  while (typeof val === "function") val = val();
  return val;
}

function inc(val) {
  return function() { unwrap(val) + 1 };
}

function dec(val) {
  return function() { unwrap(val) - 1 };
}

function add(val1, val2) {
  return function() { unwrap(val1) + unwrap(val2) }
}

// lets "calculate" something

let thirteen = inc(inc(inc(10)))
let twentyFive = dec(add(thirteen, thirteen))

// MAGIC! The computer still has not calculated anything.
// 'thirteen' is simply a recipe that will provide us with the value 13

// lets compose a new function

let doubler = function(val) {
  return add(val, val);
}

// more modern syntax, but it's the same:
let alternativeDoubler = (val) => add(val, val)

// another function
let doublerMinusOne = (val) => dec(add(val, val));

// Will this be calculating anything?

let twentyFive = doubler(thirteen)

// no, nothing has been calculated. If we need the value, we have to unwrap it:
console.log(unwrap(thirteen)); // 26

The unwrap function will evaluate all the functions to the point of having a scalar value.

Language Design Consequences

Some nice features in imperative languages, are impossible in functional languages. For example the value++ expression, which in functional languages would be difficult to evaluate. Functional languages make constraints on how the syntax must be, because of the way they are evaluated.

On the other hand, with imperative languages can borrow great ideas from functional languages and become hybrids.

Functional languages have great difficulty with unary operators like for example ++ to increment a value. The reason for this difficulty is not obvious, unless you understand that functional languages are evaluated "in reverse".

Implementing a unary operator would have to be implemented something like this:

let value = 10;

function increment_operator(value) {
  return function() {
    unwrap(value) + 1;
  }
}

value++ // would "under the hood" become value = increment_operator(value)

Note that the unwrap function I used above, is because javascript is not a functional language, so when needed we have to manually unwrap the value.

It is now apparent that applying increment a thousand times would cause us to wrap the value with 10000 closures, which is worthless.

The more obvious approach, is to actually directly change the value in place - but voila: you have introduced modifiable values a.k.a mutable values which makes the language imperative - or actually a hybrid.

Under the hood, it boils down to two different approaches to come up with an output when provided with an input.

Below, I'll try to make an illustration of a city with the following items:

  1. The Computer
  2. Your Home
  3. The Fibonaccis

Imperative Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Put The Computer into a box and mark it with a sticky note:

    Field Value
    Mail Address The Fibonaccis
    Return Address Your Home
    Parameters 3
    Return Value undefined

    and send off the computer.

  2. The Fibonaccis will upon receiving the box do as they always do:

    • Is the parameter < 2?

      • Yes: Change the sticky note, and return the computer to the post office:

        Field Value
        Mail Address The Fibonaccis
        Return Address Your Home
        Parameters 3
        Return Value 0 or 1 (returning the parameter)

        and return to sender.

      • Otherwise:

        1. Put a new sticky note on top of the old one:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, step 2, c/oThe Fibonaccis
          Parameters 2 (passing parameter-1)
          Return Value undefined

          and send it.

        2. Take off the returned sticky note. Put a new sticky note on top of the initial one and send The Computer again:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, done, c/o The Fibonaccis
          Parameters 2 (passing parameter-2)
          Return Value undefined
        3. By now, we should have the initial sticky note from the requester, and two used sticky notes, each having their Return Value field filled. We summarize the return values and put it in the Return Value field of the final sticky note.

          Field Value
          Mail Address The Fibonaccis
          Return Address Your Home
          Parameters 3
          Return Value 2 (returnValue1 + returnValue2)

          and return to sender.

As you can imagine, quite a lot of work starts immediately after you send your computer off to the functions you call.

The entire programming logic is recursive, but in truth the algorithm happens sequentially as the computer moves from algorithm to algorithm with the help of a stack of sticky notes.

Functional Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Write the following down on a sticky note:

    Field Value
    Instructions The Fibonaccis
    Parameters 3

That's essentially it. That sticky note now represents the computation result of fib(3).

We have attached the parameter 3 to the recipe named The Fibonaccis. The computer does not have to perform any calculations, unless somebody needs the scalar value.

Functional Javascript Example

I've been working on designing a programming language named Charm, and this is how fibonacci would look in that language.

fib: (n) => if (                         
  n < 2               // test
  n                   // when true
  fib(n-1) + fib(n-2) // when false
)
print(fib(4));

This code can be compiled both into imperative and functional "bytecode".

The imperative javascript version would be:

let fib = (n) => 
  n < 2 ?
  n : 
  fib(n-1) + fib(n-2);

The HALF functional javascript version would be:

let fib = (n) => () =>
  n < 2 ?
  n :
  fib(n-1) + fib(n-2);

The PURE functional javascript version would be much more involved, because javascript doesn't have functional equivalents.

let unwrap = ($) =>
  typeof $ !== "function" ? $ : unwrap($());

let $if = ($test, $whenTrue, $whenFalse) => () =>
  unwrap($test) ? $whenTrue : $whenFalse;

let $lessThen = (a, b) => () =>
  unwrap(a) < unwrap(b);

let $add = ($value, $amount) => () =>
  unwrap($value) + unwrap($amount);

let $sub = ($value, $amount) => () =>
  unwrap($value) - unwrap($amount);

let $fib = ($n) => () =>
  $if(
    $lessThen($n, 2),
    $n,
    $add( $fib( $sub($n, 1) ), $fib( $sub($n, 2) ) )
  );

I'll manually "compile" it into javascript code:

"use strict";

// Library of functions:
  /**
   * Function that resolves the output of a function.
   */
  let $$ = (val) => {
    while (typeof val === "function") {
      val = val();
    }
    return val;
  }

  /**
   * Functional if
   *
   * The $ suffix is a convention I use to show that it is "functional"
   * style, and I need to use $$() to "unwrap" the value when I need it.
   */
  let if$ = (test, whenTrue, otherwise) => () =>
    $$(test) ? whenTrue : otherwise;

  /**
   * Functional lt (less then)
   */
  let lt$ = (leftSide, rightSide)   => () => 
    $$(leftSide) < $$(rightSide)


  /**
   * Functional add (+)
   */
  let add$ = (leftSide, rightSide) => () => 
    $$(leftSide) + $$(rightSide)

// My hand compiled Charm script:

  /**
   * Functional fib compiled
   */
  let fib$ = (n) => if$(                 // fib: (n) => if(
    lt$(n, 2),                           //   n < 2
    () => n,                             //   n
    () => add$(fib$(n-2), fib$(n-1))     //   fib(n-1) + fib(n-2)
  )                                      // )

// This takes a microsecond or so, because nothing is calculated
console.log(fib$(30));

// When you need the value, just unwrap it with $$( fib$(30) )
console.log( $$( fib$(5) ))

// The only problem that makes this not truly functional, is that
console.log(fib$(5) === fib$(5)) // is false, while it should be true
// but that should be solveable

https://jsfiddle.net/819Lgwtz/42/

What is the documents directory (NSDocumentDirectory)?

You can access documents directory using this code it is basically used for storing file in plist format:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;

check if array is empty (vba excel)

The problem with VBA is that there are both dynamic and static arrays...

Dynamic Array Example

Dim myDynamicArray() as Variant

Static Array Example

Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant

Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.

So for clarity's sake, I named my function "IsZeroLengthArray".

    Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
        'Tell VBA to proceed if there is an error to the next line.
        On Error Resume Next
    
        Dim UpperBound As Integer
        Dim ErrorNumber As Long
        Dim ErrorDescription As String
        Dim ErrorSource As String
    
        'If the array is empty this will throw an error because a zero-length 
          'array has no UpperBound (or LowerBound).
        'This only works for dynamic arrays.  If this was a static array there 
          'would be both an upper and lower bound.
        UpperBound = UBound(subject)


        'Store the Error Number and then clear the Error object 
         'because we want VBA to treat unintended errors normally
        ErrorNumber = Err.Number
        ErrorDescription = Err.Description
        ErrorSource = Err.Source
        Err.Clear
        On Error GoTo 0
    
        'Check the Error Object to see if we have a "subscript out of range" error.  
          'If we do (the number is 9) then we can assume that the array is zero-length.
        If ErrorNumber = 9 Then
            IsZeroLengthArray = True

        'If the Error number is something else then 9 we want to raise 
        'that error again...
        ElseIf ErrorNumber <> 0 Then
            Err.Raise ErrorNumber, ErrorSource, ErrorDescription

        'If the Error number is 0 then we have no error and can assume that the
         'array is not of zero-length
        ElseIf ErrorNumber = 0 Then
            IsZeroLengthArray = False
        End If
    End Function

I hope that this helps others as it helped me.

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <label>Email</label>
    <input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  
  </form>
</section>

and controller code:

app.controller('MainCtrl', function($scope) {  
  $scope.save = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
      console.log(model); 
    } else {
      console.log('Errors in form data');
    }
  };
});

I hope this helps.

How to initialize an array of custom objects

The simplest way to initialize an array

Create array

$array = @()

Create your header

$line = "" | select name,age,phone

Fill the line

$line.name = "Leandro"
$line.age = "39"
$line.phone = "555-555555"

Add line to $array

$array += $line

Result

$array

name                                                     age                                                      phone
----                                                     ---                                                      -----
Leandro                                                  39                                                       555-555555

Why can't C# interfaces contain fields?

Interfaces in C# are intended to define the contract that a class will adhere to - not a particular implementation.

In that spirit, C# interfaces do allow properties to be defined - which the caller must supply an implementation for:

interface ICar
{
    int Year { get; set; }
}

Implementing classes can use auto-properties to simplify implementation, if there's no special logic associated with the property:

class Automobile : ICar
{
    public int Year { get; set; } // automatically implemented
}

What is output buffering?

I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe.

If output buffering is turned off, then echo will send data immediately to the Browser.

enter image description here

If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.

enter image description here

phpinfo

To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering directive will tell you if Output buffering is on/off.

enter image description here In this case the output_buffering value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.

php.ini

It's possible to turn on/off and change buffer size by changing the value of the output_buffering directive. Just find it in php.ini, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini below.

; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
;   functions.
; Possible Values:
;   On = Enabled and buffer is unlimited. (Use with caution)
;   Off = Disabled
;   Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096

The directive output_buffering is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php

Example: ob_get_clean()

Below you can see how to capture an echo and manipulate it before sending it to the browser.

// Turn on output buffering  
ob_start();  

echo 'Hello World';  // save to output buffer

$output = ob_get_clean();  // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output  

echo $output;  // send to output stream / Browser

// OUTPUT:  
HELLO WORLD

Examples: Hackingwithphp.com

More info about Output buffer with examples can be found here:

http://www.hackingwithphp.com/13/0/0/output-buffering

Use of 'prototype' vs. 'this' in JavaScript?

Every object is linked to a prototype object. When trying to access a property that does not exist, JavaScript will look in the object's prototype object for that property and return it if it exists.

The prototype property of a function constructor refers to the prototype object of all instances created with that function when using new.


In your first example, you are adding a property x to each instance created with the A function.

var A = function () {
    this.x = function () {
        //do something
    };
};

var a = new A();    // constructor function gets executed
                    // newly created object gets an 'x' property
                    // which is a function
a.x();              // and can be called like this

In the second example you are adding a property to the prototype object that all the instances created with A point to.

var A = function () { };
A.prototype.x = function () {
    //do something
};

var a = new A();    // constructor function gets executed
                    // which does nothing in this example

a.x();              // you are trying to access the 'x' property of an instance of 'A'
                    // which does not exist
                    // so JavaScript looks for that property in the prototype object
                    // that was defined using the 'prototype' property of the constructor

In conclusion, in the first example a copy of the function is assigned to each instance. In the second example a single copy of the function is shared by all instances.

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

How do you create a toggle button?

I don't think using JS for creating a button is good practice. What if the user's browser deactivates JavaScript ?

Plus, you can just use a checkbox and a bit of CSS to do it. And it easy to retrieve the state of your checkbox.

This is just one example, but you can style it how want.

http://jsfiddle.net/4gjZX/

HTML

<fieldset class="toggle">
  <input id="data-policy" type="checkbox" checked="checked" />
  <label for="data-policy">
  <div class="toggle-button">
    <div class="toggle-tab"></div>
  </div>
  Toggle
  </label>
</fieldset>?

CSS

.toggle label {
  color: #444;
  float: left;
  line-height: 26px;
}
.toggle .toggle-button {
  margin: 0px 10px 0px 0px;
  float: left;
  width: 70px;
  height: 26px;
  background-color: #eeeeee;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#fafafa));
  background-image: -webkit-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -moz-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -o-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -ms-linear-gradient(top, #eeeeee, #fafafa);
  background-image: linear-gradient(top, #eeeeee, #fafafa);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#eeeeee', EndColorStr='#fafafa');
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border: 1px solid #D1D1D1;
}
.toggle .toggle-button .toggle-tab {
  width: 30px;
  height: 26px;
  background-color: #fafafa;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#eeeeee));
  background-image: -webkit-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -moz-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -o-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -ms-linear-gradient(top, #fafafa, #eeeeee);
  background-image: linear-gradient(top, #fafafa, #eeeeee);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#fafafa', EndColorStr='#eeeeee');
  border: 1px solid #CCC;
  margin-left: -1px;
  margin-top: -1px;
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-box-shadow: 5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
  -moz-box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
  box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}
.toggle input[type=checkbox] {
  display: none;
}
.toggle input[type=checkbox]:checked ~ label .toggle-button {
  background-color: #2d71c2;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#2d71c2), to(#4ea1db));
  background-image: -webkit-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -moz-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -o-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -ms-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: linear-gradient(top, #2d71c2, #4ea1db);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#2d71c2', EndColorStr='#4ea1db');
}
.toggle input[type=checkbox]:checked ~ label .toggle-button .toggle-tab {
  margin-left: 39px;
  -webkit-box-shadow: -5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
  -moz-box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
  box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}?

Hope this helps

Allowed memory size of 536870912 bytes exhausted in Laravel

It is happened to me with laravel 5.1 on php-7 when I was running bunch of unitests.

The solution was - to change memory_limit in php.ini but it should be correct one. So you need one responsible for server, located there:

/etc/php/7.0/cli/php.ini

so you need a line with

 memory_limit

After that you need to restart php service

sudo service php7.0-fpm restart

to check if it was changed successfully I used command line to run this:

 php -i

the report contained following line

memory_limit => 2048M => 2048M

Now test cases are fine.

Mongoose: Get full list of users

In case we want to list all documents in Mongoose collection after update or delete

We can edit the function to some thing like this:

exports.product_update = function (req, res, next) {
        Product.findByIdAndUpdate(req.params.id, {$set: req.body}, function (err, product) {
            if (err) return next(err);
            Product.find({}).then(function (products) {
                res.send(products);
                });
            //res.send('Product udpated.');
        });
    };

This will list all documents on success instead of just showing success message

Access parent URL from iframe

You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...), but other JS APIs are intentionally made inaccessible.

It's also still possible to get the URL depending on the context. See other answers for more details.

Rownum in postgresql

Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.

Time calculation in php (add 10 hours)?

$date = date('h:i:s A', strtotime($today . ' + 10 hours'));

(untested)

More Pythonic Way to Run a Process X Times

Personally:

for _ in range(50):
    print "Some thing"

if you don't need i. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange as there is no need to generate the whole list beforehand.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

If you must do this, you can check the user agent string in JavaScript:

var isIE10 = !!navigator.userAgent.match(/MSIE 10/);

As other people have mentioned, I'd always recommend feature detection instead.

Use PPK file in Mac Terminal to connect to remote connection over SSH

You can ssh directly from the Terminal on Mac, but you need to use a .PEM key rather than the putty .PPK key. You can use PuttyGen on Windows to convert from .PEM to .PPK, I'm not sure about the other way around though.

You can also convert the key using putty for Mac via port or brew:

sudo port install putty

or

brew install putty

This will also install puttygen. To get puttygen to output a .PEM file:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Once you have the key, open a terminal window and:

ssh -i privatekey.pem [email protected]

The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.

chmod go-rw privatekey.pem

CakePHP 3.0 installation: intl extension missing from system

The error message clearly states what the problem is. You need the intl extension installed.

Step 1: install PHP intl you comfortable version

$sudo apt-get install php-intl

step 2:

For XAMPP Server intl extension is already installed, you need to enable this extension to uncomment below the line in your php.ini file. Php.ini file is located at c:\xampp\php\php.ini or where you have installed XAMPP.

Before uncomment:

;extension=php_intl.dll ;extension=php_mbstring.dll

After uncommenting:

extension=php_intl.dll extension=php_mbstring.dll

multiple plot in one figure in Python

Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.

In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()

Loading an image to a <img> from <input file>

Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.

* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)

Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)

Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               creationComplete="init()">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
    <mx:Image id="myImage" x="9" y="44"/>
    <fx:Script>
        <![CDATA[
            private var fr:FileReference = new FileReference();

            // Called when the app starts.
            private function init():void
            {
                // Set up event handlers.
                fr.addEventListener(Event.SELECT, onSelect);
                fr.addEventListener(Event.COMPLETE, onComplete);
            }

            // Called when the user clicks "Choose file..."
            private function showFilePicker():void
            {
                fr.browse();
            }

            // Called when fr.browse() dispatches Event.SELECT to indicate
            // that the user has picked a file.
            private function onSelect(e:Event):void
            {
                fr.load(); // start reading the file
            }

            // Called when fr.load() dispatches Event.COMPLETE to indicate
            // that the file has finished loading.
            private function onComplete(e:Event):void
            {
                myImage.data = fr.data; // load the file's data into the Image
            }
        ]]>
    </fx:Script>
</s:Application>

How to make a div fill a remaining horizontal space?

I had a similar problem and I found the solution here: https://stackoverflow.com/a/16909141/3934886

The solution is for a fixed center div and liquid side columns.

.center{
    background:#ddd;
    width: 500px;
    float:left;
}

.left{
    background:#999;
    width: calc(50% - 250px);
    float:left;
}

.right{
    background:#999;
    width: calc(50% - 250px);
    float:right;
}

If you want a fixed left column, just change the formula accordingly.

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

This is not how SQL works:

INSERT INTO employee(hans,germany) values(?,?)

The values (hans,germany) should use column names (emp_name, emp_address). The values are provided by your program by using the Statement.setString(pos,value) methods. It is complaining because you said there were two parameters (the question marks) but didn't provide values.

You should be creating a PreparedStatement and then setting parameter values as in:

String insert= "INSERT INTO employee(emp_name,emp_address) values(?,?)";
PreparedStatement stmt = con.prepareStatement(insert);
stmt.setString(1,"hans");
stmt.setString(2,"germany");
stmt.execute();

How to check if a string starts with one of several prefixes?

A simple solution is:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed"))
// ... you get the idea ...

A fancier solution would be:

List<String> days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
String day = newStr4.substring(0, 3).toUpperCase();
if (days.contains(day)) {
    // ...
}

Pandas Replace NaN with blank/empty string

If you are reading the dataframe from a file (say CSV or Excel) then use :

  • df.read_csv(path , na_filter=False)
  • df.read_excel(path , na_filter=False)

This will automatically consider the empty fields as empty strings ''


If you already have the dataframe

  • df = df.replace(np.nan, '', regex=True)
  • df = df.fillna('')

error, string or binary data would be truncated when trying to insert

You simply can't beat SQL Server on this.

You can insert into a new table like this:

select foo, bar
into tmp_new_table_to_dispose_later
from my_table

and compare the table definition with the real table you want to insert the data into.

Sometime it's helpful sometimes it's not.

If you try inserting in the final/real table from that temporary table it may just work (due to data conversion working differently than SSMS for example).

Another alternative is to insert the data in chunks, instead of inserting everything immediately you insert with top 1000 and you repeat the process, till you find a chunk with an error. At least you have better visibility on what's not fitting into the table.

What is DOM element?

To find out concept of DOM element it is essential to understand concept of Dynamic HTML and DOM. Everything is started from the time that requirements of all stockholders of web pages are enhanced. They wanted the Web pages that can be more interactive, dynamic and lively. In addition, to reach this goal, developers required the tools and mechanisms that via them the presentation and content of each section of web page can be modified or manipulated. Therefore the concept of Dynamic HTML is created. To understand it, a great definition for Dynamic HTML is accessible in Wikipedia:

Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and animated websites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model (DOM).

So, writing standard DHTML web pages are standardized in three fields, including client-side scripting language (such as JavaScript), a presentation definition language (such as CSS) and uniform programming interface(API) to access and modify the Web page (Document Object Model). This activity is performed by W3C and others. Also to solve the problem of cross browser, W3C tried to reach a general consensus (with different browser vendors) about scripts to access and manipulate HTML and XML documents via Document Object Model (DOM) as a standard application programming interface (API).

But the main question is that how they designed the structure of Document Object Model to meet their needs. Their solution was simple but wonderful. They used a hierarchical structure such as tree which at the root of the tree you can find document object, also each node is equivalent of a HTML elements (DOM element). This abstraction of your web page give you a great facility to access any HTML element, style sheets, and ... . To understand it better you can map each indent of your HTML code to each level of DOM tree. Please pay attention to this example:

Your HTML:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p>...</p>
        <ul>
            <li>...</li>
        </ul>
        <table>
            <tr>...</tr>
        </table>
    </body>
</html> 

DOM Structure:

    document
      |    .    
    <html>    .
    /   \         .
 <head> <body>  styleSheets
        /  \  \
      <p> <ul> <table>
      /     \       \
    text    <li>    <tr>  

So, each node of this hierarchical structure (DOM tree) refers to a DOM element. To learn more use tis reference

Plot inline or a separate window using Matplotlib in Spyder IDE

Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"

Reset the kernel at the console, and the plot will appear in a separate window

How can I build a recursive function in python?

Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0

One solution is to define a simple recursive function:

u0 = ...

def f(x):
  ...

def u(n):
  if n==0: return u0
  return f(u(n-1))

Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.

Another solution is a simple loop:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  return ux

But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  yield ux

for val in u(1000):
  print val

There are many other options, but I guess these are the main ones.

How to set Internet options for Android emulator?

You can do it using AVD Manager, choose Tools -> Options. Set HTTP Proxy Server to 8.8.8.8,8.8.4.4

The emulator will be connected.

Opening A Specific File With A Batch File?

start wgnplot.exe "c:\path to file to open\foo.dat"

Markdown and image alignment

You can embed HTML in Markdown, so you can do something like this:

<img style="float: right;" src="whatever.jpg">

Continue markdown text...

Using npm behind corporate proxy .pac

If you are behind a corporate network with proxy, i just used a ntlm proxy tool and used the port and proxy provided by ntlm, for instnce i used this configuration:

strict-ssl=false
proxy=http://localhost:3125

I hope this helps.

Can an AJAX response set a cookie?

For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).

Get Table and Index storage size in sql server

This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:

SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%'    -- filter out system tables for diagramming
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

If you want to separate table space from index space, you need to use AND i.index_id IN (0,1) for the table space (index_id = 0 is the heap space, index_id = 1 is the size of the clustered index = data pages) and AND i.index_id > 1 for the index-only space

How to Correctly Use Lists in R?

x = list(1, 2, 3, 4)
x2 = list(1:4)
all.equal(x,x2)

is not the same because 1:4 is the same as c(1,2,3,4). If you want them to be the same then:

x = list(c(1,2,3,4))
x2 = list(1:4)
all.equal(x,x2)

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

SQL Developer is returning only the date, not the time. How do I fix this?

From Tools > Preferences > Database > NLS Parameter and set Date Format as

DD-MON-RR HH:MI:SS

Bootstrap 4 - Inline List?

.list-inline class in bootstrap is a Inline Unordered List.

If you want to create a horizontal menu using ordered or unordered list you need to place all list items in a single line i.e. side by side. You can do this by simply applying the class

<div class="list-inline">
    <a href="#" class="list-inline-item">First item</a>
    <a href="#" class="list-inline-item">Secound item</a>
    <a href="#" class="list-inline-item">Third item</a>
  </div>

Auto logout with Angularjs based on idle user

I think Buu's digest cycle watch is genius. Thanks for sharing. As others have noted $interval also causes the digest cycle to run. We could for the purpose of auto logging the user out use setInterval which will not cause a digest loop.

app.run(function($rootScope) {
    var lastDigestRun = new Date();
    setInterval(function () {
        var now = Date.now();
        if (now - lastDigestRun > 10 * 60 * 1000) {
          //logout
        }
    }, 60 * 1000);

    $rootScope.$watch(function() {
        lastDigestRun = new Date();
    });
});

How to pip or easy_install tkinter on Windows

Inside cmd, run command pip install tk and Tkinter should install.

How to kill an application with all its activities?

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

    if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."

Evaluate expression given as a string

Alternatively, you can use evals from my pander package to capture output and all warnings, errors and other messages along with the raw results:

> pander::evals("5+5")
[[1]]
$src
[1] "5 + 5"

$result
[1] 10

$output
[1] "[1] 10"

$type
[1] "numeric"

$msg
$msg$messages
NULL

$msg$warnings
NULL

$msg$errors
NULL


$stdout
NULL

attr(,"class")
[1] "evals"

Disable form auto submit on button click

another one:

if(this.checkValidity() == false) {

                $(this).addClass('was-validated');
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();

                return false;
}

What is the difference between static_cast<> and C style casting?

A great post explaining different casts in C/C++, and what C-style cast really does: https://anteru.net/blog/2007/12/18/200/index.html

C-Style casting, using the (type)variable syntax. The worst ever invented. This tries to do the following casts, in this order: (see also C++ Standard, 5.4 expr.cast paragraph 5)

  1. const_cast
  2. static_cast
  3. static_cast followed by const_cast
  4. reinterpret_cast
  5. reinterpret_castfollowed by const_cast

Execute Shell Script after post build in Jenkins

You'd have to set up the post-build shell script as a separate Jenkins job and trigger it as a post-build step. It looks like you will need to use the Parameterized Trigger Plugin as the standard "Build other projects" option only works if your triggering build is successful.

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

-- I like this as the data type and the format remains consistent with a date time data type

;with cte as(
    select 
        cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
    from dbo.mytable cd 
    where utcdate between '2014-01-14' and '2014-01-15'
    group by
        cast(utcdate as date), DATEPART(hour, utcdate)
)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte

C++ Matrix Class

The library called, Matrix supports so many features including mathematics operations, dumping and logging features, associative containers, multiple dimensions and etc.

Usage

its usage is similar to c++ arrays.

Matrix<int> A(1, 2);
Matrix<int> B(2, 3);
Matrix<int> result(1, 3);

A[0][0] = 7;
A[0][1] = 10;

B[0][0] = 1;
B[0][1] = 4;
B[0][2] = 2;
B[1][0] = 1;
B[1][1] = 2;
B[1][2] = 100;

result = A * B;

result.dump.matrix();

Result:

Matrix view:
-            -
| 17 48 1014 |
-            -

Here is the documentation and Github page.

Bash function to find newest file matching pattern

Dark magic function incantation for those who want the find ... xargs ... head ... solution above, but in easy to use function form so you don't have to think:

#define the function
find_newest_file_matching_pattern_under_directory(){
    echo $(find $1 -name $2 -print0 | xargs -0 ls -1 -t | head -1)
}

#setup:
#mkdir /tmp/files_to_move
#cd /tmp/files_to_move
#touch file1.txt
#touch file2.txt

#invoke the function:
newest_file=$( find_newest_file_matching_pattern_under_directory /tmp/files_to_move/ bc* )
echo $newest_file

Prints:

file2.txt

Which is:

The filename with the oldest modified timestamp of the file under the given directory matching the given pattern.

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

You either need to increase the max_connections configuration setting or (probably better) use connection pooling to route a large number of user requests through a smaller connection pool.

https://wiki.postgresql.org/wiki/Number_Of_Database_Connections

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You need to start your Apache Server normally you should have an xampp icon in the info-section from the taskbar, with this tool you can start the apache server as wel as the mysql database (if you need it)

Why does z-index not work?

Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.

Here's an example:

<section class="content">            
    <div class="modal"></div>
</section>

<div class="side-tab"></div>

// CSS //
.content {
    position: relative;
    z-index: 1;
}

.modal {
    position: fixed;
    z-index: 100;
}

.side-tab {
    position: fixed;
    z-index: 5;
}

In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.

Here's an article that explains 4 reasons why z-index might not work: https://coder-coder.com/z-index-isnt-working/

How do I sort a Set to a List in Java?

Sorted set:

return new TreeSet(setIWantSorted);

or:

return new ArrayList(new TreeSet(setIWantSorted));

Difference between "as $key => $value" and "as $value" in PHP foreach

if the array looks like:

  • $featured["fruit"] = "orange";
  • $featured["fruit"] = "banana";
  • $featured["vegetable"] = "carrot";

the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)

How to get Toolbar from fragment?

In XML

 <androidx.appcompat.widget.Toolbar
  android:id="@+id/main_toolbar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  app:layout_scrollFlags="scroll|enterAlways">
 </androidx.appcompat.widget.Toolbar>

Kotlin: In fragment.kt -> onCreateView()

setHasOptionsMenu(true)

val toolbar = view.findViewById<Toolbar>(R.id.main_toolbar)

(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)

(activity as? AppCompatActivity)?.supportActionBar?.show()

-> onCreateOptionsMenu()

   override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
       inflater.inflate(R.menu.app_main_menu,menu)
       super.onCreateOptionsMenu(menu, inflater)
   }

->onOptionsItemSelected()

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
             R.id.selected_id->{//to_do}
             else -> super.onOptionsItemSelected(item)
        }
    }

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.