Programs & Examples On #Adfs2.0

Active Directory Federation Services 2.0

Differences between SP initiated SSO and IDP initiated SSO

https://support.procore.com/faq/what-is-the-difference-between-sp-and-idp-initiated-sso

There is much more to this but this is a high level overview on which is which.

Procore supports both SP- and IdP-initiated SSO:

Identity Provider Initiated (IdP-initiated) SSO. With this option, your end users must log into your Identity Provider's SSO page (e.g., Okta, OneLogin, or Microsoft Azure AD) and then click an icon to log into and open the Procore web application. To configure this solution, see Configure IdP-Initiated SSO for Microsoft Azure AD, Configure Procore for IdP-Initated Okta SSO, or Configure IdP-Initiated SSO for OneLogin. OR Service Provider Initiated (SP-initiated) SSO. Referred to as Procore-initiated SSO, this option gives your end users the ability to sign into the Procore Login page and then sends an authorization request to the Identify Provider (e.g., Okta, OneLogin, or Microsoft Azure AD). Once the IdP authenticates the user's identify, the user is logged into Procore. To configure this solution, see Configure Procore-Initiated SSO for Microsoft Azure Active Directory, Configure Procore-Initiated SSO for Okta, or Configure Procore-Initiated SSO for OneLogin.

C# Foreach statement does not contain public definition for GetEnumerator

Your CarBootSaleList class is not a list. It is a class that contain a list.

You have three options:

Make your CarBootSaleList object implement IEnumerable

or

make your CarBootSaleList inherit from List<CarBootSale>

or

if you are lazy this could almost do the same thing without extra coding

List<List<CarBootSale>>

Escape @ character in razor view engine

Instead of HTML entity I prefer the use of @Html.Raw("@").

How can I solve a connection pool problem between ASP.NET and SQL Server?

Yes, There is a way to change configuration. If you are on a dedicated server and simply need more SQL connections, you may update the "max pool size" entries in both connection strings by following these instructions:

  1. Log into your server using Remote Desktop
  2. Open My Computer (Windows - E) and go to C:\inetpub\vhosts[domain]\httpdocs
  3. Double click on the web.config file. This may just be listed as web if the file structure is set to hide extensions. This will open up Visual Basic or similar editor.
  4. Find your Connection Strings, these will look similar to the examples below :

    "add name="SiteSqlServer" connectionString="server=(local);database=dbname;uid=dbuser;pwd=dbpassword;pooling=true;connection lifetime=120;max pool size=25;""

5.Change the max pool size=X value to the required pool size.

  1. Save and close your web.config file.

Generate a random letter in Python

All previous answers are correct, if you are looking for random characters of various types (i.e. alphanumeric and special characters) then here is an script that I created to demonstrate various types of creating random functions, it has three functions one for numbers, alpha- characters and special characters. The script simply generates passwords and is just an example to demonstrate various ways of generating random characters.

import string
import random
import sys

#make sure it's 3.7 or above
print(sys.version)

def create_str(str_length):
    return random.sample(string.ascii_letters, str_length)

def create_num(num_length):
    digits = []
    for i in range(num_length):
        digits.append(str(random.randint(1, 100)))

    return digits

def create_special_chars(special_length):
    stringSpecial = []
    for i in range(special_length):
        stringSpecial.append(random.choice('!$%&()*+,-.:;<=>?@[]^_`{|}~'))

    return stringSpecial

print("how many characters would you like to use ? (DO NOT USE LESS THAN 8)")
str_cnt = input()
print("how many digits would you like to use ? (DO NOT USE LESS THAN 2)")
num_cnt = input()
print("how many special characters would you like to use ? (DO NOT USE LESS THAN 1)")
s_chars_cnt = input()
password_values = create_str(int(str_cnt)) +create_num(int(num_cnt)) + create_special_chars(int(s_chars_cnt))

#shuffle/mix the values
random.shuffle(password_values)

print("generated password is: ")
print(''.join(password_values))

Result:

enter image description here

Background service with location listener in android

Very easy no need create class extends LocationListener 1- Variable

private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;

2- onStartService()

@Override public void onStartService() {
    addListenerLocation();
}

3- Method addListenerLocation()

 private void addListenerLocation() {
    mLocationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            currentLat = location.getLatitude();
            currentLon = location.getLongitude();

            Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if(lastKnownLocation!=null){
                currentLat = lastKnownLocation.getLatitude();
                currentLon = lastKnownLocation.getLongitude();
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}

4- onDestroy()

@Override
public void onDestroy() {
    super.onDestroy();
    mLocationManager.removeUpdates(mLocationListener);
}

'const int' vs. 'int const' as function parameters in C++ and C

Yes, they are same for just int

and different for int*

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

How to define a circle shape in an Android XML drawable file?

Set this as your view background

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <stroke
        android:width="1dp"
        android:color="#78d9ff"/>
</shape>

enter image description here

For solid circle use:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid
        android:color="#48b3ff"/>
</shape>

enter image description here

Solid with stroke:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#199fff"/>
    <stroke
        android:width="2dp"
        android:color="#444444"/>
</shape>

enter image description here

Note: To make the oval shape appear as a circle, in these examples, either your view that you are using this shape as its background should be a square or you have to set the height and width properties of the shape tag to an equal value.

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

Bubble Sort Homework

If anyone is interested in a shorter implementation using a list comprehension:

def bubble_sort(lst: list) -> None:
    [swap_items(lst, i, i+1) for left in range(len(lst)-1, 0, -1) for i in range(left) if lst[i] > lst[i+1]]


def swap_items(lst: list, pos1: int, pos2: int) -> None:
    lst[pos1], lst[pos2] = lst[pos2], lst[pos1]

How can I create a progress bar in Excel VBA?

You can add a Form and name it as Form1, add a Frame to it as Frame1 as well as Label1 too. Set Frame1 width to 200, Back Color to Blue. Place the code in the module and check if it helps.

    Sub Main()
    Dim i As Integer
    Dim response
    Form1.Show vbModeless
    Form1.Frame1.Width = 0
    For i = 10 To 10000
        With Form1
            .Label1.Caption = Round(i / 100, 0) & "%"
            .Frame1.Width = Round(i / 100, 0) * 2
             DoEvents
        End With
    Next i

    Application.Wait Now + 0.0000075

    Unload Form1

    response = MsgBox("100% Done", vbOKOnly)

    End Sub

If you want to display on the Status Bar then you can use other way that's simpler:

   Sub Main()
   Dim i As Integer
   Dim response
   For i = 10 To 10000
        Application.StatusBar = Round(i / 100, 0) & "%"
   Next i

   Application.Wait Now + 0.0000075

   response = MsgBox("100% Done", vbOKOnly)

   End Sub

How to catch a unique constraint error in a PL/SQL block?

EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         UPDATE

How to keep two folders automatically synchronized?

Just simple modification of @silgon answer:

while true; do 
  inotifywait -r -e modify,create,delete /directory
  rsync -avz /directory /target
done

(@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)

Why am I getting "IndentationError: expected an indented block"?

I had this same problem and discovered (via this answer to a similar question) that the problem was that I didn't properly indent the docstring properly. Unfortunately IDLE doesn't give useful feedback here, but once I fixed the docstring indentation, the problem went away.

Specifically --- bad code that generates indentation errors:

def my_function(args):
"Here is my docstring"
    ....

Good code that avoids indentation errors:

def my_function(args):
    "Here is my docstring"
    ....

Note: I'm not saying this is the problem, but that it might be, because in my case, it was!

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

Which one is better and what is the difference between these two Its almost imposibble to me, someone just want to get the number of records without re-touching or perform another query which involved same resource. Furthermore, the memory used by these two function is in same way after all, since with count_all_result you still performing get (in CI AR terms), so i recomend you using the other one (or use count() instead) which gave you reusability benefits.

How can I print using JQuery

There is a jquery print area. I've been using it for some time now.

$(".printMe").click(function(){
   $("#outprint").printArea({ mode: 'popup', popClose: true });
});

Early exit from function?

If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.

  function myfunction(e)
  {
       e.stopImmediatePropagation();
       ................
  }

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

How to download python from command-line?

wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz  
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.

./configure  
make  
sudo make install  

For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

For other versions and the most up to date download links:
http://www.python.org/getit/

how to set the default value to the drop down list control?

Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:

lstDepartment.ClearSelection();

foreach (var item in lstDepartment.Items) 
{
  if (item.Value == otherDropDownList.SelectedValue)
  {
    item.Selected = true;
  }
}

Rename multiple files based on pattern in Unix

On Solaris you can try:

for file in `find ./ -name "*TextForRename*"`; do 
    mv -f "$file" "${file/TextForRename/NewText}"
done

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])

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

In my case, I was using a style called "FullScreenTheme", and although it seemed to be correctly defined (it was a descendant of Theme.AppCompat) it was not working.

I finally realized that I was using an AAR library that internally also had defined a style called "FullScreenTheme" and it was not descendant of Theme.AppCompat. The clashing of the names was causing the problem.

Fix it by renaming my own style name so now Android is using the correct style.

CSS Circular Cropping of Rectangle Image

I know many of the solutions mentioned above works, you can as well try flex.

But my image was rectangular and not fitting properly. so this is what i did.

.parentDivClass {
    position: relative;
    height: 100px;
    width: 100px;
    overflow: hidden;
    border-radius: 50%;
    margin: 20px;
    display: flex;
    justify-content: center;
}

and for the image inside, you can use,

child Img {
    display: block;
    margin: 0 auto;
    height: 100%;
    width: auto;
}

This is helpful when you are using bootstrap 4 classes.

In Java how does one turn a String into a char or a char into a String?

In order to convert string to char

 String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();

CodeIgniter: 404 Page Not Found on Live Server

I have solved this problem, please just make few changes

1- all controller class name should start with capital letter. i mean first letter of class should be capital . eg we have controler with class name Pages

so it should be Pages not pages

2- save the controller class Pages as Pages.php not pages.php

so first letter must be capital

same for model, model class first letter should be capital and also save model class as Pages_model.php not page_model.php

hope this will solve ur problem

What is __pycache__?

When you import a module,

import file_name

Python stores the compiled bytecode in __pycache__ directory so that future imports can use it directly, rather than having to parse and compile the source again.

It does not do that for merely running a script, only when a file is imported.

(Previous versions used to store the cached bytecode as .pyc files that littered up the same directory as the .py files, but starting in Python 3 they were moved to a subdirectory to make things tidier.)

PYTHONDONTWRITEBYTECODE ---> If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This is equivalent to specifying the -B option.

How to get date and time from server

For enable PHP Extension intl , follow the Steps..

  1. Open the xampp/php/php.ini file in any editor.
  2. Search ";extension=php_intl.dll"
  3. kindly remove the starting semicolon ( ; ) Like : ;extension=php_intl.dll. to. extension=php_intl.dll.
  4. Save the xampp/php/php.ini file.
  5. Restart your xampp/wamp.

Git: See my last commit

$ git diff --name-only HEAD^..HEAD

or

$ git log --name-only HEAD^..HEAD

Android WebView not loading URL

Use the following things on your webview

webview.setWebChromeClient(new WebChromeClient());

then implement the required methods for WebChromeClient class.

How to copy data to clipboard in C#

Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.

        /// <summary>
        /// Sets clipboard to value.
        /// </summary>
        /// <param name="value">String to set the clipboard to.</param>
        public static void SetClipboard(string value)
        {
            if (value == null)
                throw new ArgumentNullException("Attempt to set clipboard with null");

            Process clipboardExecutable = new Process(); 
            clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
            {
                RedirectStandardInput = true,
                FileName = @"clip", 
            };
            clipboardExecutable.Start();

            clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
            // When we are done writing all the string, close it so clip doesn't wait and get stuck
            clipboardExecutable.StandardInput.Close(); 

            return;
        }

day of the week to day number (Monday = 1, Tuesday = 2)

$day_number = date('N', $date);

This will return a 1 for Monday to 7 for Sunday, for the date that is stored in $date. Omitting the second argument will cause date() to return the number for the current day.

JavaScript CSS how to add and remove multiple CSS classes to an element

Here's a simpler method to add multiple classes via classList (supported by all modern browsers, as noted in other answers here):

div.classList.add('foo', 'bar'); // add multiple classes

From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples

If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add() via this one-liner:

let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);

Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.

Bootstrap button drop-down inside responsive table not visible because of scroll

We solved this issue here at work by applying a .dropup class to the dropdown when the dropdown is close to the bottom of a table.enter image description here

How to allow only one radio button to be checked?

Add "name" attribute and keep the name same for all the radio buttons in a form.

i.e.,

<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3

Hope that would help.

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

python manage.py migrate --fake APPNAME zero

This will make your migration to fake. Now you can run the migrate script

python manage.py migrate APPNAME

Tables will be created and you solved your problem.. Cheers!!!

AngularJS: How do I manually set input to $valid in controller?

I came across this post w/a similar issue. My fix was to add a hidden field to hold my invalid state for me.

<input type="hidden" ng-model="vm.application.isValid" required="" />

In my case I had a nullable bool which a person had to select one of two different buttons. if they answer yes, an entity is added to the collection and the state of the button changes. Until all of the questions get answered, (one of the buttons in each of the pairs has a click) the form is not valid.

vm.hasHighSchool = function (attended) { 
  vm.application.hasHighSchool = attended;
  applicationSvc.addSchool(attended, 1, vm.application);
}
<input type="hidden" ng-model="vm.application.hasHighSchool" required="" />
<div class="row">
  <div class="col-lg-3"><label>Did You Attend High School?</label><label class="required" ng-hide="vm.application.hasHighSchool != undefined">*</label></div>
  <div class="col-lg-2">
    <button value="Yes" title="Yes" ng-click="vm.hasHighSchool(true)" class="btn btn-default" ng-class="{'btn-success': vm.application.hasHighSchool == true}">Yes</button>
    <button value="No" title="No" ng-click="vm.hasHighSchool(false)" class="btn btn-default" ng-class="{'btn-success':  vm.application.hasHighSchool == false}">No</button>
  </div>
</div>

How do I create a nice-looking DMG for Mac OS X using command-line tools?

I also in need of using command line approach to do the packaging and dmg creation "programmatically in a script". The best answer I found so far is from Adium project' Release building framework (See R1). There is a custom script(AdiumApplescriptRunner) to allow you avoid OSX WindowsServer GUI interaction. "osascript applescript.scpt" approach require you to login as builder and run the dmg creation from a command line vt100 session.

OSX package management system is not so advanced compared to other Unixen which can do this task easily and systematically.

R1: http://hg.adium.im/adium-1.4/file/00d944a3ef16/Release

How to call a REST web service API from JavaScript?

Usual way is to go with PHP and ajax. But for your requirement, below will work fine.

<body>

https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>

<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>

<script type="text/javascript">

document.getElementById('sub').onclick = function(){

var url = document.getElementById('url').value;
var controller = null; 
var method = null; 
var parm = []; 

//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4]; 
parm[0] = x[5]; 
parm[1] = x[6];
 }
}

//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}  

//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}


//Process
function ProcessRequest(){

if(method=="Add"){
    ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
    ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
   ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
    ResponseRequest("404","Not Found");
 }

}

URLValidation(url);
ProcessRequest();

};
</script>

reactjs - how to set inline style of backgroundcolor?

If you want more than one style this is the correct full answer. This is div with class and style:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>

Highlight all occurrence of a selected word?

In Normal mode:

:set hlsearch

Then search for a pattern with the command / in Normal mode, or <Ctrl>o followed by / in Insert mode. * in Normal mode will search for the next occurrence of the word under the cursor. The hlsearch option will highlight all of them if set. # will search for the previous occurrence of the word.

To remove the highlight of the previous search:

:nohlsearch

You might wish to map :nohlsearch<CR> to some convenient key.

Invalid hook call. Hooks can only be called inside of the body of a function component

My case.... SOLUTION in HOOKS

const [cep, setCep] = useState('');
const mounted = useRef(false);

useEffect(() => {
    if (mounted.current) {
        fetchAPI();
      } else {
        mounted.current = true;
      }
}, [cep]);

const setParams = (_cep) => {
    if (cep !== _cep || cep === '') {
        setCep(_cep);
    }
};

C++ Get name of type in template

This trick was mentioned under a few other questions, but not here yet.

All major compilers support __PRETTY_FUNC__ (GCC & Clang) /__FUNCSIG__ (MSVC) as an extension.

When used in a template like this:

template <typename T> const char *foo()
{
    #ifdef _MSC_VER
    return __FUNCSIG__;
    #else
    return __PRETTY_FUNCTION__;
    #endif
}

It produces strings in a compiler-dependent format, that contain, among other things, the name of T.

E.g. foo<float>() returns:

  • "const char* foo() [with T = float]" on GCC
  • "const char *foo() [T = float]" on Clang
  • "const char *__cdecl foo<float>(void)" on MSVC

You can easily parse the type names out of those strings. You just need to figure out how many 'junk' characters your compiler inserts before and after the type.

You can even do that completely at compile-time.


The resulting names can slightly vary between different compilers. E.g. GCC omits default template arguments, and MSVC prefixes classes with the word class.


Here's an implementation that I've been using. Everything is done at compile-time.

Example usage:

std::cout << TypeName<float>() << '\n';
std::cout << TypeName(1.2f); << '\n';

Implementation:

#include <array>
#include <cstddef>

namespace impl
{
    template <typename T>
    constexpr const auto &RawTypeName()
    {
        #ifdef _MSC_VER
        return __FUNCSIG__;
        #else
        return __PRETTY_FUNCTION__;
        #endif
    }

    struct RawTypeNameFormat
    {
        std::size_t leading_junk = 0, trailing_junk = 0;
    };

    // Returns `false` on failure.
    inline constexpr bool GetRawTypeNameFormat(RawTypeNameFormat *format)
    {
        const auto &str = RawTypeName<int>();
        for (std::size_t i = 0;; i++)
        {
            if (str[i] == 'i' && str[i+1] == 'n' && str[i+2] == 't')
            {
                if (format)
                {
                    format->leading_junk = i;
                    format->trailing_junk = sizeof(str)-i-3-1; // `3` is the length of "int", `1` is the space for the null terminator.
                }
                return true;
            }
        }
        return false;
    }

    inline static constexpr RawTypeNameFormat format =
    []{
        static_assert(GetRawTypeNameFormat(nullptr), "Unable to figure out how to generate type names on this compiler.");
        RawTypeNameFormat format;
        GetRawTypeNameFormat(&format);
        return format;
    }();
}

// Returns the type name in a `std::array<char, N>` (null-terminated).
template <typename T>
[[nodiscard]] constexpr auto CexprTypeName()
{
    constexpr std::size_t len = sizeof(impl::RawTypeName<T>()) - impl::format.leading_junk - impl::format.trailing_junk;
    std::array<char, len> name{};
    for (std::size_t i = 0; i < len-1; i++)
        name[i] = impl::RawTypeName<T>()[i + impl::format.leading_junk];
    return name;
}

template <typename T>
[[nodiscard]] const char *TypeName()
{
    static constexpr auto name = CexprTypeName<T>();
    return name.data();
}
template <typename T>
[[nodiscard]] const char *TypeName(const T &)
{
    return TypeName<T>();
}

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

Add a space (" ") after an element using :after

element::after { 
    display: block;
    content: " ";
}

This worked for me.

Get startup type of Windows service using PowerShell

As far as I know there is no “native” PowerShell way of getting this information. And perhaps it is rather the .NET limitation than PowerShell.

Here is the suggestion to add this functionality to the version next:

https://connect.microsoft.com/PowerShell/feedback/details/424948/i-would-like-to-see-the-property-starttype-added-to-get-services

The WMI workaround is also there, just in case. I use this WMI solution for my tasks and it works.

Describe table structure

Sql server

DECLARE @tableName nvarchar(100)
SET @tableName = N'members' -- change with table name
SELECT
    [column].*,
    COLUMNPROPERTY(object_id([column].[TABLE_NAME]), [column].[COLUMN_NAME], 'IsIdentity') AS [identity]
FROM 
    INFORMATION_SCHEMA.COLUMNS [column] 
WHERE
    [column].[Table_Name] = @tableName

Javascript Src Path

Piece of cake!

<SCRIPT LANGUAGE="JavaScript" SRC="/clock.js"></SCRIPT>

Moving from one activity to another Activity in Android

First you have to declare the activity in Manifest. It is important. You can add this inside application like this.

CSS pseudo elements in React

Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):

https://stackoverflow.com/a/42000085

<span class="something" datacustomattribute="">
  Hello
</span>
.something::before {
  content: attr(datascustomattribute);
  position: absolute;
}

Note that the datacustomattribute must start with data and be all lowercase to satisfy React.

How do I fix the indentation of an entire file in Vi?

:set paste is your friend I use putty and end up copying code between windows. Before I was turned on to :set paste (and :set nopaste) copy/paste gave me fits for that very reason.

What is the difference between a framework and a library?

I think library is a set of utilities to reach a goal (for example, sockets, cryptography, etc). Framework is library + RUNTIME EINVIRONNEMENT. For example, ASP.NET is a framework: it accepts HTTP requests, create page object, invoke lyfe cicle events, etc. Framework does all this, you write a bit of code which will be run at a specific time of the life cycle of current request!

Anyway, very interestering question!

How to hash a string into 8 digits?

Raymond's answer is great for python2 (though, you don't need the abs() nor the parens around 10 ** 8). However, for python3, there are important caveats. First, you'll need to make sure you are passing an encoded string. These days, in most circumstances, it's probably also better to shy away from sha-1 and use something like sha-256, instead. So, the hashlib approach would be:

>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417

If you want to use the hash() function instead, the important caveat is that, unlike in Python 2.x, in Python 3.x, the result of hash() will only be consistent within a process, not across python invocations. See here:

$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597

$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934

This means the hash()-based solution suggested, which can be shortened to just:

hash(s) % 10**8

will only return the same value within a given script run:

#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543

#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451

So, depending on if this matters in your application (it did in mine), you'll probably want to stick to the hashlib-based approach.

Left Join without duplicate rows from left table

Using the DISTINCT flag will remove duplicate rows.

SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id

FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
ORDER BY C.Content_DatePublished ASC

how to open popup window using jsp or jquery?

<a href="javaScript:{openPopUp();}"></a>
<form action="actionName">
<div id="divId" style="display:none;">
UsreName:<input type="text" name="userName"/>
</div>
</form>

function openPopUp()
{
  $('#divId').css('display','block');
$('#divId').dialog();
}

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

Resolution for 404 Forbidden in recent .Net 4.7 MVC/webform pplication hosting in Azure VM We need to install the .Net 4.7 and extensibilty and development in server role other than the .Net 4.7/version feature as below: This might have been alreday activated .Net Activated feature

We need to also add the below under IIS webserver role-> Application Development -> select the .Net version as below Image to Activate the requited Role under IIS webserver Role Server Role Activation under application Development

Parsing JSON in Excel VBA

Another Regex based JSON parser (decode only)

Private Enum JsonStep
    jsonString
    jsonNumber
    jsonTrue
    jsonFalse
    jsonNull
    jsonOpeningBrace
    jsonClosingBrace
    jsonOpeningBracket
    jsonClosingBracket
    jsonComma
    jsonColon
End Enum

Private regexp As Object

Private Function JsonStepName(ByVal json_step As JsonStep) As String
    Select Case json_step
        Case jsonString: JsonStepName = "'STRING'"
        Case jsonNumber: JsonStepName = "'NUMBER'"
        Case jsonTrue: JsonStepName = "true"
        Case jsonFalse: JsonStepName = "false"
        Case jsonNull: JsonStepName = "null"
        Case jsonOpeningBrace: JsonStepName = "'{'"
        Case jsonClosingBrace: JsonStepName = "'}'"
        Case jsonOpeningBracket: JsonStepName = "'['"
        Case jsonClosingBracket: JsonStepName = "']'"
        Case jsonComma: JsonStepName = "','"
        Case jsonColon: JsonStepName = "':'"
    End Select
End Function

Private Function Unescape(ByVal str As String) As String
    Dim match As Object

    str = Replace$(str, "\""", """")
    str = Replace$(str, "\\", "\")
    str = Replace$(str, "\/", "/")
    str = Replace$(str, "\b", vbBack)
    str = Replace$(str, "\f", vbFormFeed)
    str = Replace$(str, "\n", vbCrLf)
    str = Replace$(str, "\r", vbCr)
    str = Replace$(str, "\t", vbTab)
    With regexp
        .Global = True
        .IgnoreCase = False
        .MultiLine = False
        .Pattern = "\\u([0-9a-fA-F]{4})"
        For Each match In .Execute(str)
            str = Replace$(str, match.value, ChrW$(Val("&H" + match.SubMatches(0))), match.FirstIndex + 1, 1)
        Next match
    End With
    Unescape = str
End Function

Private Function ParseStep(ByVal str As String, _
                           ByRef index As Long, _
                           ByRef value As Variant, _
                           ByVal json_step As JsonStep, _
                           ByVal expected As Boolean) As Boolean
    Dim match As Object

    With regexp
        .Global = False
        .IgnoreCase = False
        .MultiLine = False
        Select Case json_step
            'Case jsonString: .Pattern = "^\s*""(([^\\""]+|\\[""\\/bfnrt]|\\u[0-9a-fA-F]{4})*)""\s*"
            Case jsonString: .Pattern = "^\s*""([^\\""]+|([^\\""]+|\\[""\\/bfnrt]|\\u[0-9a-fA-F]{4})*)""\s*"
            Case jsonNumber: .Pattern = "^\s*(-?(0|[1-9]\d*)(\.\d+)?([eE][-+]?\d+)?)\s*"
            Case jsonTrue: .Pattern = "^\s*(true)\s*"
            Case jsonFalse: .Pattern = "^\s*(false)\s*"
            Case jsonNull: .Pattern = "^\s*(null)\s*"
            Case jsonOpeningBrace: .Pattern = "^\s*(\{)\s*"
            Case jsonClosingBrace: .Pattern = "^\s*(\})\s*"
            Case jsonOpeningBracket: .Pattern = "^\s*(\[)\s*"
            Case jsonClosingBracket: .Pattern = "^\s*(\])\s*"
            Case jsonComma: .Pattern = "^\s*(\,)\s*"
            Case jsonColon: .Pattern = "^\s*(:)\s*"
        End Select
        Set match = .Execute(Mid$(str, index))
    End With
    If match.Count > 0 Then
        index = index + match(0).Length
        Select Case json_step
            Case jsonString
                If match(0).SubMatches(1) = Empty Then
                    value = match(0).SubMatches(0)
                Else
                    value = Unescape(match(0).SubMatches(0))
                End If
            Case jsonNumber: value = Val(match(0).SubMatches(0))
            Case jsonTrue: value = True
            Case jsonFalse: value = False
            Case jsonNull: value = Null
            Case Else: value = Empty
        End Select
        ParseStep = True
    ElseIf expected Then
        Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(json_step) & " at char " & index & "."
    End If
End Function

Private Function ParseValue(ByRef str As String, _
                            ByRef index As Long, _
                            ByRef value As Variant, _
                            ByVal expected As Boolean) As Boolean
    ParseValue = True
    If ParseStep(str, index, value, jsonString, False) Then Exit Function
    If ParseStep(str, index, value, jsonNumber, False) Then Exit Function
    If ParseObject(str, index, value, False) Then Exit Function
    If ParseArray(str, index, value, False) Then Exit Function
    If ParseStep(str, index, value, jsonTrue, False) Then Exit Function
    If ParseStep(str, index, value, jsonFalse, False) Then Exit Function
    If ParseStep(str, index, value, jsonNull, False) Then Exit Function
    ParseValue = False
    If expected Then
        Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(jsonString) & ", " & JsonStepName(jsonNumber) & ", " & JsonStepName(jsonTrue) & ", " & JsonStepName(jsonFalse) & ", " & JsonStepName(jsonNull) & ", " & JsonStepName(jsonOpeningBrace) & ", or " & JsonStepName(jsonOpeningBracket) & " at char " & index & "."
    End If
End Function

Private Function ParseObject(ByRef str As String, _
                             ByRef index As Long, _
                             ByRef obj As Variant, _
                             ByVal expected As Boolean) As Boolean
    Dim key As Variant
    Dim value As Variant

    ParseObject = ParseStep(str, index, Empty, jsonOpeningBrace, expected)
    If ParseObject Then
        Set obj = CreateObject("Scripting.Dictionary")
        If ParseStep(str, index, Empty, jsonClosingBrace, False) Then Exit Function
        Do
            If ParseStep(str, index, key, jsonString, True) Then
                If ParseStep(str, index, Empty, jsonColon, True) Then
                    If ParseValue(str, index, value, True) Then
                        If IsObject(value) Then
                            Set obj.Item(key) = value
                        Else
                            obj.Item(key) = value
                        End If
                    End If
                End If
            End If
        Loop While ParseStep(str, index, Empty, jsonComma, False)
        ParseObject = ParseStep(str, index, Empty, jsonClosingBrace, True)
    End If
End Function

Private Function ParseArray(ByRef str As String, _
                            ByRef index As Long, _
                            ByRef arr As Variant, _
                            ByVal expected As Boolean) As Boolean
    Dim key As Variant
    Dim value As Variant

    ParseArray = ParseStep(str, index, Empty, jsonOpeningBracket, expected)
    If ParseArray Then
        Set arr = New Collection
        If ParseStep(str, index, Empty, jsonClosingBracket, False) Then Exit Function
        Do
            If ParseValue(str, index, value, True) Then
                arr.Add value
            End If
        Loop While ParseStep(str, index, Empty, jsonComma, False)
        ParseArray = ParseStep(str, index, Empty, jsonClosingBracket, True)
    End If
End Function

Public Function ParseJson(ByVal str As String) As Object
    If regexp Is Nothing Then
        Set regexp = CreateObject("VBScript.RegExp")
    End If
    If ParseObject(str, 1, ParseJson, False) Then Exit Function
    If ParseArray(str, 1, ParseJson, False) Then Exit Function
    Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(jsonOpeningBrace) & " or " & JsonStepName(jsonOpeningBracket) & "."
End Function

Getting the base url of the website and globally passing it to twig in Symfony 2

Why do you need to get this root url ? Can't you generate directly absolute URL's ?

{{ url('_demo_hello', { 'name': 'Thomas' }) }}

This Twig code will generate the full http:// url to the _demo_hello route.

In fact, getting the base url of the website is only getting the full url of the homepage route :

{{ url('homepage') }}

(homepage, or whatever you call it in your routing file).

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

How to import module when module name has a '-' dash or hyphen in it?

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )

Get MIME type from filename extension

I like the work that Samuel Neff did, but not the idea and overhead of creating a dictionary every time.

I restructured things as a switch case. Yes you can't iterate over it but in my case I only ever use it to quickly look up a value. Especially because it is done in a web service, the last thing I want is a bunch of overhead as the application prepares its structures. The compiler will turn this into a hashed lookup and so it will be very fast.

public static string GetMimeType(string extension)
{
  if (extension == null)
    throw new ArgumentNullException("extension");

  if (extension.StartsWith("."))
    extension = extension.Substring(1);


  switch (extension.ToLower())
{
    #region Big freaking list of mime types
    case "323": return "text/h323";
    case "3g2": return "video/3gpp2";
    case "3gp": return "video/3gpp";
    case "3gp2": return "video/3gpp2";
    case "3gpp": return "video/3gpp";
    case "7z": return "application/x-7z-compressed";
    case "aa": return "audio/audible";
    case "aac": return "audio/aac";
    case "aaf": return "application/octet-stream";
    case "aax": return "audio/vnd.audible.aax";
    case "ac3": return "audio/ac3";
    case "aca": return "application/octet-stream";
    case "accda": return "application/msaccess.addin";
    case "accdb": return "application/msaccess";
    case "accdc": return "application/msaccess.cab";
    case "accde": return "application/msaccess";
    case "accdr": return "application/msaccess.runtime";
    case "accdt": return "application/msaccess";
    case "accdw": return "application/msaccess.webapplication";
    case "accft": return "application/msaccess.ftemplate";
    case "acx": return "application/internet-property-stream";
    case "addin": return "text/xml";
    case "ade": return "application/msaccess";
    case "adobebridge": return "application/x-bridge-url";
    case "adp": return "application/msaccess";
    case "adt": return "audio/vnd.dlna.adts";
    case "adts": return "audio/aac";
    case "afm": return "application/octet-stream";
    case "ai": return "application/postscript";
    case "aif": return "audio/x-aiff";
    case "aifc": return "audio/aiff";
    case "aiff": return "audio/aiff";
    case "air": return "application/vnd.adobe.air-application-installer-package+zip";
    case "amc": return "application/x-mpeg";
    case "application": return "application/x-ms-application";
    case "art": return "image/x-jg";
    case "asa": return "application/xml";
    case "asax": return "application/xml";
    case "ascx": return "application/xml";
    case "asd": return "application/octet-stream";
    case "asf": return "video/x-ms-asf";
    case "ashx": return "application/xml";
    case "asi": return "application/octet-stream";
    case "asm": return "text/plain";
    case "asmx": return "application/xml";
    case "aspx": return "application/xml";
    case "asr": return "video/x-ms-asf";
    case "asx": return "video/x-ms-asf";
    case "atom": return "application/atom+xml";
    case "au": return "audio/basic";
    case "avi": return "video/x-msvideo";
    case "axs": return "application/olescript";
    case "bas": return "text/plain";
    case "bcpio": return "application/x-bcpio";
    case "bin": return "application/octet-stream";
    case "bmp": return "image/bmp";
    case "c": return "text/plain";
    case "cab": return "application/octet-stream";
    case "caf": return "audio/x-caf";
    case "calx": return "application/vnd.ms-office.calx";
    case "cat": return "application/vnd.ms-pki.seccat";
    case "cc": return "text/plain";
    case "cd": return "text/plain";
    case "cdda": return "audio/aiff";
    case "cdf": return "application/x-cdf";
    case "cer": return "application/x-x509-ca-cert";
    case "chm": return "application/octet-stream";
    case "class": return "application/x-java-applet";
    case "clp": return "application/x-msclip";
    case "cmx": return "image/x-cmx";
    case "cnf": return "text/plain";
    case "cod": return "image/cis-cod";
    case "config": return "application/xml";
    case "contact": return "text/x-ms-contact";
    case "coverage": return "application/xml";
    case "cpio": return "application/x-cpio";
    case "cpp": return "text/plain";
    case "crd": return "application/x-mscardfile";
    case "crl": return "application/pkix-crl";
    case "crt": return "application/x-x509-ca-cert";
    case "cs": return "text/plain";
    case "csdproj": return "text/plain";
    case "csh": return "application/x-csh";
    case "csproj": return "text/plain";
    case "css": return "text/css";
    case "csv": return "text/csv";
    case "cur": return "application/octet-stream";
    case "cxx": return "text/plain";
    case "dat": return "application/octet-stream";
    case "datasource": return "application/xml";
    case "dbproj": return "text/plain";
    case "dcr": return "application/x-director";
    case "def": return "text/plain";
    case "deploy": return "application/octet-stream";
    case "der": return "application/x-x509-ca-cert";
    case "dgml": return "application/xml";
    case "dib": return "image/bmp";
    case "dif": return "video/x-dv";
    case "dir": return "application/x-director";
    case "disco": return "text/xml";
    case "dll": return "application/x-msdownload";
    case "dll.config": return "text/xml";
    case "dlm": return "text/dlm";
    case "doc": return "application/msword";
    case "docm": return "application/vnd.ms-word.document.macroenabled.12";
    case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    case "dot": return "application/msword";
    case "dotm": return "application/vnd.ms-word.template.macroenabled.12";
    case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
    case "dsp": return "application/octet-stream";
    case "dsw": return "text/plain";
    case "dtd": return "text/xml";
    case "dtsconfig": return "text/xml";
    case "dv": return "video/x-dv";
    case "dvi": return "application/x-dvi";
    case "dwf": return "drawing/x-dwf";
    case "dwp": return "application/octet-stream";
    case "dxr": return "application/x-director";
    case "eml": return "message/rfc822";
    case "emz": return "application/octet-stream";
    case "eot": return "application/octet-stream";
    case "eps": return "application/postscript";
    case "etl": return "application/etl";
    case "etx": return "text/x-setext";
    case "evy": return "application/envoy";
    case "exe": return "application/octet-stream";
    case "exe.config": return "text/xml";
    case "fdf": return "application/vnd.fdf";
    case "fif": return "application/fractals";
    case "filters": return "application/xml";
    case "fla": return "application/octet-stream";
    case "flr": return "x-world/x-vrml";
    case "flv": return "video/x-flv";
    case "fsscript": return "application/fsharp-script";
    case "fsx": return "application/fsharp-script";
    case "generictest": return "application/xml";
    case "gif": return "image/gif";
    case "group": return "text/x-ms-group";
    case "gsm": return "audio/x-gsm";
    case "gtar": return "application/x-gtar";
    case "gz": return "application/x-gzip";
    case "h": return "text/plain";
    case "hdf": return "application/x-hdf";
    case "hdml": return "text/x-hdml";
    case "hhc": return "application/x-oleobject";
    case "hhk": return "application/octet-stream";
    case "hhp": return "application/octet-stream";
    case "hlp": return "application/winhlp";
    case "hpp": return "text/plain";
    case "hqx": return "application/mac-binhex40";
    case "hta": return "application/hta";
    case "htc": return "text/x-component";
    case "htm": return "text/html";
    case "html": return "text/html";
    case "htt": return "text/webviewhtml";
    case "hxa": return "application/xml";
    case "hxc": return "application/xml";
    case "hxd": return "application/octet-stream";
    case "hxe": return "application/xml";
    case "hxf": return "application/xml";
    case "hxh": return "application/octet-stream";
    case "hxi": return "application/octet-stream";
    case "hxk": return "application/xml";
    case "hxq": return "application/octet-stream";
    case "hxr": return "application/octet-stream";
    case "hxs": return "application/octet-stream";
    case "hxt": return "text/html";
    case "hxv": return "application/xml";
    case "hxw": return "application/octet-stream";
    case "hxx": return "text/plain";
    case "i": return "text/plain";
    case "ico": return "image/x-icon";
    case "ics": return "application/octet-stream";
    case "idl": return "text/plain";
    case "ief": return "image/ief";
    case "iii": return "application/x-iphone";
    case "inc": return "text/plain";
    case "inf": return "application/octet-stream";
    case "inl": return "text/plain";
    case "ins": return "application/x-internet-signup";
    case "ipa": return "application/x-itunes-ipa";
    case "ipg": return "application/x-itunes-ipg";
    case "ipproj": return "text/plain";
    case "ipsw": return "application/x-itunes-ipsw";
    case "iqy": return "text/x-ms-iqy";
    case "isp": return "application/x-internet-signup";
    case "ite": return "application/x-itunes-ite";
    case "itlp": return "application/x-itunes-itlp";
    case "itms": return "application/x-itunes-itms";
    case "itpc": return "application/x-itunes-itpc";
    case "ivf": return "video/x-ivf";
    case "jar": return "application/java-archive";
    case "java": return "application/octet-stream";
    case "jck": return "application/liquidmotion";
    case "jcz": return "application/liquidmotion";
    case "jfif": return "image/pjpeg";
    case "jnlp": return "application/x-java-jnlp-file";
    case "jpb": return "application/octet-stream";
    case "jpe": return "image/jpeg";
    case "jpeg": return "image/jpeg";
    case "jpg": return "image/jpeg";
    case "js": return "application/x-javascript";
    case "jsx": return "text/jscript";
    case "jsxbin": return "text/plain";
    case "latex": return "application/x-latex";
    case "library-ms": return "application/windows-library+xml";
    case "lit": return "application/x-ms-reader";
    case "loadtest": return "application/xml";
    case "lpk": return "application/octet-stream";
    case "lsf": return "video/x-la-asf";
    case "lst": return "text/plain";
    case "lsx": return "video/x-la-asf";
    case "lzh": return "application/octet-stream";
    case "m13": return "application/x-msmediaview";
    case "m14": return "application/x-msmediaview";
    case "m1v": return "video/mpeg";
    case "m2t": return "video/vnd.dlna.mpeg-tts";
    case "m2ts": return "video/vnd.dlna.mpeg-tts";
    case "m2v": return "video/mpeg";
    case "m3u": return "audio/x-mpegurl";
    case "m3u8": return "audio/x-mpegurl";
    case "m4a": return "audio/m4a";
    case "m4b": return "audio/m4b";
    case "m4p": return "audio/m4p";
    case "m4r": return "audio/x-m4r";
    case "m4v": return "video/x-m4v";
    case "mac": return "image/x-macpaint";
    case "mak": return "text/plain";
    case "man": return "application/x-troff-man";
    case "manifest": return "application/x-ms-manifest";
    case "map": return "text/plain";
    case "master": return "application/xml";
    case "mda": return "application/msaccess";
    case "mdb": return "application/x-msaccess";
    case "mde": return "application/msaccess";
    case "mdp": return "application/octet-stream";
    case "me": return "application/x-troff-me";
    case "mfp": return "application/x-shockwave-flash";
    case "mht": return "message/rfc822";
    case "mhtml": return "message/rfc822";
    case "mid": return "audio/mid";
    case "midi": return "audio/mid";
    case "mix": return "application/octet-stream";
    case "mk": return "text/plain";
    case "mmf": return "application/x-smaf";
    case "mno": return "text/xml";
    case "mny": return "application/x-msmoney";
    case "mod": return "video/mpeg";
    case "mov": return "video/quicktime";
    case "movie": return "video/x-sgi-movie";
    case "mp2": return "video/mpeg";
    case "mp2v": return "video/mpeg";
    case "mp3": return "audio/mpeg";
    case "mp4": return "video/mp4";
    case "mp4v": return "video/mp4";
    case "mpa": return "video/mpeg";
    case "mpe": return "video/mpeg";
    case "mpeg": return "video/mpeg";
    case "mpf": return "application/vnd.ms-mediapackage";
    case "mpg": return "video/mpeg";
    case "mpp": return "application/vnd.ms-project";
    case "mpv2": return "video/mpeg";
    case "mqv": return "video/quicktime";
    case "ms": return "application/x-troff-ms";
    case "msi": return "application/octet-stream";
    case "mso": return "application/octet-stream";
    case "mts": return "video/vnd.dlna.mpeg-tts";
    case "mtx": return "application/xml";
    case "mvb": return "application/x-msmediaview";
    case "mvc": return "application/x-miva-compiled";
    case "mxp": return "application/x-mmxp";
    case "nc": return "application/x-netcdf";
    case "nsc": return "video/x-ms-asf";
    case "nws": return "message/rfc822";
    case "ocx": return "application/octet-stream";
    case "oda": return "application/oda";
    case "odc": return "text/x-ms-odc";
    case "odh": return "text/plain";
    case "odl": return "text/plain";
    case "odp": return "application/vnd.oasis.opendocument.presentation";
    case "ods": return "application/oleobject";
    case "odt": return "application/vnd.oasis.opendocument.text";
    case "one": return "application/onenote";
    case "onea": return "application/onenote";
    case "onepkg": return "application/onenote";
    case "onetmp": return "application/onenote";
    case "onetoc": return "application/onenote";
    case "onetoc2": return "application/onenote";
    case "orderedtest": return "application/xml";
    case "osdx": return "application/opensearchdescription+xml";
    case "p10": return "application/pkcs10";
    case "p12": return "application/x-pkcs12";
    case "p7b": return "application/x-pkcs7-certificates";
    case "p7c": return "application/pkcs7-mime";
    case "p7m": return "application/pkcs7-mime";
    case "p7r": return "application/x-pkcs7-certreqresp";
    case "p7s": return "application/pkcs7-signature";
    case "pbm": return "image/x-portable-bitmap";
    case "pcast": return "application/x-podcast";
    case "pct": return "image/pict";
    case "pcx": return "application/octet-stream";
    case "pcz": return "application/octet-stream";
    case "pdf": return "application/pdf";
    case "pfb": return "application/octet-stream";
    case "pfm": return "application/octet-stream";
    case "pfx": return "application/x-pkcs12";
    case "pgm": return "image/x-portable-graymap";
    case "pic": return "image/pict";
    case "pict": return "image/pict";
    case "pkgdef": return "text/plain";
    case "pkgundef": return "text/plain";
    case "pko": return "application/vnd.ms-pki.pko";
    case "pls": return "audio/scpls";
    case "pma": return "application/x-perfmon";
    case "pmc": return "application/x-perfmon";
    case "pml": return "application/x-perfmon";
    case "pmr": return "application/x-perfmon";
    case "pmw": return "application/x-perfmon";
    case "png": return "image/png";
    case "pnm": return "image/x-portable-anymap";
    case "pnt": return "image/x-macpaint";
    case "pntg": return "image/x-macpaint";
    case "pnz": return "image/png";
    case "pot": return "application/vnd.ms-powerpoint";
    case "potm": return "application/vnd.ms-powerpoint.template.macroenabled.12";
    case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
    case "ppa": return "application/vnd.ms-powerpoint";
    case "ppam": return "application/vnd.ms-powerpoint.addin.macroenabled.12";
    case "ppm": return "image/x-portable-pixmap";
    case "pps": return "application/vnd.ms-powerpoint";
    case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroenabled.12";
    case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
    case "ppt": return "application/vnd.ms-powerpoint";
    case "pptm": return "application/vnd.ms-powerpoint.presentation.macroenabled.12";
    case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
    case "prf": return "application/pics-rules";
    case "prm": return "application/octet-stream";
    case "prx": return "application/octet-stream";
    case "ps": return "application/postscript";
    case "psc1": return "application/powershell";
    case "psd": return "application/octet-stream";
    case "psess": return "application/xml";
    case "psm": return "application/octet-stream";
    case "psp": return "application/octet-stream";
    case "pub": return "application/x-mspublisher";
    case "pwz": return "application/vnd.ms-powerpoint";
    case "qht": return "text/x-html-insertion";
    case "qhtm": return "text/x-html-insertion";
    case "qt": return "video/quicktime";
    case "qti": return "image/x-quicktime";
    case "qtif": return "image/x-quicktime";
    case "qtl": return "application/x-quicktimeplayer";
    case "qxd": return "application/octet-stream";
    case "ra": return "audio/x-pn-realaudio";
    case "ram": return "audio/x-pn-realaudio";
    case "rar": return "application/octet-stream";
    case "ras": return "image/x-cmu-raster";
    case "rat": return "application/rat-file";
    case "rc": return "text/plain";
    case "rc2": return "text/plain";
    case "rct": return "text/plain";
    case "rdlc": return "application/xml";
    case "resx": return "application/xml";
    case "rf": return "image/vnd.rn-realflash";
    case "rgb": return "image/x-rgb";
    case "rgs": return "text/plain";
    case "rm": return "application/vnd.rn-realmedia";
    case "rmi": return "audio/mid";
    case "rmp": return "application/vnd.rn-rn_music_package";
    case "roff": return "application/x-troff";
    case "rpm": return "audio/x-pn-realaudio-plugin";
    case "rqy": return "text/x-ms-rqy";
    case "rtf": return "application/rtf";
    case "rtx": return "text/richtext";
    case "ruleset": return "application/xml";
    case "s": return "text/plain";
    case "safariextz": return "application/x-safari-safariextz";
    case "scd": return "application/x-msschedule";
    case "sct": return "text/scriptlet";
    case "sd2": return "audio/x-sd2";
    case "sdp": return "application/sdp";
    case "sea": return "application/octet-stream";
    case "searchconnector-ms": return "application/windows-search-connector+xml";
    case "setpay": return "application/set-payment-initiation";
    case "setreg": return "application/set-registration-initiation";
    case "settings": return "application/xml";
    case "sgimb": return "application/x-sgimb";
    case "sgml": return "text/sgml";
    case "sh": return "application/x-sh";
    case "shar": return "application/x-shar";
    case "shtml": return "text/html";
    case "sit": return "application/x-stuffit";
    case "sitemap": return "application/xml";
    case "skin": return "application/xml";
    case "sldm": return "application/vnd.ms-powerpoint.slide.macroenabled.12";
    case "sldx": return "application/vnd.openxmlformats-officedocument.presentationml.slide";
    case "slk": return "application/vnd.ms-excel";
    case "sln": return "text/plain";
    case "slupkg-ms": return "application/x-ms-license";
    case "smd": return "audio/x-smd";
    case "smi": return "application/octet-stream";
    case "smx": return "audio/x-smd";
    case "smz": return "audio/x-smd";
    case "snd": return "audio/basic";
    case "snippet": return "application/xml";
    case "snp": return "application/octet-stream";
    case "sol": return "text/plain";
    case "sor": return "text/plain";
    case "spc": return "application/x-pkcs7-certificates";
    case "spl": return "application/futuresplash";
    case "src": return "application/x-wais-source";
    case "srf": return "text/plain";
    case "ssisdeploymentmanifest": return "text/xml";
    case "ssm": return "application/streamingmedia";
    case "sst": return "application/vnd.ms-pki.certstore";
    case "stl": return "application/vnd.ms-pki.stl";
    case "sv4cpio": return "application/x-sv4cpio";
    case "sv4crc": return "application/x-sv4crc";
    case "svc": return "application/xml";
    case "swf": return "application/x-shockwave-flash";
    case "t": return "application/x-troff";
    case "tar": return "application/x-tar";
    case "tcl": return "application/x-tcl";
    case "testrunconfig": return "application/xml";
    case "testsettings": return "application/xml";
    case "tex": return "application/x-tex";
    case "texi": return "application/x-texinfo";
    case "texinfo": return "application/x-texinfo";
    case "tgz": return "application/x-compressed";
    case "thmx": return "application/vnd.ms-officetheme";
    case "thn": return "application/octet-stream";
    case "tif": return "image/tiff";
    case "tiff": return "image/tiff";
    case "tlh": return "text/plain";
    case "tli": return "text/plain";
    case "toc": return "application/octet-stream";
    case "tr": return "application/x-troff";
    case "trm": return "application/x-msterminal";
    case "trx": return "application/xml";
    case "ts": return "video/vnd.dlna.mpeg-tts";
    case "tsv": return "text/tab-separated-values";
    case "ttf": return "application/octet-stream";
    case "tts": return "video/vnd.dlna.mpeg-tts";
    case "txt": return "text/plain";
    case "u32": return "application/octet-stream";
    case "uls": return "text/iuls";
    case "user": return "text/plain";
    case "ustar": return "application/x-ustar";
    case "vb": return "text/plain";
    case "vbdproj": return "text/plain";
    case "vbk": return "video/mpeg";
    case "vbproj": return "text/plain";
    case "vbs": return "text/vbscript";
    case "vcf": return "text/x-vcard";
    case "vcproj": return "application/xml";
    case "vcs": return "text/plain";
    case "vcxproj": return "application/xml";
    case "vddproj": return "text/plain";
    case "vdp": return "text/plain";
    case "vdproj": return "text/plain";
    case "vdx": return "application/vnd.ms-visio.viewer";
    case "vml": return "text/xml";
    case "vscontent": return "application/xml";
    case "vsct": return "text/xml";
    case "vsd": return "application/vnd.visio";
    case "vsi": return "application/ms-vsi";
    case "vsix": return "application/vsix";
    case "vsixlangpack": return "text/xml";
    case "vsixmanifest": return "text/xml";
    case "vsmdi": return "application/xml";
    case "vspscc": return "text/plain";
    case "vss": return "application/vnd.visio";
    case "vsscc": return "text/plain";
    case "vssettings": return "text/xml";
    case "vssscc": return "text/plain";
    case "vst": return "application/vnd.visio";
    case "vstemplate": return "text/xml";
    case "vsto": return "application/x-ms-vsto";
    case "vsw": return "application/vnd.visio";
    case "vsx": return "application/vnd.visio";
    case "vtx": return "application/vnd.visio";
    case "wav": return "audio/wav";
    case "wave": return "audio/wav";
    case "wax": return "audio/x-ms-wax";
    case "wbk": return "application/msword";
    case "wbmp": return "image/vnd.wap.wbmp";
    case "wcm": return "application/vnd.ms-works";
    case "wdb": return "application/vnd.ms-works";
    case "wdp": return "image/vnd.ms-photo";
    case "webarchive": return "application/x-safari-webarchive";
    case "webtest": return "application/xml";
    case "wiq": return "application/xml";
    case "wiz": return "application/msword";
    case "wks": return "application/vnd.ms-works";
    case "wlmp": return "application/wlmoviemaker";
    case "wlpginstall": return "application/x-wlpg-detect";
    case "wlpginstall3": return "application/x-wlpg3-detect";
    case "wm": return "video/x-ms-wm";
    case "wma": return "audio/x-ms-wma";
    case "wmd": return "application/x-ms-wmd";
    case "wmf": return "application/x-msmetafile";
    case "wml": return "text/vnd.wap.wml";
    case "wmlc": return "application/vnd.wap.wmlc";
    case "wmls": return "text/vnd.wap.wmlscript";
    case "wmlsc": return "application/vnd.wap.wmlscriptc";
    case "wmp": return "video/x-ms-wmp";
    case "wmv": return "video/x-ms-wmv";
    case "wmx": return "video/x-ms-wmx";
    case "wmz": return "application/x-ms-wmz";
    case "wpl": return "application/vnd.ms-wpl";
    case "wps": return "application/vnd.ms-works";
    case "wri": return "application/x-mswrite";
    case "wrl": return "x-world/x-vrml";
    case "wrz": return "x-world/x-vrml";
    case "wsc": return "text/scriptlet";
    case "wsdl": return "text/xml";
    case "wvx": return "video/x-ms-wvx";
    case "x": return "application/directx";
    case "xaf": return "x-world/x-vrml";
    case "xaml": return "application/xaml+xml";
    case "xap": return "application/x-silverlight-app";
    case "xbap": return "application/x-ms-xbap";
    case "xbm": return "image/x-xbitmap";
    case "xdr": return "text/plain";
    case "xht": return "application/xhtml+xml";
    case "xhtml": return "application/xhtml+xml";
    case "xla": return "application/vnd.ms-excel";
    case "xlam": return "application/vnd.ms-excel.addin.macroenabled.12";
    case "xlc": return "application/vnd.ms-excel";
    case "xld": return "application/vnd.ms-excel";
    case "xlk": return "application/vnd.ms-excel";
    case "xll": return "application/vnd.ms-excel";
    case "xlm": return "application/vnd.ms-excel";
    case "xls": return "application/vnd.ms-excel";
    case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroenabled.12";
    case "xlsm": return "application/vnd.ms-excel.sheet.macroenabled.12";
    case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    case "xlt": return "application/vnd.ms-excel";
    case "xltm": return "application/vnd.ms-excel.template.macroenabled.12";
    case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
    case "xlw": return "application/vnd.ms-excel";
    case "xml": return "text/xml";
    case "xmta": return "application/xml";
    case "xof": return "x-world/x-vrml";
    case "xoml": return "text/plain";
    case "xpm": return "image/x-xpixmap";
    case "xps": return "application/vnd.ms-xpsdocument";
    case "xrm-ms": return "text/xml";
    case "xsc": return "application/xml";
    case "xsd": return "text/xml";
    case "xsf": return "text/xml";
    case "xsl": return "text/xml";
    case "xslt": return "text/xml";
    case "xsn": return "application/octet-stream";
    case "xss": return "application/xml";
    case "xtp": return "application/octet-stream";
    case "xwd": return "image/x-xwindowdump";
    case "z": return "application/x-compress";
    case "zip": return "application/x-zip-compressed";
  #endregion
    default: return "application/octet-stream";
  }
}

Store images in a MongoDB database

You can use the bin data type if you are using any scripting language to store files/images in MongoDB. Bin data is developed to store small size of files.

Refer to your scripting language driver. For PHP, click here.

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

Convert Char to String in C

This is an old question, but I'd say none of the answers really fits the OP's question. All he wanted/needed to do is this:

char c = std::fgetc(fp);
std::strcpy(buffer, &c);

The relevant aspect here is the fact, that the second argument of strcpy() doesn't need to be a char array / c-string. In fact, none of the arguments is a char or char array at all. They are both char pointers:

strcpy(char* dest, const char* src);

dest : A non-const char pointer
Its value has to be the memory address of an element of a writable char array (with at least one more element after that).
src : A const char pointer
Its value can be the address of a single char, or of an element in a char array. That array must contain the special character \0 within its remaining elements (starting with src), to mark the end of the c-string that should be copied.

What is LDAP used for?

To take the definitions the other mentioned earlier a bit further, how about this perspective...

LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).

There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).

LDAP is just a very lightweight DAP, as the name suggests.

Handling very large numbers in Python

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int type has been dropped completely.

That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.

You can find all the gory details in PEP 0237.

EPPlus - Read Excel Table

This is my working version. Note that the resolvers code is not shown but are a spin on my implementation which allows columns to be resolved even though they are named slightly differently in each worksheet.

public static IEnumerable<T> ToArray<T>(this ExcelWorksheet worksheet, List<PropertyNameResolver> resolvers) where T : new()
{

  // List of all the column names
  var header = worksheet.Cells.GroupBy(cell => cell.Start.Row).First();

  // Get the properties from the type your are populating
  var properties = typeof(T).GetProperties().ToList();


  var start = worksheet.Dimension.Start;
  var end = worksheet.Dimension.End;

  // Resulting list
  var list = new List<T>();

  // Iterate the rows starting at row 2 (ie start.Row + 1)
  for (int row = start.Row + 1; row <= end.Row; row++)
  {
    var instance = new T();
    for (int col = start.Column; col <= end.Column; col++)
    {
      object value = worksheet.Cells[row, col].Text;

      // Get the column name zero based (ie col -1)
      var column = (string)header.Skip(col - 1).First().Value;

      // Gets the corresponding property to set
      var property = properties.Property(resolvers, column);

      try
      {
        var propertyName = property.PropertyType.IsGenericType
          ? property.PropertyType.GetGenericArguments().First().FullName
          : property.PropertyType.FullName;


        // Implement setter code as needed. 
        switch (propertyName)
        {
          case "System.String":
            property.SetValue(instance, Convert.ToString(value));
            break;
          case "System.Int32":
            property.SetValue(instance, Convert.ToInt32(value));
            break;
          case "System.DateTime":
            if (DateTime.TryParse((string) value, out var date))
            {
              property.SetValue(instance, date);
            }
            property.SetValue(instance, FromExcelSerialDate(Convert.ToInt32(value)));
            break;
          case "System.Boolean":
            property.SetValue(instance, (int)value == 1);
            break;
        }
      }
      catch (Exception e)
      {
        // instance property is empty because there was a problem.
      }

    } 
    list.Add(instance);
  }
  return list;
}

// Utility function taken from the above post's inline function.
public static DateTime FromExcelSerialDate(int excelDate)
{
  if (excelDate < 1)
    throw new ArgumentException("Excel dates cannot be smaller than 0.");

  var dateOfReference = new DateTime(1900, 1, 1);

  if (excelDate > 60d)
    excelDate = excelDate - 2;
  else
    excelDate = excelDate - 1;
  return dateOfReference.AddDays(excelDate);
}

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

passing form data to another HTML page

If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.

In the form, add a method="GET" attribute:

<form action="display.html" method="GET">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

When they submit this form, the user will be directed to an address which includes the serialNumber value as a parameter. Something like:

http://www.example.com/display.html?serialNumber=XYZ

You should then be able to parse the query string - which will contain the serialNumber parameter value - from JavaScript, using the window.location.search value:

// from display.html
document.getElementById("write").innerHTML = window.location.search; // you will have to parse
                                                                     // the query string to extract the
                                                                     // parameter you need

See also JavaScript query string.


The alternative is to store the values in cookies when the form is submit and read them out of the cookies again once the display.html page loads.

See also How to use JavaScript to fill a form on another page.

Tomcat starts but home page cannot open with url http://localhost:8080

For *Unix based systems, you can check the ports used by a particular application by issueing the following command in the terminal

[~/.]$ netstat -tuplen

You will get the list of all the ports that are being currently held and used by their respective process ID's

Redirect from an HTML page

Redirect using JavaScript, <noscript> in case JS is disabled.

<script>
    window.location.replace("https://google.com");
</script>

<noscript>
    <a href="https://google.com">Click here if you are not redirected automatically.</a>
</noscript>

angularjs getting previous route path

This alternative also provides a back function.

The template:

<a ng-click='back()'>Back</a>

The module:

myModule.run(function ($rootScope, $location) {

    var history = [];

    $rootScope.$on('$routeChangeSuccess', function() {
        history.push($location.$$path);
    });

    $rootScope.back = function () {
        var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
        $location.path(prevUrl);
    };

});

Performance differences between ArrayList and LinkedList

In a LinkedList the elements have a reference to the element before and after it. In an ArrayList the data structure is just an array.

  1. A LinkedList needs to iterate over N elements to get the Nth element. An ArrayList only needs to return element N of the backing array.

  2. The backing array needs to either be reallocated for the new size and the array copied over or every element after the deleted element needs to be moved up to fill the empty space. A LinkedList just needs to set the previous reference on the element after the removed to the one before the removed and the next reference on the element before the removed element to the element after the removed element. Longer to explain, but faster to do.

  3. Same reason as deletion here.

CSV file written with Python has blank lines between each row

In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes \r\n into the file directly. If you don't open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

In Python 3 the required syntax changed (see documentation links below), so open outfile with the additional parameter newline='' (empty string) instead.

Examples:

# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

Documentation Links

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How to read line by line of a text area HTML tag

Try this.

var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
    //code here using lines[i] which will give you each line
}

Laravel Eloquent "WHERE NOT IN"

The dynamic way of implement whereNotIn:

 $users = User::where('status',0)->get();
    foreach ($users as $user) {
                $data[] = $user->id;
            }
    $available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();

how to change class name of an element by jquery

$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');

Your code has two problems:

  1. The selector .IsBestAnswe does not match what you thought
  2. It's addClass(), not addclass().

Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer') part to add only:

$('.IsBestAnswer').addClass('bestanswer');

You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer vs. bestanswer).

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Catching access violation exceptions?

Not the exception handling mechanism, But you can use the signal() mechanism that is provided by the C.

> man signal

     11    SIGSEGV      create core image    segmentation violation

Writing to a NULL pointer is probably going to cause a SIGSEGV signal

C# equivalent of the IsNull() function in SQL Server

    public static T IsNull<T>(this T DefaultValue, T InsteadValue)
    {

        object obj="kk";

        if((object) DefaultValue == DBNull.Value)
        {
            obj = null;
        }

        if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
        {
            return InsteadValue;
        }
        else
        {
            return DefaultValue;
        }

    }

//This method can work with DBNull and null value. This method is question's answer

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

jquery stop child triggering parent event

Better way by using on() with chaining like,

$(document).ready(function(){
    $(".header").on('click',function(){
        $(this).children(".children").toggle();
    }).on('click','a',function(e) {
        e.stopPropagation();
   });
});

Add image in title bar

That method will not work. The <title> only supports plain text. You will need to create an .ico image with the filename of favicon.ico and save it into the root folder of your site (where your default page is).

Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head> section of your HTML and reference your icon:

<link rel="shortcut icon" href="your_image_path_and_name.ico" />

You can use Photoshop (with a plug in) or GIMP (free) to create an .ico file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).

Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.

Update 2: You can also use .png images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico files.

Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

Essentially you want to add code to the Calculate event of the relevant Worksheet.

In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.

Alternatively, copy the code below into the editor of the sheet you want to use:

Private Sub Worksheet_Calculate()

If Sheets("MySheet").Range("A1").Value > 0.5 Then
    MsgBox "Over 50%!", vbOKOnly
End If

End Sub

This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.

How to change the docker image installation directory?

Following advice from comments I utilize Docker systemd documentation to improve this answer. Below procedure doesn't require reboot and is much cleaner.

First create directory and file for custom configuration:

sudo mkdir -p /etc/systemd/system/docker.service.d
sudo $EDITOR /etc/systemd/system/docker.service.d/docker-storage.conf

For docker version before 17.06-ce paste:

[Service]
ExecStart=
ExecStart=/usr/bin/docker daemon -H fd:// --graph="/mnt"

For docker after 17.06-ce paste:

[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// --data-root="/mnt"

Alternative method through daemon.json

I recently tried above procedure with 17.09-ce on Fedora 25 and it seem to not work. Instead of that simple modification in /etc/docker/daemon.json do the trick:

{
    "graph": "/mnt",
    "storage-driver": "overlay"
}

Despite the method you have to reload configuration and restart Docker:

sudo systemctl daemon-reload
sudo systemctl restart docker

To confirm that Docker was reconfigured:

docker info|grep "loop file"

In recent version (17.03) different command is required:

docker info|grep "Docker Root Dir"

Output should look like this:

 Data loop file: /mnt/devicemapper/devicemapper/data
 Metadata loop file: /mnt/devicemapper/devicemapper/metadata

Or:

 Docker Root Dir: /mnt

Then you can safely remove old Docker storage:

rm -rf /var/lib/docker

What is the best way to update the entity in JPA

That depends on what you want to do, but as you said, getting an entity reference using find() and then just updating that entity is the easiest way to do that.

I'd not bother about performance differences of the various methods unless you have strong indications that this really matters.

C# Encoding a text string with line breaks

Yes - it means you're using \n as the line break instead of \r\n. Notepad only understands the latter.

(Note that Environment.NewLine suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n, you should specify it explicitly.)

Generating a SHA-256 hash from the Linux command line

For the sha256 hash in base64, use:

echo -n foo | openssl dgst -binary -sha1 | openssl base64

Example

echo -n foo | openssl dgst -binary -sha1 | openssl base64
C+7Hteo/D9vJXQ3UfzxbwnXaijM=

How do I vertically align text in a paragraph?

If the answers that involve tables or setting line-height don't work for you, you can experiment with wrapping the p element in a div and style its positioning relative to the height of the parent div.

_x000D_
_x000D_
.parent-div{_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.text-div{_x000D_
  position: relative;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
}_x000D_
_x000D_
p.event_desc{_x000D_
  font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="parent-div">_x000D_
  <div class="text-div">_x000D_
   <p class="event_desc">_x000D_
    MY TEXT_x000D_
   </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to host google web fonts on my own server?

My solution was to download the TTF files from google web fonts and then use onlinefontconverter.com.

Create a folder and sub folder in Excel VBA

One sub and two functions. The sub builds your path and use the functions to check if the path exists and create if not. If the full path exists already, it will just pass on by. This will work on PC, but you will have to check what needs to be modified to work on Mac as well.

'requires reference to Microsoft Scripting Runtime
Sub MakeFolder()

Dim strComp As String, strPart As String, strPath As String

strComp = Range("A1") ' assumes company name in A1
strPart = CleanName(Range("C1")) ' assumes part in C1
strPath = "C:\Images\"

If Not FolderExists(strPath & strComp) Then 
'company doesn't exist, so create full path
    FolderCreate strPath & strComp & "\" & strPart
Else
'company does exist, but does part folder
    If Not FolderExists(strPath & strComp & "\" & strPart) Then
        FolderCreate strPath & strComp & "\" & strPart
    End If
End If

End Sub

Function FolderCreate(ByVal path As String) As Boolean

FolderCreate = True
Dim fso As New FileSystemObject

If Functions.FolderExists(path) Then
    Exit Function
Else
    On Error GoTo DeadInTheWater
    fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
    Exit Function
End If

DeadInTheWater:
    MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
    FolderCreate = False
    Exit Function

End Function

Function FolderExists(ByVal path As String) As Boolean

FolderExists = False
Dim fso As New FileSystemObject

If fso.FolderExists(path) Then FolderExists = True

End Function

Function CleanName(strName as String) as String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters

    CleanName = Replace(strName, "/","")
    CleanName = Replace(CleanName, "*","")
    etc...

End Function

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

How to add some non-standard font to a website?

The technique that the W3C has recommended for do this is called "embedding" and is well described by the three articles here: Embedding Fonts. In my limited experiments, I have found this process error-prone and have had limited success in making it function in a multi-browser environment.

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

WPF Check box: Check changed handling

What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.

How to disable right-click context-menu in JavaScript

You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.

Error while sending QUERY packet

You cannot have the WHERE clause in an INSERT statement.

insert into table1(data) VALUES(:data) where sno ='45830'

Should be

insert into table1(data) VALUES(:data)


Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:

SET GLOBAL max_allowed_packet=32M

Change the 32M (32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.

Android Design Support Library expandable Floating Action Button(FAB) menu

Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.

Just using animate().translationY() function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.

first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab3"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_btn_speak_now" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_dialog_map" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

Now in your java class just define all your FAB and perform the click like shown below:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab1 = (FloatingActionButton) findViewById(R.id.fab1);
    fab2 = (FloatingActionButton) findViewById(R.id.fab2);
    fab3 = (FloatingActionButton) findViewById(R.id.fab3);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isFABOpen){
                showFABMenu();
            }else{
                closeFABMenu();
            }
        }
    });

Use the animation().translationY() to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:

 private void showFABMenu(){
    isFABOpen=true;
    fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
    fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
    fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}

private void closeFABMenu(){
    isFABOpen=false;
    fab1.animate().translationY(0);
    fab2.animate().translationY(0);
    fab3.animate().translationY(0);
}

Now define the above mentioned dimension inside res->values->dimens.xml as shown below:

    <dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>

That's all hope this solution will help the people in future, who are searching for simple solution.

EDITED

If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github

to close the FAB on Backpress, override onBackPress() as showen below:

    @Override
public void onBackPressed() {
    if(!isFABOpen){
        this.super.onBackPressed();
    }else{
        closeFABMenu();
    }
}

The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub

enter image description here

Get program execution time in the shell

If you intend to use the times later to compute with, learn how to use the -f option of /usr/bin/time to output code that saves times. Here's some code I used recently to get and sort the execution times of a whole classful of students' programs:

fmt="run { date = '$(date)', user = '$who', test = '$test', host = '$(hostname)', times = { user = %U, system = %S, elapsed = %e } }"
/usr/bin/time -f "$fmt" -o $timefile command args...

I later concatenated all the $timefile files and pipe the output into a Lua interpreter. You can do the same with Python or bash or whatever your favorite syntax is. I love this technique.

"No backupset selected to be restored" SQL Server 2012

I had this problem and it turned out I was trying to restore to the wrong version of SQL. If you want more information on what's going on, try restoring the database using the following SQL:

RESTORE DATABASE <YourDatabase> 
FROM DISK='<the path to your backup file>\<YourDatabase>.bak'

That should give you the error message that you need to debug this.

How to add a Java Properties file to my Java Project in Eclipse

If you are working with core java, create your file(.properties) by right clicking your project. If the file is present inside your package or src folder it will throw an file not found error

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

use grep -n -i null myfile.txt to output the line number in front of each match.

I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

grep -n -i null myfile.txt | wc -l

Android Studio says "cannot resolve symbol" but project compiles

I had this problem for a couple of days now and finally figured it out! All other solutions didn't work for me btw.

Solution: I had special characters in my project path!

Just make sure to have none of those and you should be fine or at least one of the other solutions should work for you.

Hope this helps someone!

Comparing two NumPy arrays for equality, element-wise

Usually two arrays will have some small numeric errors,

You can use numpy.allclose(A,B), instead of (A==B).all(). This returns a bool True/False

ListView item background via custom selector

instead of:

android:drawable="@color/transparent" 

write

android:drawable="@android:color/transparent"

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'

Is Python interpreted, or compiled, or both?

The answer depends on what implementation of python is being used. If you are using lets say CPython (The Standard implementation of python) or Jython (Targeted for integration with java programming language)it is first translated into bytecode, and depending on the implementation of python you are using, this bycode is directed to the corresponding virtual machine for interpretation. PVM (Python Virtual Machine) for CPython and JVM (Java Virtual Machine) for Jython.

But lets say you are using PyPy which is another standard CPython implementation. It would use a Just-In-Time Compiler.

Can I Set "android:layout_below" at Runtime Programmatically?

Yes:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.

How to put multiple statements in one line?

I know I am late, but stumped into the question, and based on ThomasH's answer:

for i in range(4): print "i equals 3" if i==3 else None

output: None None None i equals 3

I propose to update as:

for i in range(4): print("i equals 3") if i==3 else print('', end='')

output: i equals 3

Note, I am in python3 and had to use two print commands. pass after else won't work. Wanted to just comment on ThomasH's answer, but can't because I don't have enough reputation yet.

Getting index value on razor foreach

Is there a reason you're not using CSS selectors to style the first and last elements instead of trying to attach a custom class to them? Instead of styling based on alpha or omega, use first-child and last-child.

http://www.quirksmode.org/css/firstchild.html

React Native: Possible unhandled promise rejection

You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

C# : "A first chance exception of type 'System.InvalidOperationException'"

Consider using System.Windows.Forms.Timer instead of System.Threading.Timer for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.

In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.

Convert timestamp to readable date/time PHP

echo date("l M j, Y",$res1['timep']);
This is really good for converting a unix timestamp to a readable date along with day. Example: Thursday Jul 7, 2016

java.security.AccessControlException: Access denied (java.io.FilePermission

Within your <jre location>\lib\security\java.policy try adding:

grant { permission java.security.AllPermission; };

And see if it allows you. If so, you will have to add more granular permissions.

See:

Java 8 Documentation for java.policy files

and

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

R - " missing value where TRUE/FALSE needed "

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

Center image in div horizontally

A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:

.top_image img { margin:0 auto; }

More information and examples from W3C.

Best practices for copying files with Maven

I've had very good experience with copy-maven-plugin. It has a much more convenient and concise syntax in comparison to maven-resources-plugin.

How to access cookies in AngularJS?

The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.

Now, if you want to integrate js-cookie with angular, it is as easy as something like:

module.factory( "cookies", function() {
  return Cookies.noConflict();
});

And that's it. No jQuery. No ngCookies.


You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign + instead of also percent-encode it:

module.factory( "phpCookies", function() {
  return Cookies
    .noConflict()
    .withConverter(function( value, name ) {
      return value
            // Decode all characters according to the "encodeURIComponent" spec
            .replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
            // Decode the plus sign to spaces
            .replace(/\+/g, ' ')
    });
});

The usage for a custom Provider would be something like this:

module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
  this.storeData = function( data ) {
    phpCookies.set( "data", data );
  };
  this.containsStoredData = function() {
    return phpCookies.get( "data" );
  }
}]);

I hope this helps anyone.

See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103

For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

CSS transition fade on hover

This will do the trick

.gallery-item
{
  opacity:1;
}

.gallery-item:hover
{
  opacity:0;
  transition: opacity .2s ease-out;
  -moz-transition: opacity .2s ease-out;
  -webkit-transition: opacity .2s ease-out;
  -o-transition: opacity .2s ease-out;
}

React: how to update state.item[1] in state using setState?

Since there's a lot of misinformation in this thread, here's how you can do it without helper libs:

handleChange: function (e) {
    // 1. Make a shallow copy of the items
    let items = [...this.state.items];
    // 2. Make a shallow copy of the item you want to mutate
    let item = {...items[1]};
    // 3. Replace the property you're intested in
    item.name = 'newName';
    // 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
    items[1] = item;
    // 5. Set the state to our new copy
    this.setState({items});
},

You can combine steps 2 and 3 if you want:

let item = {
    ...items[1],
    name: 'newName'
}

Or you can do the whole thing in one line:

this.setState(({items}) => ({
    items: [
        ...items.slice(0,1),
        {
            ...items[1],
            name: 'newName',
        },
        ...items.slice(2)
    ]
}));

Note: I made items an array. OP used an object. However, the concepts are the same.


You can see what's going on in your terminal/console:

? node
> items = [{name:'foo'},{name:'bar'},{name:'baz'}]
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ]
> clone = [...items]
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ]
> item1 = {...clone[1]}
{ name: 'bar' }
> item1.name = 'bacon'
'bacon'
> clone[1] = item1
{ name: 'bacon' }
> clone
[ { name: 'foo' }, { name: 'bacon' }, { name: 'baz' } ]
> items
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ] // good! we didn't mutate `items`
> items === clone
false // these are different objects
> items[0] === clone[0]
true // we don't need to clone items 0 and 2 because we're not mutating them (efficiency gains!)
> items[1] === clone[1]
false // this guy we copied

Webdriver findElements By xpath

Your questions:

Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText() Where getText will return all text content of all children of your result.

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.

Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for. Example:

<p1> <div/> </p1 <p2/> 

The following to parent of the div is p2. This would be:

 //div[@id='container'][1]/parent::*/following-sibling::* 

or shorter

 //div[@id='container'][1]/../following-sibling::* 

If you are only looking for the first one extent the expression with an "predicate" (e.g [1] - for the first one. or [position() &lt; 4]for the first three)

If your are looking for the first child of the first div:

//div[@id='container'][1]/*[1]

If there is only one div with id an you are looking for the first child:

   //div[@id='container']/*[1]

and so on.

PHP random string generator

Please, try this my function to generate a custom random alphanumeric string:

<?php
  function random_alphanumeric($length) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
    $my_string = '';
    for ($i = 0; $i < $length; $i++) {
      $pos = mt_rand(0, strlen($chars) -1);
      $my_string .= substr($chars, $pos, 1);
    }
    return $my_string;
  }
?>

You can adjust the result by passing the length of the string to the function like below:

  $test_with_50_items = random_alphanumeric(50); // 50 characters
  echo $test_with_50_items;

Example (test_with_50_items): Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86

If you need more than 50 chars or less simply call the function how you like:

  $test_with_27_items = random_alphanumeric(27); // 27 characters
  echo $test_with_27_items;

If you need two or more unique strings you can do by loop using while so you are sure to get two unique strings... you can do the same with more strings, the only limit is your fantasy...

  $string_1 = random_alphanumeric(50);
  $string_2 = random_alphanumeric(50);
  while ($string_1 == $string_2) {
    $string_1 = random_alphanumeric(50);
    $string_2 = random_alphanumeric(50);
    if ($string_1 != $string_2) {
       break;
    }
  }
  echo $string_1;
  echo "<br>\n";
  echo $string_2;

$string_1: KkvUwia8rbDEV2aChWqm3AgeUZqyrRbUx2AxVhx5s4TSJ2VwA4

$string_2: XraO85YfxBBCInafvwipSOJwLmk6JMWiuWOxYQDnXohcn2D8K6

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

(Get-Date (Get-Date -Format d)).AddHours(-2)

How to calculate the running time of my program?

Use System.nanoTime to get the current time.

long startTime = System.nanoTime();
.....your program....
long endTime   = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);

The above code prints the running time of the program in nanoseconds.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

The existing answers already cover the "how", but I just wanted to elaborate on the "what" and "why" for others who might be wondering.

What a compiler (gcc) does: The term "compile" is a bit of an overloaded term because it is used at a high-level to mean "convert source code to a program", but more technically means to "convert source code to object code". A compiler like gcc actually performs two related, but arguably distinct functions to turn your source code into a program: compiling (as in the latter definition of turning source to object code) and linking (the process of combining the necessary object code files together into one complete executable).

The original error that you saw is technically a "linking error", and is thrown by "ld", the linker. Unlike (strict) compile-time errors, there is no reference to source code lines, as the linker is already in object space.

By default, when gcc is given source code as input, it attempts to compile each and then link them all together. As noted in the other responses, it's possible to use flags to instruct gcc to just compile first, then use the object files later to link in a separate step. This two-step process may seem unnecessary (and probably is for very small programs) but it is very important when managing a very large program, where compiling the entire project each time you make a small change would waste a considerable amount of time.

How to add multiple columns to pandas dataframe in one assignment?

With the use of concat:

In [128]: df
Out[128]: 
   col_1  col_2
0      0      4
1      1      5
2      2      6
3      3      7

In [129]: pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
Out[129]: 
   col_1  col_2 column_new_1 column_new_2 column_new_3
0    0.0    4.0          NaN          NaN          NaN
1    1.0    5.0          NaN          NaN          NaN
2    2.0    6.0          NaN          NaN          NaN
3    3.0    7.0          NaN          NaN          NaN

Not very sure of what you wanted to do with [np.nan, 'dogs',3]. Maybe now set them as default values?

In [142]: df1 = pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
In [143]: df1[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs', 3]

In [144]: df1
Out[144]: 
   col_1  col_2  column_new_1 column_new_2  column_new_3
0    0.0    4.0           NaN         dogs             3
1    1.0    5.0           NaN         dogs             3
2    2.0    6.0           NaN         dogs             3
3    3.0    7.0           NaN         dogs             3

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

You also have to delete the local branch:

git branch -d 6796

Another way is to prune all stale branches from your local repository. This will delete all local branches that already have been removed from the remote:

git remote prune origin --dry-run

Android Studio - Unable to find valid certification path to requested target

If you still have the problem, try deleting the directory named '.AndroidStudio1.2' under 'C:\Users\UserName\.AndroidStudio1.2'

Of course the name differs according to which version you have

That worked for me

What's a quick way to comment/uncomment lines in Vim?

Press ctrl+v then use ? or ? to select the number of lines to comment. Then press shift+I, press # and then ESC. This will comment out the number of lines you have selected.

The opposite for uncomment lines.

Converting a Uniform Distribution to a Normal Distribution

I have the following code which maybe could help:

set.seed(123)
n <- 1000
u <- runif(n) #creates U
x <- -log(u)
y <- runif(n, max=u*sqrt((2*exp(1))/pi)) #create Y
z <- ifelse (y < dnorm(x)/2, -x, NA)
z <- ifelse ((y > dnorm(x)/2) & (y < dnorm(x)), x, z)
z <- z[!is.na(z)]

What's a good IDE for Python on Mac OS X?

since you are familiar with Eclipse maybe you are interested in Pydev

Angular 2 change event on every keypress

In my case, the solution is:

[ngModel]="X?.Y" (ngModelChange)="X.Y=$event"

Eclipse: Set maximum line length for auto formatting?

For HTML / PHP / JSP / JSPF: Web -> HTML Files -> Editor -> Line width

Get top first record from duplicate records having no unique identity

Find all products that has been ordered 1 or more times... (kind of duplicate records)

SELECT DISTINCT * from [order_items] where productid in 
(SELECT productid 
  FROM [order_items]
  group by productid 
  having COUNT(*)>0)
order by productid 

To select the last inserted of those...

SELECT DISTINCT productid, MAX(id) OVER (PARTITION BY productid) AS LastRowId from [order_items] where productid in 
(SELECT productid 
  FROM [order_items]
  group by productid 
  having COUNT(*)>0)
order by productid 

How to change the output color of echo in Linux

This is the color switch \033[. See history.

Color codes are like 1;32 (Light Green), 0;34 (Blue), 1;34 (Light Blue), etc.

We terminate color sequences with a color switch \033[ and 0m, the no-color code. Just like opening and closing tabs in a markup language.

  SWITCH="\033["
  NORMAL="${SWITCH}0m"
  YELLOW="${SWITCH}1;33m"
  echo "${YELLOW}hello, yellow${NORMAL}"

Simple color echo function solution:

cecho() {
  local code="\033["
  case "$1" in
    black  | bk) color="${code}0;30m";;
    red    |  r) color="${code}1;31m";;
    green  |  g) color="${code}1;32m";;
    yellow |  y) color="${code}1;33m";;
    blue   |  b) color="${code}1;34m";;
    purple |  p) color="${code}1;35m";;
    cyan   |  c) color="${code}1;36m";;
    gray   | gr) color="${code}0;37m";;
    *) local text="$1"
  esac
  [ -z "$text" ] && local text="$color$2${code}0m"
  echo "$text"
}

cecho "Normal"
cecho y "Yellow!"

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

encrypt and decrypt md5

/* you  can match the exact string with table value*/

if(md5("string to match") == $res["hashstring"])
 echo "login correct";

What is difference between mutable and immutable String in java

In Java, all strings are immutable(Can't change). When you are trying to modify a String, what you are really doing is creating a new one.

Following ways we can create the string object

  1. Using String literal

    String str="java";
    
  2. Using new keyword

    String str = new String("java");
    
  3. Using character array

    char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
    
    String helloString = new String(helloArray);   
    

coming to String immutability, simply means unmodifiable or unchangeable

Let's take one example

I'm initializing the value to the String literal s

String s="kumar";

Below I'm going to display the decimal representation of the location address using hashcode()

System.out.println(s.hashCode());

Simply printing the value of a String s

System.out.println("value "+s);

Okay, this time I'm inittializing value "kumar" to s1

String s1="kumar";   // what you think is this line, takes new location in the memory ??? 

Okay let's check by displaying hashcode of the s1 object which we created

System.out.println(s1.hashCode());

okay, let's check below code

String s2=new String("Kumar");
    System.out.println(s2.hashCode());  // why this gives the different address ??

Okay, check this below code at last

String s3=new String("KUMAR");
    System.out.println(s3.hashCode());  // again different address ???

YES, if you see Strings 's' and 's1' having the same hashcode because the value hold by 's' & 's1' are same that is 'kumar'

Let's consider String 's2' and 's3' these two Strings hashcode appears to be different in the sense, they both stored in a different location because you see their values are different.

since s and s1 hashcode is same because those values are same and storing in the same location.

Example 1: Try below code and analyze line by line

public class StringImmutable {
public static void main(String[] args) {

    String s="java";
    System.out.println(s.hashCode());
    String s1="javA";
    System.out.println(s1.hashCode());
    String s2=new String("Java");
    System.out.println(s2.hashCode());
    String s3=new String("JAVA");
    System.out.println(s3.hashCode());
}
}

Example 2: Try below code and analyze line by line

public class StringImmutable {
    public static void main(String[] args) {

        String s="java";
        s.concat(" programming");  // s can not be changed "immutablity"
        System.out.println("value of s "+s);
        System.out.println(" hashcode of s "+s.hashCode());

        String s1="java";
        String s2=s.concat(" programming");   // s1 can not be changed "immutablity" rather creates object s2
        System.out.println("value of s1 "+s1);
        System.out.println(" hashcode of s1 "+s1.hashCode());  

        System.out.println("value of s2 "+s2);
        System.out.println(" hashcode of s2 "+s2.hashCode());

    }
}

Okay, Let's look what is the difference between mutable and immutable.

mutable(it change) vs. immutable (it can't change)

public class StringMutableANDimmutable {
    public static void main(String[] args) {


        // it demonstrates immutable concept
        String s="java";
        s.concat(" programming");  // s can not be changed (immutablity)
        System.out.println("value of s ==  "+s); 
        System.out.println(" hashcode of s == "+s.hashCode()+"\n\n");


        // it demonstrates mutable concept
        StringBuffer s1= new StringBuffer("java");
        s1.append(" programming");  // s can be changed (mutablity)
        System.out.println("value of s1 ==  "+s1); 
        System.out.println(" hashcode of s1 == "+s1.hashCode());


    }
}

Any further questions?? please write on...

How to undo a git merge with conflicts

Assuming you are using the latest git,

git merge --abort

How to set a Header field on POST a form?

If you are using JQuery with Form plugin, you can use:

$('#myForm').ajaxSubmit({
    headers: {
        "foo": "bar"
    }
});

Source: https://stackoverflow.com/a/31955515/9469069

How do I see the commit differences between branches in git?

I used some of the answers and found one that fit my case ( make sure all tasks are in the release branch).

Other methods works as well but I found that they might add lines that I do not need, like merge commits that add no value.

git fetch
git log origin/master..origin/release-1.1 --oneline --no-merges

or you can compare your current with master

git fetch
git log origin/master..HEAD --oneline --no-merges

git fetch is there to make sure you are using updated info.

In this way each commit will be on a line and you can copy/paste that into an text editor and start comparing the tasks with the commits that will be merged.

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

How to disable Google asking permission to regularly check installed apps on my phone?

In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".

How do I get a list of installed CPAN modules?

cd /the/lib/dir/of/your/perl/installation
perldoc $(find . -name perllocal.pod)

Windows users just do a Windows Explorer search to find it.

How to open some ports on Ubuntu?

Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.

Try using this command to allow a port

sudo ufw allow 1701

To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:

nc -l 1701

Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.

Given a DateTime object, how do I get an ISO 8601 date in string format?

To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:

public static string FormatDateTime(DateTime dateTime)
{
    return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
}

Generating HTML email body in C#

Updated Answer:

The documentation for SmtpClient, the class used in this answer, now reads, 'Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")'.

Source: https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official

Original Answer:

Using the MailDefinition class is the wrong approach. Yes, it's handy, but it's also primitive and depends on web UI controls--that doesn't make sense for something that is typically a server-side task.

The approach presented below is based on MSDN documentation and Qureshi's post on CodeProject.com.

NOTE: This example extracts the HTML file, images, and attachments from embedded resources, but using other alternatives to get streams for these elements are fine, e.g. hard-coded strings, local files, and so on.

Stream htmlStream = null;
Stream imageStream = null;
Stream fileStream = null;
try
{
    // Create the message.
    var from = new MailAddress(FROM_EMAIL, FROM_NAME);
    var to = new MailAddress(TO_EMAIL, TO_NAME);
    var msg = new MailMessage(from, to);
    msg.Subject = SUBJECT;
    msg.SubjectEncoding = Encoding.UTF8;
 
    // Get the HTML from an embedded resource.
    var assembly = Assembly.GetExecutingAssembly();
    htmlStream = assembly.GetManifestResourceStream(HTML_RESOURCE_PATH);
 
    // Perform replacements on the HTML file (if you're using it as a template).
    var reader = new StreamReader(htmlStream);
    var body = reader
        .ReadToEnd()
        .Replace("%TEMPLATE_TOKEN1%", TOKEN1_VALUE)
        .Replace("%TEMPLATE_TOKEN2%", TOKEN2_VALUE); // and so on...
 
    // Create an alternate view and add it to the email.
    var altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
    msg.AlternateViews.Add(altView);
 
    // Get the image from an embedded resource. The <img> tag in the HTML is:
    //     <img src="pid:IMAGE.PNG">
    imageStream = assembly.GetManifestResourceStream(IMAGE_RESOURCE_PATH);
    var linkedImage = new LinkedResource(imageStream, "image/png");
    linkedImage.ContentId = "IMAGE.PNG";
    altView.LinkedResources.Add(linkedImage);
 
    // Get the attachment from an embedded resource.
    fileStream = assembly.GetManifestResourceStream(FILE_RESOURCE_PATH);
    var file = new Attachment(fileStream, MediaTypeNames.Application.Pdf);
    file.Name = "FILE.PDF";
    msg.Attachments.Add(file);
 
    // Send the email
    var client = new SmtpClient(...);
    client.Credentials = new NetworkCredential(...);
    client.Send(msg);
}
finally
{
    if (fileStream != null) fileStream.Dispose();
    if (imageStream != null) imageStream.Dispose();
    if (htmlStream != null) htmlStream.Dispose();
}

How do I pass JavaScript values to Scriptlet in JSP?

I can provide two ways,

a.jsp,

<html>
    <script language="javascript" type="text/javascript">
        function call(){
            var name = "xyz";
            window.location.replace("a.jsp?name="+name);
        }
    </script>
    <input type="button" value="Get" onclick='call()'>
    <%
        String name=request.getParameter("name");
        if(name!=null){
            out.println(name);
        }
    %>
</html>

b.jsp,

<script>
    var v="xyz";
</script>
<% 
    String st="<script>document.writeln(v)</script>";
    out.println("value="+st); 
%>

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I update my Hibernate JPA to 2.1 and It works.

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Azure SQL Database "DTU percentage" metric

DTU is nothing but a blend of CPU, memory and IO. Why do we need a blend when these 3 are pretty clear? Because we want a unit for power. But it is still confusing in many ways. eg: If I simply increase memory will it increase power(DTU)? If yes, how can DTU be a blend? It is a yes. In this memory-increase case, as per the query in the answer given by jyong, DTU will be equivalent to memory(since we increased it). MS has even a pricing model based on this DTU and it raised many questions.

Because of these confusions and questions, MS wanted to bring in another option. We already had some specs in on-premise, why can't we use them? As a result, 'vCore pricing model' was born. In this model we have visibility to RAM and CPU. But not in DTU model.

The counter argument from DTU would be that DTU measures are calibrated using a benchmark that simulates real-world database workload. And that we are not in on-premise anymore ;). Yes it is designed with cloud computing in mind(but is also used in OLTP workloads).

But that is not all. Now that we are entering the pricing model the equation changes. The question now is about money and the bundle(what all features are included). Here DTU has some advantages(the way I see it) but enterprises with many existing licenses would disagree.

  • DTU has one pricing(Compute + Storage + Backup). Simpler and can start with lower pricing.
  • vCore has different pricing (Compute, Storage). Software assurance is available here. Enterprises will have on-premise licenses, this can be easily ported here(so they get big machines for less price than DTU model). Plus they commit for multiple years and get additional discounts.

We can switch between both when needed so if not sure start with DTU(Basic/Standard/Premium).

How can we know which pricing tier to use? Go to configure menu as given below: (on the right/left you can switch between both) VCore

DTU

Even though Vcore is bigger 'machine' and for bigger things, the cost can sometimes be cheaper for enterprise organizations. Here is a proof. DTU costs $147 . But Vcore costs $111. That is because you can commit for 3 years(but still pay monthly) and also because of the license re-use option(enterprises will have on-premise licenses).

Cost DTU

enter image description here

It is a bit too much than answering direct question but I am gonna go ahead and make this complete by answering 'how to choose between different options in DTU let alone choosing between DTU and vCore'. This is answered in this beautiful blog and this flowchart explains it all

enter image description here

How to prevent a click on a '#' link from jumping to top of page?

The <a href="#!">Link</a> and <a href="#/">Link</a> does not work if one has to click on the same input more than once.. it only takes in 1 event click for each on multiple inputs.

still the best way to go is with <a href="#">Link</a>

then,

event.preventDefault();

MyISAM versus InnoDB

Also check out some drop-in replacements for MySQL itself:

MariaDB

http://mariadb.org/

MariaDB is a database server that offers drop-in replacement functionality for MySQL. MariaDB is built by some of the original authors of MySQL, with assistance from the broader community of Free and open source software developers. In addition to the core functionality of MySQL, MariaDB offers a rich set of feature enhancements including alternate storage engines, server optimizations, and patches.

Percona Server

https://launchpad.net/percona-server

An enhanced drop-in replacement for MySQL, with better performance, improved diagnostics, and added features.

What is unit testing and how do you do it?

What exactly IS unit testing? Is it built into code or run as separate programs? Or something else?

From MSDN: The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.

Essentially, you are writing small bits of code to test the individual bits of your code. In the .net world, you would run these small bits of code using something like NUnit or MBunit or even the built in testing tools in visual studio. In Java you might use JUnit. Essentially the test runners will build your project, load and execute the unit tests and then let you know if they pass or fail.

How do you do it?

Well it's easier said than done to unit test. It takes quite a bit of practice to get good at it. You need to structure your code in a way that makes it easy to unit test to make your tests effective.

When should it be done? Are there times or projects not to do it? Is everything unit-testable?

You should do it where it makes sense. Not everything is suited to unit testing. For example UI code is very hard to unit test and you often get little benefit from doing so. Business Layer code however is often very suitable for tests and that is where most unit testing is focused.

Unit testing is a massive topic and to fully get an understanding of how it can best benefit you I'd recommend getting hold of a book on unit testing such as "Test Driven Development by Example" which will give you a good grasp on the concepts and how you can apply them to your code.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

For me, it was a much different solution since it was running on a virtualbox, so I had to edit the hosts file and add the virtualbox as a localhost

127.0.0.1 VirtualBox-blahblah

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

How can I change NULL to 0 when getting a single value from a SQL function?

Most database servers have a COALESCE function, which will return the first argument that is non-null, so the following should do what you want:

SELECT COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

Since there seems to be a lot of discussion about

COALESCE/ISNULL will still return NULL if no rows match, try this query you can copy-and-paste into SQL Server directly as-is:

SELECT coalesce(SUM(column_id),0) AS TotalPrice 
FROM sys.columns
WHERE (object_id BETWEEN -1 AND -2)

Note that the where clause excludes all the rows from sys.columns from consideration, but the 'sum' operator still results in a single row being returned that is null, which coalesce fixes to be a single row with a 0.

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

How to escape apostrophe (') in MySql?

Replace the string

value = value.replace(/'/g, "\\'");

where value is your string which is going to store in your Database.

Further,

NPM package for this, you can have look into it

https://www.npmjs.com/package/mysql-apostrophe

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

What is the difference between Python and IPython?

Even after viewing this thread, I had thought that ipython was a synonym for the python shell, in other words that typing python at the command line put one into ipython mode.

It is in fact, as referenced above, a very cool interactive shell (command line program) that can be installed from iPython.org or simply by running

pip install ipython

or the more extensive:

pip install ipython[notebook]

from the command line.

Javascript find json value

Making more general the @showdev answer.

var getObjectByValue = function (array, key, value) {
    return array.filter(function (object) {
        return object[key] === value;
    });
};

Example:

getObjectByValue(data, "code", "DZ" );

Determine a string's encoding in C#

My finally working approach is to try potential candidates of expected encodings by detecting invalid characters in the strings created from the byte array by the encodings. If I don't encounter invalid characters, I suppose the tested encoding works fine for the tested data.

For me, having only Latin and German special characters to consider, in order to determine the proper encoding for a byte array, I try to detect invalid characters in a string with this method:

    /// <summary>
    /// detect invalid characters in string, use to detect improper encoding
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool DetectInvalidChars(string s)
    {
        const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
        return s.Any(ch => !(
            specialChars.Contains(ch) ||
            (ch >= '0' && ch <= '9') ||
            (ch >= 'a' && ch <= 'z') ||
            (ch >= 'A' && ch <= 'Z')));
    }

(NB: if you have other Latin-based languages to consider, you might want to adapt the specialChars const string in the code)

Then I use it like this (I only expect UTF-8 or Default encoding):

        // determine encoding by detecting invalid characters in string
        var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
        if (StringFuncs.DetectInvalidChars(invoiceXmlText))
            invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default

check if directory exists and delete in one command unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

SQL Server JOIN missing NULL values

Try using ISNULL function:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 
INNER JOIN Table2
   ON Table1.Col1 = Table2.Col1 
   AND ISNULL(Table1.Col2, 'ZZZZ') = ISNULL(Table2.Col2,'ZZZZ')

Where 'ZZZZ' is some arbitrary value never in the table.

pass array to method Java

Simply remove the brackets from your original code.

PrintA(arryw);

private void PassArray(){
    String[] arrayw = new String[4];
    //populate array
    PrintA(arrayw);
}
private void PrintA(String[] a){
    //do whatever with array here
}

That is all.

Run PostgreSQL queries from the command line

I also noticed that the query

SELECT * FROM tablename;

gives an error on the psql command prompt and

SELECT * FROM "tablename";

runs fine, really strange, so don't forget the double quotes. I always liked databases :-(

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

How to display scroll bar onto a html table

The accepted answer provided a good starting point, but if you resize the frame, change the column widths, or even change the table data, the headers will get messed up in various ways. Every other example I've seen has similar issues, or imposes some serious restrictions on the table's layout.

I think I've finally got all these problems solved, though. It took a lot of CSS, but the final product is about as reliable and easy to use as a normal table.

Here's an example that has all the required features to replicate the table referenced by the OP: jsFiddle

The colors and borders would have to be changed to make it identical to the reference. Information on how to make those kinds of changes is provided in the CSS comments.

Here's the code:

_x000D_
_x000D_
/*the following html and body rule sets are required only if using a % width or height*/_x000D_
/*html {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}*/_x000D_
body {_x000D_
  box-sizing: border-box;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0 20px 0 20px;_x000D_
  text-align: center;_x000D_
  background: white;_x000D_
}_x000D_
.scrollingtable {_x000D_
  box-sizing: border-box;_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  overflow: hidden;_x000D_
  width: auto; /*if you want a fixed width, set it here, else set to auto*/_x000D_
  min-width: 0/*100%*/; /*if you want a % width, set it here, else set to 0*/_x000D_
  height: 188px/*100%*/; /*set table height here; can be fixed value or %*/_x000D_
  min-height: 0/*104px*/; /*if using % height, make this large enough to fit scrollbar arrows + caption + thead*/_x000D_
  font-family: Verdana, Tahoma, sans-serif;_x000D_
  font-size: 15px;_x000D_
  line-height: 20px;_x000D_
  padding: 20px 0 20px 0; /*need enough padding to make room for caption*/_x000D_
  text-align: left;_x000D_
}_x000D_
.scrollingtable * {box-sizing: border-box;}_x000D_
.scrollingtable > div {_x000D_
  position: relative;_x000D_
  border-top: 1px solid black;_x000D_
  height: 100%;_x000D_
  padding-top: 20px; /*this determines column header height*/_x000D_
}_x000D_
.scrollingtable > div:before {_x000D_
  top: 0;_x000D_
  background: cornflowerblue; /*header row background color*/_x000D_
}_x000D_
.scrollingtable > div:before,_x000D_
.scrollingtable > div > div:after {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
}_x000D_
.scrollingtable > div > div {_x000D_
  min-height: 0/*43px*/; /*if using % height, make this large enough to fit scrollbar arrows*/_x000D_
  max-height: 100%;_x000D_
  overflow: scroll/*auto*/; /*set to auto if using fixed or % width; else scroll*/_x000D_
  overflow-x: hidden;_x000D_
  border: 1px solid black; /*border around table body*/_x000D_
}_x000D_
.scrollingtable > div > div:after {background: white;} /*match page background color*/_x000D_
.scrollingtable > div > div > table {_x000D_
  width: 100%;_x000D_
  border-spacing: 0;_x000D_
  margin-top: -20px; /*inverse of column header height*/_x000D_
  /*margin-right: 17px;*/ /*uncomment if using % width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > caption {_x000D_
  position: absolute;_x000D_
  top: -20px; /*inverse of caption height*/_x000D_
  margin-top: -1px; /*inverse of border-width*/_x000D_
  width: 100%;_x000D_
  font-weight: bold;_x000D_
  text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > * > tr > * {padding: 0;}_x000D_
.scrollingtable > div > div > table > thead {_x000D_
  vertical-align: bottom;_x000D_
  white-space: nowrap;_x000D_
  text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div {_x000D_
  display: inline-block;_x000D_
  padding: 0 6px 0 6px; /*header cell padding*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > :first-child:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 20px; /*match column header height*/_x000D_
  border-left: 1px solid black; /*leftmost header border*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div > div:first-child,_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  white-space: pre-wrap;_x000D_
  color: white; /*header row font color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:after {content: attr(label);}_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  min-height: 20px; /*match column header height*/_x000D_
  padding-top: 1px;_x000D_
  border-left: 1px solid black; /*borders between header cells*/_x000D_
}_x000D_
.scrollingtable .scrollbarhead {float: right;}_x000D_
.scrollingtable .scrollbarhead:before {_x000D_
  position: absolute;_x000D_
  width: 100px;_x000D_
  top: -1px; /*inverse border-width*/_x000D_
  background: white; /*match page background color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody > tr:after {_x000D_
  content: "";_x000D_
  display: table-cell;_x000D_
  position: relative;_x000D_
  padding: 0;_x000D_
  border-top: 1px solid black;_x000D_
  top: -1px; /*inverse of border width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody {vertical-align: top;}_x000D_
.scrollingtable > div > div > table > tbody > tr {background: white;}_x000D_
.scrollingtable > div > div > table > tbody > tr > * {_x000D_
  border-bottom: 1px solid black;_x000D_
  padding: 0 6px 0 6px;_x000D_
  height: 20px; /*match column header height*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody:last-of-type > tr:last-child > * {border-bottom: none;}_x000D_
.scrollingtable > div > div > table > tbody > tr:nth-child(even) {background: gainsboro;} /*alternate row color*/_x000D_
.scrollingtable > div > div > table > tbody > tr > * + * {border-left: 1px solid black;} /*borders between body cells*/
_x000D_
<div class="scrollingtable">_x000D_
  <div>_x000D_
    <div>_x000D_
      <table>_x000D_
        <caption>Top Caption</caption>_x000D_
        <thead>_x000D_
          <tr>_x000D_
            <th><div label="Column 1"></div></th>_x000D_
            <th><div label="Column 2"></div></th>_x000D_
            <th><div label="Column 3"></div></th>_x000D_
            <th>_x000D_
              <!--more versatile way of doing column label; requires 2 identical copies of label-->_x000D_
              <div><div>Column 4</div><div>Column 4</div></div>_x000D_
            </th>_x000D_
            <th class="scrollbarhead"/> <!--ALWAYS ADD THIS EXTRA CELL AT END OF HEADER ROW-->_x000D_
          </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
        </tbody>_x000D_
      </table>_x000D_
    </div>_x000D_
    Faux bottom caption_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<!--[if lte IE 9]><style>.scrollingtable > div > div > table {margin-right: 17px;}</style><![endif]-->
_x000D_
_x000D_
_x000D_

curl_exec() always returns false

This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

It took me a couple hours to finally understand the diference in the characters bellow:

https://www.e-example.com/api
https://www.e-example.com/api

Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

Hope this helps someone.

How to add external JS scripts to VueJS Components

Simplest solution is to add the script in the index.html file of your vue-project

index.html:

 <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>vue-webpack</title>
      </head>
      <body>
        <div id="app"></div>
        <!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
    0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(" ");
    for(h=0;h<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
    MIXPANEL_CUSTOM_LIB_URL:"file:"===c.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
    mixpanel.init("xyz");</script><!-- end Mixpanel -->
        <script src="/dist/build.js"></script>
      </body>
    </html>

Set folder browser dialog start location

Just set the SelectedPath property before calling ShowDialog.

fdbLocation.SelectedPath = myFolder;

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

Assign keyboard shortcut to run procedure

Write a vba proc like:

Sub E_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
    Range("AG" & (ActiveCell.Row)).Select 'go to column AG in the same row
End Sub

then go to developer tab, macros, select the macro, click options, then add a shortcut letter or button.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

How to download a file with Node.js (without using third-party libraries)?

const download = (url, path) => new Promise((resolve, reject) => {
http.get(url, response => {
    const statusCode = response.statusCode;

    if (statusCode !== 200) {
        return reject('Download error!');
    }

    const writeStream = fs.createWriteStream(path);
    response.pipe(writeStream);

    writeStream.on('error', () => reject('Error writing to file!'));
    writeStream.on('finish', () => writeStream.close(resolve));
});}).catch(err => console.error(err));

How do I add a new class to an element dynamically?

This is how you do it:

var e = document.getElementById('myIdName');
var value = window.getComputedStyle(e, null).getPropertyValue("zIndex");
alert('z-index: ' + value);

BackgroundWorker vs background Thread

What's perplexing to me is that the visual studio designer only allows you to use BackgroundWorkers and Timers that don't actually work with the service project.

It gives you neat drag and drop controls onto your service but... don't even try deploying it. Won't work.

Services: Only use System.Timers.Timer System.Windows.Forms.Timer won't work even though it's available in the toolbox

Services: BackgroundWorkers will not work when it's running as a service Use System.Threading.ThreadPools instead or Async calls

Display label text with line breaks in c#

Following line worked for me:

lbTabRes.Text += num + " x " + i + " = " + (num * i).ToString() + "<br/> \n";

Windows equivalent of the 'tail' command

I have not tried extracting a range, but I was able to get a line using the following DOS command:

find /N " " *.log|find "[6]" 

Since most files contain spaces, this command pulls every line from all LOG files and basically numbers them starting from 1 for each file. The numbered results are then piped into the second FIND command which looks for the line tagged as number 6.

Erasing elements from a vector

Calling erase will invalidate iterators, you could use:

void erase(std::vector<int>& myNumbers_in, int number_in)
{
    std::vector<int>::iterator iter = myNumbers_in.begin();
    while (iter != myNumbers_in.end())
    {
        if (*iter == number_in)
        {
            iter = myNumbers_in.erase(iter);
        }
        else
        {
           ++iter;
        }
    }

}

Or you could use std::remove_if together with a functor and std::vector::erase:

struct Eraser
{
    Eraser(int number_in) : number_in(number_in) {}
    int number_in;
    bool operator()(int i) const
    {
        return i == number_in;
    }
};

std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());

Instead of writing your own functor in this case you could use std::remove:

std::vector<int> myNumbers;
myNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());

In C++11 you could use a lambda instead of a functor:

std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());

In C++17 std::experimental::erase and std::experimental::erase_if are also available, in C++20 these are (finally) renamed to std::erase and std::erase_if (note: in Visual Studio 2019 you'll need to change your C++ language version to the latest experimental version for support):

std::vector<int> myNumbers;
std::erase_if(myNumbers, Eraser(number_in)); // or use lambda

or:

std::vector<int> myNumbers;
std::erase(myNumbers, number_in);

Start and stop a timer PHP

As alternative, php has a built-in timer controller: new EvTimer().

It can be used to make a task scheduler, with proper handling of special cases.

This is not only the Time, but a time transport layer, a chronometer, a lap counter, just as a stopwatch but with php callbacks ;)

EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.

The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year, it will still time out after(roughly) one hour.

The callback is guaranteed to be invoked only after its timeout has passed (...). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values.

The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.

The first two parameters allows to controls the time delay before execution, and the number of iterations.

The third parameter is a callback function, called at each iteration.

after

    Configures the timer to trigger after after seconds.

repeat

    If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
    If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

https://www.php.net/manual/en/class.evtimer.php

https://www.php.net/manual/en/evtimer.construct.php

$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

We can of course easily create this with basic looping and some tempo with sleep(), usleep(), or hrtime(), but new EvTimer() allows cleans and organized multiples calls, while handling special cases like overlapping.

Take the content of a list and append it to another list

Take a look at itertools.chain for a fast way to treat many small lists as a single big list (or at least as a single big iterable) without copying the smaller lists:

>>> import itertools
>>> p = ['a', 'b', 'c']
>>> q = ['d', 'e', 'f']
>>> r = ['g', 'h', 'i']
>>> for x in itertools.chain(p, q, r):
        print x.upper()

WCF on IIS8; *.svc handler mapping doesn't work

We managed to solve the error under Windows Server 2012 by:

  1. Removing from "Remove Roles and Features Wizard" .NET Framework 4.5 Features/ASP.NET 4.5 and all its dependent features
  2. Re-installing the removed features.

It seems the order of installation is the cause.

Also, make sure you have HTTP Activation installed under WCF Services.

How to empty a list in C#?

Option #1: Use Clear() function to empty the List<T> and retain it's capacity.

  • Count is set to 0, and references to other objects from elements of the collection are also released.

  • Capacity remains unchanged.

Option #2 - Use Clear() and TrimExcess() functions to set List<T> to initial state.

  • Count is set to 0, and references to other objects from elements of the collection are also released.

  • Trimming an empty List<T> sets the capacity of the List to the default capacity.

Definitions

Count = number of elements that are actually in the List<T>

Capacity = total number of elements the internal data structure can hold without resizing.

Clear() Only

List<string> dinosaurs = new List<string>();    
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);

Clear() and TrimExcess()

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Triceratops");
dinosaurs.Add("Stegosaurus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
dinosaurs.TrimExcess();
Console.WriteLine("\nClear() and TrimExcess()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);

Searching for UUIDs in text with regex

Wanted to give my contribution, as my regex cover all cases from OP and correctly group all relevant data on the group method (you don't need to post process the string to get each part of the uuid, this regex already get it for you)

([\d\w]{8})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{12})|[{0x]*([\d\w]{8})[0x, ]{4}([\d\w]{4})[0x, ]{4}([\d\w]{4})[0x, {]{5}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

Is PowerShell ready to replace my Cygwin shell on Windows?

You can also try running Bash scripts on Windows using BashWin at https://github.com/skanga/BashWin.

When do items in HTML5 local storage expire?

@sebarmeli's approach is the best in my opinion, but if you only want data to persist for the life of a session then sessionStorage is probably a better option:

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

MDN: sessionStorage

How do I rename a local Git branch?

git branch -m [old-branch] [new-branch]

-m means move all from [old-branch] to [new-branch] and remember you can use -M for other file systems.

How to import functions from different js file in a Vue+webpack+vue-loader project

After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?

BUT there was an import that was screwing the rest of it up:

Use require in .vue files

<script>
  var mylib = require('./mylib');
  export default {
  ....

Exports in mylib

 exports.myfunc = () => {....}

Avoid import

The actual issue in my case (which I didn't think was relevant!) was that mylib.js was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack but anyway I had:

import models from './model/models'
import axios from 'axios'

This works so long as I'm not using mylib in a .vue component. However as soon as I use mylib there, the error described in this issue arises.

I changed to:

let models = require('./model/models');
let axios = require('axios');

And all works as expected.

Copy and Paste a set range in the next empty row

Below is the code that works well but my values overlap in sheet "Final" everytime the condition of <=11 meets in sheet "Calculator"

I would like you to kindly support me to modify the code so that the cursor should move to next blank cell and values keeps on adding up like a list.

Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Calculator")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Final")

For i = 2 To ws1.Range("A65536").End(xlUp).Row

    If ws1.Cells(i, 4) <= 11 Then

        ws2.Cells(i, 1).Value = Left(Worksheets("Calculator").Cells(i, 1).Value, Len(Worksheets("Calculator").Cells(i, 1).Value) - 0)
        ws2.Cells(i, 2) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:D"), 4, False)
        ws2.Cells(i, 3) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:E"), 5, False)
        ws2.Cells(i, 4) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:B"), 2, False)
        ws2.Cells(i, 5) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:C"), 3, False)

    End If
Next i