Programs & Examples On #Domain mapping

How can I get file extensions with JavaScript?

Simple way to get filename even multiple dot in name

var filename = "my.filehere.txt";

file_name =  filename.replace('.'+filename.split('.').pop(),'');

console.log("Filename =>"+file_name);

OutPut : my.filehere

extension = filename.split('.').pop();
console.log("Extension =>"+extension);

OutPut : txt

Try this is one line code

What is the best way to left align and right align two div tags?

You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.

<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>

<style>
.div_r{
float:right;
color:red;
}
</style>

Get the element triggering an onclick event in jquery?

Try this

<input onclick="confirmSubmit(event);" type="button" value="Send" />

Along with this

function confirmSubmit(event){
            var domElement =$(event.target);
            console.log(domElement.attr('type'));
        }

I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.

Fastest way to reset every value of std::vector<int> to 0

I had the same question but about rather short vector<bool> (afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):

            -O0       -O3
         --------  --------
memset     0.666     1.045
fill      19.357     1.066
iterator  67.368     1.043
assign    17.975     0.530
for i     22.610     1.004

So apparently for these sizes, vector<bool>::assign() is faster. The code used for tests:

#include <vector>
#include <cstring>
#include <cstdlib>

#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;

using namespace std;

int main(int argc, char** argv) {

    std::vector<int> v(TEST_ARRAY_SIZE, 0);

    for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
        memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
        std::fill(v.begin(), v.end(), false);
   #elif TEST_METHOD == 3
        for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
            *it = 0;
        }
   #elif TEST_METHOD == 4
      v.assign(v.size(),false);
   #elif TEST_METHOD == 5
      for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
          v[i] = false;
      }
#endif
    }

    return EXIT_SUCCESS;
}

I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:

g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp

Check if a string is a valid date using DateTime.TryParse

If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse

DateTime.TryParse

This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored.

If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                        "5/1/2009 6:32:00", "05/01/2009 06:32", 
                        "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
DateTime dateValue;

foreach (string dateString in dateStrings)
{
   if (DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
      Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
   else
      Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
// The example displays the following output: 
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM. 
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.

Java JTextField with input hint

Here is a simple way that looks good in any L&F:

public class HintTextField extends JTextField {
    public HintTextField(String hint) {
        _hint = hint;
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (getText().length() == 0) {
            int h = getHeight();
            ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Insets ins = getInsets();
            FontMetrics fm = g.getFontMetrics();
            int c0 = getBackground().getRGB();
            int c1 = getForeground().getRGB();
            int m = 0xfefefefe;
            int c2 = ((c0 & m) >>> 1) + ((c1 & m) >>> 1);
            g.setColor(new Color(c2, true));
            g.drawString(_hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);
        }
    }
    private final String _hint;
}

strange error in my Animation Drawable

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

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

nginx error connect to php5-fpm.sock failed (13: Permission denied)

In my case php-fpm wasn't running at all, so I just had to start the service

service php7.3-fpm start
#on ubuntu 18.04

How to Scroll Down - JQuery

$('.btnMedio').click(function(event) {
    // Preventing default action of the event
    event.preventDefault();
    // Getting the height of the document
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, 50);
//                                       |    |
//                                       |    --- duration (milliseconds) 
//                                       ---- distance from the top
});

How to increase timeout for a single test case in mocha

For test navegation on Express:

const request = require('supertest');
const server = require('../bin/www');

describe('navegation', () => {
    it('login page', function(done) {
        this.timeout(4000);
        const timeOut = setTimeout(done, 3500);

        request(server)
            .get('/login')
            .expect(200)
            .then(res => {
                res.text.should.include('Login');
                clearTimeout(timeOut);
                done();
            })
            .catch(err => {
                console.log(this.test.fullTitle(), err);
                clearTimeout(timeOut);
                done(err);
            });
    });
});

In the example the test time is 4000 (4s).

Note: setTimeout(done, 3500) is minor for than done is called within the time of the test but clearTimeout(timeOut) it avoid than used all these time.

Get List of connected USB Devices

To see the devices I was interested in, I had replace Win32_USBHub by Win32_PnPEntity in Adel Hazzah's code, based on this post. This works for me:

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management; // need to add System.Management to your project references.

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      ManagementObjectCollection collection;
      using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        collection = searcher.Get();      

      foreach (var device in collection)
      {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID"),
        (string)device.GetPropertyValue("PNPDeviceID"),
        (string)device.GetPropertyValue("Description")
        ));
      }

      collection.Dispose();
      return devices;
    }
  }

  class USBDeviceInfo
  {
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
    {
      this.DeviceID = deviceID;
      this.PnpDeviceID = pnpDeviceID;
      this.Description = description;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
  }
}

Find an item in List by LINQ?

Do you want the item in the list or the actual item itself (would assume the item itself).

Here are a bunch of options for you:

string result = _list.First(s => s == search);

string result = (from s in _list
                 where s == search
                 select s).Single();

string result = _list.Find(search);

int result = _list.IndexOf(search);

How to use moment.js library in angular 2 typescript app?

The following worked for me.

First, install the type definitions for moment.

typings install moment --save

(Note: NOT --ambient)

Then, to work around the lack of a proper export:

import * as moment from 'moment';

return, return None, and no return at all?

On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.

Using return None

This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.

We've got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function.

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.

Using no return at all

This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

In the following example, we set person's mother's name and then the function exits after completing successfully.

def set_mother(person, mother):
    if is_human(person):
        person.mother = mother

Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.

How can I stop a While loop?

just indent your code correctly:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:   
            return period

You need to understand that the break statement in your example will exit the infinite loop you've created with while True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break statement by a return statement.

Following your idea to use an infinite loop, this is the best way to write it:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period

Properties file with a list as the value for an individual key

There's probably a another way or better. But this is how I do this in Spring Boot.

My property file contains the following lines. "," is the delimiter in each line.

mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;

My server config

@Configuration
public class ServerConfig {

    @Inject
    private Environment env;

    @Bean
    public MMLProperties mmlProperties() {
        MMLProperties properties = new MMLProperties();
        properties.setMmmlPots(env.getProperty("mml.pots"));
        properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
        properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
        return properties;
    }
}

MMLProperties class.

public class MMLProperties {
    private String mmlPots;
    private String mmlIsdnGrunntengingar;
    private String mmlIsdnStofntengingar;

    public MMLProperties() {
        super();
    }

    public void setMmmlPots(String mmlPots) {
        this.mmlPots = mmlPots;
    }

    public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
        this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
    }

    public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
        this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
    }

    // These three public getXXX functions then take care of spliting the properties into List
    public List<String> getMmmlCommandForPotsAsList() {
        return getPropertieAsList(mmlPots);
    }

    public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
        return getPropertieAsList(mmlIsdnGrunntengingar);
    }

    public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
        return getPropertieAsList(mmlIsdnStofntengingar);
    }

    private List<String> getPropertieAsList(String propertie) {
        return ((propertie != null) || (propertie.length() > 0))
        ? Arrays.asList(propertie.split("\\s*,\\s*"))
        : Collections.emptyList();
    }
}

Then in my Runner class I Autowire MMLProperties

@Component
public class Runner implements CommandLineRunner {

    @Autowired
    MMLProperties mmlProperties;

    @Override
    public void run(String... arg0) throws Exception {
        // Now I can call my getXXX function to retrieve the properties as List
        for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
            System.out.println(command);
        }
    }
}

Hope this helps

Android: Storing username and password?

With the new (Android 6.0) fingerprint hardware and API you can do it as in this github sample application.

What is the purpose of the HTML "no-js" class?

The no-js class is used to style a webpage, dependent on whether the user has JS disabled or enabled in the browser.

As per the Modernizr docs:

no-js

By default, Modernizr will rewrite <html class="no-js"> to <html class="js">. This lets hide certain elements that should only be exposed in environments that execute JavaScript. If you want to disable this change, you can set enableJSClass to false in your config.

How do I add all new files to SVN

svn status | grep "^\?" | awk '{ printf("\""); for (f=2; f <= NF; f++) { printf("%s", $f); if (f<NF) printf(" "); } printf("\"\n");}' | xargs svn add

This was based on markb's answer... and a little hunting on the internet. It looks ugly, but it seems to work for me on OS X (including files with spaces).

Drop all tables whose names begin with a certain string

SELECT 'DROP TABLE "' + TABLE_NAME + '"' 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '[prefix]%'

This will generate a script.

Adding clause to check existence of table before deleting:

SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '[prefix]%'

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I will throw one more solution into the mix. I downloaded a sample app and it was crimping only on this taglib. Turns out it didn't care for the single quotes around the attributes.

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>

Once I changed those and made sure jstl.jar was in the web app, i was good to go.

ASP.NET MVC 404 Error Handling

What I can recomend is to look on FilterAttribute. For example MVC already has HandleErrorAttribute. You can customize it to handle only 404. Reply if you are interesed I will look example.

BTW

Solution(with last route) that you have accepted in previous question does not work in much of the situations. Second solution with HandleUnknownAction will work but require to make this change in each controller or to have single base controller.

My choice is a solution with HandleUnknownAction.

How do I retrieve the number of columns in a Pandas data frame?

In order to include the number of row index "columns" in your total shape I would personally add together the number of columns df.columns.size with the attribute pd.Index.nlevels/pd.MultiIndex.nlevels:

Set up dummy data

import pandas as pd

flat_index = pd.Index([0, 1, 2])
multi_index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), names=["letter", "id"])

columns = ["cat", "dog", "fish"]

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_df = pd.DataFrame(data, index=flat_index, columns=columns)
multi_df = pd.DataFrame(data, index=multi_index, columns=columns)

# Show data
# -----------------
# 3 columns, 4 including the index
print(flat_df)
    cat  dog  fish
id                
0     1    2     3
1     4    5     6
2     7    8     9

# -----------------
# 3 columns, 5 including the index
print(multi_df)
           cat  dog  fish
letter id                
a      1     1    2     3
       2     4    5     6
b      1     7    8     9

Writing our process as a function:

def total_ncols(df, include_index=False):
    ncols = df.columns.size
    if include_index is True:
        ncols += df.index.nlevels
    return ncols

print("Ignore the index:")
print(total_ncols(flat_df), total_ncols(multi_df))

print("Include the index:")
print(total_ncols(flat_df, include_index=True), total_ncols(multi_df, include_index=True))

This prints:

Ignore the index:
3 3

Include the index:
4 5

If you want to only include the number of indices if the index is a pd.MultiIndex, then you can throw in an isinstance check in the defined function.

As an alternative, you could use df.reset_index().columns.size to achieve the same result, but this won't be as performant since we're temporarily inserting new columns into the index and making a new index before getting the number of columns.

Prevent div from moving while resizing the page

hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body> in a fixed width <div style="margin: 0 auto; width: 900px> to achieve what you have done with the body {margin: 0 10% 0 10%}

Get webpage contents with Python?

Also you can use faster_than_requests package. That's very fast and simple:

import faster_than_requests as r
content = r.get2str("http://test.com/")

Look at this comparison:

enter image description here

jQuery remove selected option from this

 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

Using the find method.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

Instead of using json, you can do simple thing.

$.post("${pageContext.servletContext.contextPath}/Test",
                {
                "str1": "test one",
                "str2": "two test",

                        <other form data>
                },
                function(j)
                {
                        <j is the string you will return from the controller function.>
                });

Now in the controller you need to map the ajax request as below:

 @RequestMapping(value="/Test", method=RequestMethod.POST)
    @ResponseBody
    public String calculateTestData(@RequestParam("str1") String str1, @RequestParam("str2") String str2, HttpServletRequest request, HttpServletResponse response){
            <perform the task here and return the String result.>

            return "xyz";
}

Hope this helps you.

How to get name of calling function/method in PHP?

As of php 5.4 you can use

        $dbt=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
        $caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;

This will not waste memory as it ignores arguments and returns only the last 2 backtrace stack entries, and will not generate notices as other answers here.

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

How do I sort a dictionary by value?

UPDATE: 5 DECEMBER 2015 using Python 3.5

Whilst I found the accepted answer useful, I was also surprised that it hasn't been updated to reference OrderedDict from the standard library collections module as a viable, modern alternative - designed to solve exactly this type of problem.

from operator import itemgetter
from collections import OrderedDict

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = OrderedDict(sorted(x.items(), key=itemgetter(1)))
# OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])

The official OrderedDict documentation offers a very similar example too, but using a lambda for the sort function:

# regular unsorted dictionary
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

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

How do I read the contents of a Node.js stream into a string variable?

What about something like a stream reducer ?

Here is an example using ES6 classes how to use one.

var stream = require('stream')

class StreamReducer extends stream.Writable {
  constructor(chunkReducer, initialvalue, cb) {
    super();
    this.reducer = chunkReducer;
    this.accumulator = initialvalue;
    this.cb = cb;
  }
  _write(chunk, enc, next) {
    this.accumulator = this.reducer(this.accumulator, chunk);
    next();
  }
  end() {
    this.cb(null, this.accumulator)
  }
}

// just a test stream
class EmitterStream extends stream.Readable {
  constructor(chunks) {
    super();
    this.chunks = chunks;
  }
  _read() {
    this.chunks.forEach(function (chunk) { 
        this.push(chunk);
    }.bind(this));
    this.push(null);
  }
}

// just transform the strings into buffer as we would get from fs stream or http request stream
(new EmitterStream(
  ["hello ", "world !"]
  .map(function(str) {
     return Buffer.from(str, 'utf8');
  })
)).pipe(new StreamReducer(
  function (acc, v) {
    acc.push(v);
    return acc;
  },
  [],
  function(err, chunks) {
    console.log(Buffer.concat(chunks).toString('utf8'));
  })
);

Extract every nth element of a vector

To select every nth element from any starting position in the vector

nth_element <- function(vector, starting_position, n) { 
  vector[seq(starting_position, length(vector), n)] 
  }

# E.g.
vec <- 1:12

nth_element(vec, 1, 3)
# [1]  1  4  7 10

nth_element(vec, 2, 3)
# [1]  2  5  8 11

Create comma separated strings C#?

You could override your object's ToString() method:

public override string ToString ()
{
    return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}

Pure CSS to make font-size responsive based on dynamic amount of characters

For reference, a non-CSS solution:

Below is some JS that re-sizes a font depending on the text length within a container.

Codepen with slightly modified code, but same idea as below:

function scaleFontSize(element) {
    var container = document.getElementById(element);

    // Reset font-size to 100% to begin
    container.style.fontSize = "100%";

    // Check if the text is wider than its container,
    // if so then reduce font-size
    if (container.scrollWidth > container.clientWidth) {
        container.style.fontSize = "70%";
    }
}

For me, I call this function when a user makes a selection in a drop-down, and then a div in my menu gets populated (this is where I have dynamic text occurring).

    scaleFontSize("my_container_div");

In addition, I also use CSS ellipses ("...") to truncate yet even longer text too, like so:

#my_container_div {
    width: 200px; /* width required for text-overflow to work */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

So, ultimately:

  • Short text: e.g. "APPLES"

    Fully rendered, nice big letters.

  • Long text: e.g. "APPLES & ORANGES"

    Gets scaled down 70%, via the above JS scaling function.

  • Super long text: e.g. "APPLES & ORANGES & BANAN..."

    Gets scaled down 70% AND gets truncated with a "..." ellipses, via the above JS scaling function together with the CSS rule.

You could also explore playing with CSS letter-spacing to make text narrower while keeping the same font size.

What is a correct MIME type for .docx, .pptx, etc.?

Here is the (almost) complete file extensions's MIME in a JSON format. Just do example: MIME["ppt"], MIME["docx"], etc

{"x3d": "application/vnd.hzn-3d-crossword", "3gp": "video/3gpp", "3g2": "video/3gpp2", "mseq": "application/vnd.mseq", "pwn": "application/vnd.3m.post-it-notes", "plb": "application/vnd.3gpp.pic-bw-large", "psb": "application/vnd.3gpp.pic-bw-small", "pvb": "application/vnd.3gpp.pic-bw-var", "tcap": "application/vnd.3gpp2.tcap", "7z": "application/x-7z-compressed", "abw": "application/x-abiword", "ace": "application/x-ace-compressed", "acc": "application/vnd.americandynamics.acc", "acu": "application/vnd.acucobol", "atc": "application/vnd.acucorp", "adp": "audio/adpcm", "aab": "application/x-authorware-bin", "aam": "application/x-authorware-map", "aas": "application/x-authorware-seg", "air": "application/vnd.adobe.air-application-installer-package+zip", "swf": "application/x-shockwave-flash", "fxp": "application/vnd.adobe.fxp", "pdf": "application/pdf", "ppd": "application/vnd.cups-ppd", "dir": "application/x-director", "xdp": "application/vnd.adobe.xdp+xml", "xfdf": "application/vnd.adobe.xfdf", "aac": "audio/x-aac", "ahead": "application/vnd.ahead.space", "azf": "application/vnd.airzip.filesecure.azf", "azs": "application/vnd.airzip.filesecure.azs", "azw": "application/vnd.amazon.ebook", "ami": "application/vnd.amiga.ami", "N/A": "application/andrew-inset", "apk": "application/vnd.android.package-archive", "cii": "application/vnd.anser-web-certificate-issue-initiation", "fti": "application/vnd.anser-web-funds-transfer-initiation", "atx": "application/vnd.antix.game-component", "dmg": "application/x-apple-diskimage", "mpkg": "application/vnd.apple.installer+xml", "aw": "application/applixware", "mp3": "audio/mpeg", "les": "application/vnd.hhe.lesson-player", "swi": "application/vnd.aristanetworks.swi", "s": "text/x-asm", "atomcat": "application/atomcat+xml", "atomsvc": "application/atomsvc+xml", "atom, .xml": "application/atom+xml", "ac": "application/pkix-attr-cert", "aif": "audio/x-aiff", "avi": "video/x-msvideo", "aep": "application/vnd.audiograph", "dxf": "image/vnd.dxf", "dwf": "model/vnd.dwf", "par": "text/plain-bas", "bcpio": "application/x-bcpio", "bin": "application/octet-stream", "bmp": "image/bmp", "torrent": "application/x-bittorrent", "cod": "application/vnd.rim.cod", "mpm": "application/vnd.blueice.multipass", "bmi": "application/vnd.bmi", "sh": "application/x-sh", "btif": "image/prs.btif", "rep": "application/vnd.businessobjects", "bz": "application/x-bzip", "bz2": "application/x-bzip2", "csh": "application/x-csh", "c": "text/x-c", "cdxml": "application/vnd.chemdraw+xml", "css": "text/css", "cdx": "chemical/x-cdx", "cml": "chemical/x-cml", "csml": "chemical/x-csml", "cdbcmsg": "application/vnd.contact.cmsg", "cla": "application/vnd.claymore", "c4g": "application/vnd.clonk.c4group", "sub": "image/vnd.dvb.subtitle", "cdmia": "application/cdmi-capability", "cdmic": "application/cdmi-container", "cdmid": "application/cdmi-domain", "cdmio": "application/cdmi-object", "cdmiq": "application/cdmi-queue", "c11amc": "application/vnd.cluetrust.cartomobile-config", "c11amz": "application/vnd.cluetrust.cartomobile-config-pkg", "ras": "image/x-cmu-raster", "dae": "model/vnd.collada+xml", "csv": "text/csv", "cpt": "application/mac-compactpro", "wmlc": "application/vnd.wap.wmlc", "cgm": "image/cgm", "ice": "x-conference/x-cooltalk", "cmx": "image/x-cmx", "xar": "application/vnd.xara", "cmc": "application/vnd.cosmocaller", "cpio": "application/x-cpio", "clkx": "application/vnd.crick.clicker", "clkk": "application/vnd.crick.clicker.keyboard", "clkp": "application/vnd.crick.clicker.palette", "clkt": "application/vnd.crick.clicker.template", "clkw": "application/vnd.crick.clicker.wordbank", "wbs": "application/vnd.criticaltools.wbs+xml", "cryptonote": "application/vnd.rig.cryptonote", "cif": "chemical/x-cif", "cmdf": "chemical/x-cmdf", "cu": "application/cu-seeme", "cww": "application/prs.cww", "curl": "text/vnd.curl", "dcurl": "text/vnd.curl.dcurl", "mcurl": "text/vnd.curl.mcurl", "scurl": "text/vnd.curl.scurl", "car": "application/vnd.curl.car", "pcurl": "application/vnd.curl.pcurl", "cmp": "application/vnd.yellowriver-custom-menu", "dssc": "application/dssc+der", "xdssc": "application/dssc+xml", "deb": "application/x-debian-package", "uva": "audio/vnd.dece.audio", "uvi": "image/vnd.dece.graphic", "uvh": "video/vnd.dece.hd", "uvm": "video/vnd.dece.mobile", "uvu": "video/vnd.uvvu.mp4", "uvp": "video/vnd.dece.pd", "uvs": "video/vnd.dece.sd", "uvv": "video/vnd.dece.video", "dvi": "application/x-dvi", "seed": "application/vnd.fdsn.seed", "dtb": "application/x-dtbook+xml", "res": "application/x-dtbresource+xml", "ait": "application/vnd.dvb.ait", "svc": "application/vnd.dvb.service", "eol": "audio/vnd.digital-winds", "djvu": "image/vnd.djvu", "dtd": "application/xml-dtd", "mlp": "application/vnd.dolby.mlp", "wad": "application/x-doom", "dpg": "application/vnd.dpgraph", "dra": "audio/vnd.dra", "dfac": "application/vnd.dreamfactory", "dts": "audio/vnd.dts", "dtshd": "audio/vnd.dts.hd", "dwg": "image/vnd.dwg", "geo": "application/vnd.dynageo", "es": "application/ecmascript", "mag": "application/vnd.ecowin.chart", "mmr": "image/vnd.fujixerox.edmics-mmr", "rlc": "image/vnd.fujixerox.edmics-rlc", "exi": "application/exi", "mgz": "application/vnd.proteus.magazine", "epub": "application/epub+zip", "eml": "message/rfc822", "nml": "application/vnd.enliven", "xpr": "application/vnd.is-xpr", "xif": "image/vnd.xiff", "xfdl": "application/vnd.xfdl", "emma": "application/emma+xml", "ez2": "application/vnd.ezpix-album", "ez3": "application/vnd.ezpix-package", "fst": "image/vnd.fst", "fvt": "video/vnd.fvt", "fbs": "image/vnd.fastbidsheet", "fe_launch": "application/vnd.denovo.fcselayout-link", "f4v": "video/x-f4v", "flv": "video/x-flv", "fpx": "image/vnd.fpx", "npx": "image/vnd.net-fpx", "flx": "text/vnd.fmi.flexstor", "fli": "video/x-fli", "ftc": "application/vnd.fluxtime.clip", "fdf": "application/vnd.fdf", "f": "text/x-fortran", "mif": "application/vnd.mif", "fm": "application/vnd.framemaker", "fh": "image/x-freehand", "fsc": "application/vnd.fsc.weblaunch", "fnc": "application/vnd.frogans.fnc", "ltf": "application/vnd.frogans.ltf", "ddd": "application/vnd.fujixerox.ddd", "xdw": "application/vnd.fujixerox.docuworks", "xbd": "application/vnd.fujixerox.docuworks.binder", "oas": "application/vnd.fujitsu.oasys", "oa2": "application/vnd.fujitsu.oasys2", "oa3": "application/vnd.fujitsu.oasys3", "fg5": "application/vnd.fujitsu.oasysgp", "bh2": "application/vnd.fujitsu.oasysprs", "spl": "application/x-futuresplash", "fzs": "application/vnd.fuzzysheet", "g3": "image/g3fax", "gmx": "application/vnd.gmx", "gtw": "model/vnd.gtw", "txd": "application/vnd.genomatix.tuxedo", "ggb": "application/vnd.geogebra.file", "ggt": "application/vnd.geogebra.tool", "gdl": "model/vnd.gdl", "gex": "application/vnd.geometry-explorer", "gxt": "application/vnd.geonext", "g2w": "application/vnd.geoplan", "g3w": "application/vnd.geospace", "gsf": "application/x-font-ghostscript", "bdf": "application/x-font-bdf", "gtar": "application/x-gtar", "texinfo": "application/x-texinfo", "gnumeric": "application/x-gnumeric", "kml": "application/vnd.google-earth.kml+xml", "kmz": "application/vnd.google-earth.kmz", "gqf": "application/vnd.grafeq", "gif": "image/gif", "gv": "text/vnd.graphviz", "gac": "application/vnd.groove-account", "ghf": "application/vnd.groove-help", "gim": "application/vnd.groove-identity-message", "grv": "application/vnd.groove-injector", "gtm": "application/vnd.groove-tool-message", "tpl": "application/vnd.groove-tool-template", "vcg": "application/vnd.groove-vcard", "h261": "video/h261", "h263": "video/h263", "h264": "video/h264", "hpid": "application/vnd.hp-hpid", "hps": "application/vnd.hp-hps", "hdf": "application/x-hdf", "rip": "audio/vnd.rip", "hbci": "application/vnd.hbci", "jlt": "application/vnd.hp-jlyt", "pcl": "application/vnd.hp-pcl", "hpgl": "application/vnd.hp-hpgl", "hvs": "application/vnd.yamaha.hv-script", "hvd": "application/vnd.yamaha.hv-dic", "hvp": "application/vnd.yamaha.hv-voice", "sfd-hdstx": "application/vnd.hydrostatix.sof-data", "stk": "application/hyperstudio", "hal": "application/vnd.hal+xml", "html": "text/html", "irm": "application/vnd.ibm.rights-management", "sc": "application/vnd.ibm.secure-container", "ics": "text/calendar", "icc": "application/vnd.iccprofile", "ico": "image/x-icon", "igl": "application/vnd.igloader", "ief": "image/ief", "ivp": "application/vnd.immervision-ivp", "ivu": "application/vnd.immervision-ivu", "rif": "application/reginfo+xml", "3dml": "text/vnd.in3d.3dml", "spot": "text/vnd.in3d.spot", "igs": "model/iges", "i2g": "application/vnd.intergeo", "cdy": "application/vnd.cinderella", "xpw": "application/vnd.intercon.formnet", "fcs": "application/vnd.isac.fcs", "ipfix": "application/ipfix", "cer": "application/pkix-cert", "pki": "application/pkixcmp", "crl": "application/pkix-crl", "pkipath": "application/pkix-pkipath", "igm": "application/vnd.insors.igm", "rcprofile": "application/vnd.ipunplugged.rcprofile", "irp": "application/vnd.irepository.package+xml", "jad": "text/vnd.sun.j2me.app-descriptor", "jar": "application/java-archive", "class": "application/java-vm", "jnlp": "application/x-java-jnlp-file", "ser": "application/java-serialized-object", "java": "text/x-java-source,java", "js": "application/javascript", "json": "application/json", "joda": "application/vnd.joost.joda-archive", "jpm": "video/jpm", "jpeg, .jpg": "image/x-citrix-jpeg", "pjpeg": "image/pjpeg", "jpgv": "video/jpeg", "ktz": "application/vnd.kahootz", "mmd": "application/vnd.chipnuts.karaoke-mmd", "karbon": "application/vnd.kde.karbon", "chrt": "application/vnd.kde.kchart", "kfo": "application/vnd.kde.kformula", "flw": "application/vnd.kde.kivio", "kon": "application/vnd.kde.kontour", "kpr": "application/vnd.kde.kpresenter", "ksp": "application/vnd.kde.kspread", "kwd": "application/vnd.kde.kword", "htke": "application/vnd.kenameaapp", "kia": "application/vnd.kidspiration", "kne": "application/vnd.kinar", "sse": "application/vnd.kodak-descriptor", "lasxml": "application/vnd.las.las+xml", "latex": "application/x-latex", "lbd": "application/vnd.llamagraphics.life-balance.desktop", "lbe": "application/vnd.llamagraphics.life-balance.exchange+xml", "jam": "application/vnd.jam", "123": "application/vnd.lotus-1-2-3", "apr": "application/vnd.lotus-approach", "pre": "application/vnd.lotus-freelance", "nsf": "application/vnd.lotus-notes", "org": "application/vnd.lotus-organizer", "scm": "application/vnd.lotus-screencam", "lwp": "application/vnd.lotus-wordpro", "lvp": "audio/vnd.lucent.voice", "m3u": "audio/x-mpegurl", "m4v": "video/x-m4v", "hqx": "application/mac-binhex40", "portpkg": "application/vnd.macports.portpkg", "mgp": "application/vnd.osgeo.mapguide.package", "mrc": "application/marc", "mrcx": "application/marcxml+xml", "mxf": "application/mxf", "nbp": "application/vnd.wolfram.player", "ma": "application/mathematica", "mathml": "application/mathml+xml", "mbox": "application/mbox", "mc1": "application/vnd.medcalcdata", "mscml": "application/mediaservercontrol+xml", "cdkey": "application/vnd.mediastation.cdkey", "mwf": "application/vnd.mfer", "mfm": "application/vnd.mfmp", "msh": "model/mesh", "mads": "application/mads+xml", "mets": "application/mets+xml", "mods": "application/mods+xml", "meta4": "application/metalink4+xml", "mcd": "application/vnd.mcd", "flo": "application/vnd.micrografx.flo", "igx": "application/vnd.micrografx.igx", "es3": "application/vnd.eszigno3+xml", "mdb": "application/x-msaccess", "asf": "video/x-ms-asf", "exe": "application/x-msdownload", "cil": "application/vnd.ms-artgalry", "cab": "application/vnd.ms-cab-compressed", "ims": "application/vnd.ms-ims", "application": "application/x-ms-application", "clp": "application/x-msclip", "mdi": "image/vnd.ms-modi", "eot": "application/vnd.ms-fontobject", "xls": "application/vnd.ms-excel", "xlam": "application/vnd.ms-excel.addin.macroenabled.12", "xlsb": "application/vnd.ms-excel.sheet.binary.macroenabled.12", "xltm": "application/vnd.ms-excel.template.macroenabled.12", "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12", "chm": "application/vnd.ms-htmlhelp", "crd": "application/x-mscardfile", "lrm": "application/vnd.ms-lrm", "mvb": "application/x-msmediaview", "mny": "application/x-msmoney", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", "ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", "potx": "application/vnd.openxmlformats-officedocument.presentationml.template", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "obd": "application/x-msbinder", "thmx": "application/vnd.ms-officetheme", "onetoc": "application/onenote", "pya": "audio/vnd.ms-playready.media.pya", "pyv": "video/vnd.ms-playready.media.pyv", "ppt": "application/vnd.ms-powerpoint", "ppam": "application/vnd.ms-powerpoint.addin.macroenabled.12", "sldm": "application/vnd.ms-powerpoint.slide.macroenabled.12", "pptm": "application/vnd.ms-powerpoint.presentation.macroenabled.12", "ppsm": "application/vnd.ms-powerpoint.slideshow.macroenabled.12", "potm": "application/vnd.ms-powerpoint.template.macroenabled.12", "mpp": "application/vnd.ms-project", "pub": "application/x-mspublisher", "scd": "application/x-msschedule", "xap": "application/x-silverlight-app", "stl": "application/vnd.ms-pki.stl", "cat": "application/vnd.ms-pki.seccat", "vsd": "application/vnd.visio", "vsdx": "application/vnd.visio2013", "wm": "video/x-ms-wm", "wma": "audio/x-ms-wma", "wax": "audio/x-ms-wax", "wmx": "video/x-ms-wmx", "wmd": "application/x-ms-wmd", "wpl": "application/vnd.ms-wpl", "wmz": "application/x-ms-wmz", "wmv": "video/x-ms-wmv", "wvx": "video/x-ms-wvx", "wmf": "application/x-msmetafile", "trm": "application/x-msterminal", "doc": "application/msword", "docm": "application/vnd.ms-word.document.macroenabled.12", "dotm": "application/vnd.ms-word.template.macroenabled.12", "wri": "application/x-mswrite", "wps": "application/vnd.ms-works", "xbap": "application/x-ms-xbap", "xps": "application/vnd.ms-xpsdocument", "mid": "audio/midi", "mpy": "application/vnd.ibm.minipay", "afp": "application/vnd.ibm.modcap", "rms": "application/vnd.jcp.javame.midlet-rms", "tmo": "application/vnd.tmobile-livetv", "prc": "application/x-mobipocket-ebook", "mbk": "application/vnd.mobius.mbk", "dis": "application/vnd.mobius.dis", "plc": "application/vnd.mobius.plc", "mqy": "application/vnd.mobius.mqy", "msl": "application/vnd.mobius.msl", "txf": "application/vnd.mobius.txf", "daf": "application/vnd.mobius.daf", "fly": "text/vnd.fly", "mpc": "application/vnd.mophun.certificate", "mpn": "application/vnd.mophun.application", "mj2": "video/mj2", "mpga": "audio/mpeg", "mxu": "video/vnd.mpegurl", "mpeg": "video/mpeg", "m21": "application/mp21", "mp4a": "audio/mp4", "mp4": "application/mp4", "m3u8": "application/vnd.apple.mpegurl", "mus": "application/vnd.musician", "msty": "application/vnd.muvee.style", "mxml": "application/xv+xml", "ngdat": "application/vnd.nokia.n-gage.data", "n-gage": "application/vnd.nokia.n-gage.symbian.install", "ncx": "application/x-dtbncx+xml", "nc": "application/x-netcdf", "nlu": "application/vnd.neurolanguage.nlu", "dna": "application/vnd.dna", "nnd": "application/vnd.noblenet-directory", "nns": "application/vnd.noblenet-sealer", "nnw": "application/vnd.noblenet-web", "rpst": "application/vnd.nokia.radio-preset", "rpss": "application/vnd.nokia.radio-presets", "n3": "text/n3", "edm": "application/vnd.novadigm.edm", "edx": "application/vnd.novadigm.edx", "ext": "application/vnd.novadigm.ext", "gph": "application/vnd.flographit", "ecelp4800": "audio/vnd.nuera.ecelp4800", "ecelp7470": "audio/vnd.nuera.ecelp7470", "ecelp9600": "audio/vnd.nuera.ecelp9600", "oda": "application/oda", "ogx": "application/ogg", "oga": "audio/ogg", "ogv": "video/ogg", "dd2": "application/vnd.oma.dd2+xml", "oth": "application/vnd.oasis.opendocument.text-web", "opf": "application/oebps-package+xml", "qbo": "application/vnd.intu.qbo", "oxt": "application/vnd.openofficeorg.extension", "osf": "application/vnd.yamaha.openscoreformat", "weba": "audio/webm", "webm": "video/webm", "odc": "application/vnd.oasis.opendocument.chart", "otc": "application/vnd.oasis.opendocument.chart-template", "odb": "application/vnd.oasis.opendocument.database", "odf": "application/vnd.oasis.opendocument.formula", "odft": "application/vnd.oasis.opendocument.formula-template", "odg": "application/vnd.oasis.opendocument.graphics", "otg": "application/vnd.oasis.opendocument.graphics-template", "odi": "application/vnd.oasis.opendocument.image", "oti": "application/vnd.oasis.opendocument.image-template", "odp": "application/vnd.oasis.opendocument.presentation", "otp": "application/vnd.oasis.opendocument.presentation-template", "ods": "application/vnd.oasis.opendocument.spreadsheet", "ots": "application/vnd.oasis.opendocument.spreadsheet-template", "odt": "application/vnd.oasis.opendocument.text", "odm": "application/vnd.oasis.opendocument.text-master", "ott": "application/vnd.oasis.opendocument.text-template", "ktx": "image/ktx", "sxc": "application/vnd.sun.xml.calc", "stc": "application/vnd.sun.xml.calc.template", "sxd": "application/vnd.sun.xml.draw", "std": "application/vnd.sun.xml.draw.template", "sxi": "application/vnd.sun.xml.impress", "sti": "application/vnd.sun.xml.impress.template", "sxm": "application/vnd.sun.xml.math", "sxw": "application/vnd.sun.xml.writer", "sxg": "application/vnd.sun.xml.writer.global", "stw": "application/vnd.sun.xml.writer.template", "otf": "application/x-font-otf", "osfpvg": "application/vnd.yamaha.openscoreformat.osfpvg+xml", "dp": "application/vnd.osgi.dp", "pdb": "application/vnd.palm", "p": "text/x-pascal", "paw": "application/vnd.pawaafile", "pclxl": "application/vnd.hp-pclxl", "efif": "application/vnd.picsel", "pcx": "image/x-pcx", "psd": "image/vnd.adobe.photoshop", "prf": "application/pics-rules", "pic": "image/x-pict", "chat": "application/x-chat", "p10": "application/pkcs10", "p12": "application/x-pkcs12", "p7m": "application/pkcs7-mime", "p7s": "application/pkcs7-signature", "p7r": "application/x-pkcs7-certreqresp", "p7b": "application/x-pkcs7-certificates", "p8": "application/pkcs8", "plf": "application/vnd.pocketlearn", "pnm": "image/x-portable-anymap", "pbm": "image/x-portable-bitmap", "pcf": "application/x-font-pcf", "pfr": "application/font-tdpfr", "pgn": "application/x-chess-pgn", "pgm": "image/x-portable-graymap", "png": "image/x-png", "ppm": "image/x-portable-pixmap", "pskcxml": "application/pskc+xml", "pml": "application/vnd.ctc-posml", "ai": "application/postscript", "pfa": "application/x-font-type1", "pbd": "application/vnd.powerbuilder6", "pgp": "application/pgp-signature", "box": "application/vnd.previewsystems.box", "ptid": "application/vnd.pvi.ptid1", "pls": "application/pls+xml", "str": "application/vnd.pg.format", "ei6": "application/vnd.pg.osasli", "dsc": "text/prs.lines.tag", "psf": "application/x-font-linux-psf", "qps": "application/vnd.publishare-delta-tree", "wg": "application/vnd.pmi.widget", "qxd": "application/vnd.quark.quarkxpress", "esf": "application/vnd.epson.esf", "msf": "application/vnd.epson.msf", "ssf": "application/vnd.epson.ssf", "qam": "application/vnd.epson.quickanime", "qfx": "application/vnd.intu.qfx", "qt": "video/quicktime", "rar": "application/x-rar-compressed", "ram": "audio/x-pn-realaudio", "rmp": "audio/x-pn-realaudio-plugin", "rsd": "application/rsd+xml", "rm": "application/vnd.rn-realmedia", "bed": "application/vnd.realvnc.bed", "mxl": "application/vnd.recordare.musicxml", "musicxml": "application/vnd.recordare.musicxml+xml", "rnc": "application/relax-ng-compact-syntax", "rdz": "application/vnd.data-vision.rdz", "rdf": "application/rdf+xml", "rp9": "application/vnd.cloanto.rp9", "jisp": "application/vnd.jisp", "rtf": "application/rtf", "rtx": "text/richtext", "link66": "application/vnd.route66.link66+xml", "rss, .xml": "application/rss+xml", "shf": "application/shf+xml", "st": "application/vnd.sailingtracker.track", "svg": "image/svg+xml", "sus": "application/vnd.sus-calendar", "sru": "application/sru+xml", "setpay": "application/set-payment-initiation", "setreg": "application/set-registration-initiation", "sema": "application/vnd.sema", "semd": "application/vnd.semd", "semf": "application/vnd.semf", "see": "application/vnd.seemail", "snf": "application/x-font-snf", "spq": "application/scvp-vp-request", "spp": "application/scvp-vp-response", "scq": "application/scvp-cv-request", "scs": "application/scvp-cv-response", "sdp": "application/sdp", "etx": "text/x-setext", "movie": "video/x-sgi-movie", "ifm": "application/vnd.shana.informed.formdata", "itp": "application/vnd.shana.informed.formtemplate", "iif": "application/vnd.shana.informed.interchange", "ipk": "application/vnd.shana.informed.package", "tfi": "application/thraud+xml", "shar": "application/x-shar", "rgb": "image/x-rgb", "slt": "application/vnd.epson.salt", "aso": "application/vnd.accpac.simply.aso", "imp": "application/vnd.accpac.simply.imp", "twd": "application/vnd.simtech-mindmapper", "csp": "application/vnd.commonspace", "saf": "application/vnd.yamaha.smaf-audio", "mmf": "application/vnd.smaf", "spf": "application/vnd.yamaha.smaf-phrase", "teacher": "application/vnd.smart.teacher", "svd": "application/vnd.svd", "rq": "application/sparql-query", "srx": "application/sparql-results+xml", "gram": "application/srgs", "grxml": "application/srgs+xml", "ssml": "application/ssml+xml", "skp": "application/vnd.koan", "sgml": "text/sgml", "sdc": "application/vnd.stardivision.calc", "sda": "application/vnd.stardivision.draw", "sdd": "application/vnd.stardivision.impress", "smf": "application/vnd.stardivision.math", "sdw": "application/vnd.stardivision.writer", "sgl": "application/vnd.stardivision.writer-global", "sm": "application/vnd.stepmania.stepchart", "sit": "application/x-stuffit", "sitx": "application/x-stuffitx", "sdkm": "application/vnd.solent.sdkm+xml", "xo": "application/vnd.olpc-sugar", "au": "audio/basic", "wqd": "application/vnd.wqd", "sis": "application/vnd.symbian.install", "smi": "application/smil+xml", "xsm": "application/vnd.syncml+xml", "bdm": "application/vnd.syncml.dm+wbxml", "xdm": "application/vnd.syncml.dm+xml", "sv4cpio": "application/x-sv4cpio", "sv4crc": "application/x-sv4crc", "sbml": "application/sbml+xml", "tsv": "text/tab-separated-values", "tiff": "image/tiff", "tao": "application/vnd.tao.intent-module-archive", "tar": "application/x-tar", "tcl": "application/x-tcl", "tex": "application/x-tex", "tfm": "application/x-tex-tfm", "tei": "application/tei+xml", "txt": "text/plain", "dxp": "application/vnd.spotfire.dxp", "sfs": "application/vnd.spotfire.sfs", "tsd": "application/timestamped-data", "tpt": "application/vnd.trid.tpt", "mxs": "application/vnd.triscape.mxs", "t": "text/troff", "tra": "application/vnd.trueapp", "ttf": "application/x-font-ttf", "ttl": "text/turtle", "umj": "application/vnd.umajin", "uoml": "application/vnd.uoml+xml", "unityweb": "application/vnd.unity", "ufd": "application/vnd.ufdl", "uri": "text/uri-list", "utz": "application/vnd.uiq.theme", "ustar": "application/x-ustar", "uu": "text/x-uuencode", "vcs": "text/x-vcalendar", "vcf": "text/x-vcard", "vcd": "application/x-cdlink", "vsf": "application/vnd.vsf", "wrl": "model/vrml", "vcx": "application/vnd.vcx", "mts": "model/vnd.mts", "vtu": "model/vnd.vtu", "vis": "application/vnd.visionary", "viv": "video/vnd.vivo", "ccxml": "application/ccxml+xml,", "vxml": "application/voicexml+xml", "src": "application/x-wais-source", "wbxml": "application/vnd.wap.wbxml", "wbmp": "image/vnd.wap.wbmp", "wav": "audio/x-wav", "davmount": "application/davmount+xml", "woff": "application/x-font-woff", "wspolicy": "application/wspolicy+xml", "webp": "image/webp", "wtb": "application/vnd.webturbo", "wgt": "application/widget", "hlp": "application/winhlp", "wml": "text/vnd.wap.wml", "wmls": "text/vnd.wap.wmlscript", "wmlsc": "application/vnd.wap.wmlscriptc", "wpd": "application/vnd.wordperfect", "stf": "application/vnd.wt.stf", "wsdl": "application/wsdl+xml", "xbm": "image/x-xbitmap", "xpm": "image/x-xpixmap", "xwd": "image/x-xwindowdump", "der": "application/x-x509-ca-cert", "fig": "application/x-xfig", "xhtml": "application/xhtml+xml", "xml": "application/xml", "xdf": "application/xcap-diff+xml", "xenc": "application/xenc+xml", "xer": "application/patch-ops-error+xml", "rl": "application/resource-lists+xml", "rs": "application/rls-services+xml", "rld": "application/resource-lists-diff+xml", "xslt": "application/xslt+xml", "xop": "application/xop+xml", "xpi": "application/x-xpinstall", "xspf": "application/xspf+xml", "xul": "application/vnd.mozilla.xul+xml", "xyz": "chemical/x-xyz", "yaml": "text/yaml", "yang": "application/yang", "yin": "application/yin+xml", "zir": "application/vnd.zul", "zip": "application/zip", "zmm": "application/vnd.handheld-entertainment+xml", "zaz": "application/vnd.zzazz.deck+xml"}

How to install 2 Anacondas (Python 2 and 3) on Mac OS

There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do

conda create -n python2 python=2.7 anaconda

This will create an environment named python2 that contains the Python 2.7 version of Anaconda. You can activate this environment with

source activate python2

This will put that environment (typically ~/anaconda/envs/python2) in front in your PATH, so that when you type python at the terminal it will load the Python from that environment.

If you don't want all of Anaconda, you can replace anaconda in the command above with whatever packages you want. You can use conda to install packages in that environment later, either by using the -n python2 flag to conda, or by activating the environment.

can't access mysql from command line mac

Just do the following in your terminal:

echo $PATH

If your given path is not in that string, you have to add it like this: export PATH=$PATH:/usr/local/ or export PATH=$PATH:/usr/local/mysql/bin

Switch tabs using Selenium WebDriver with Java

Since the driver.window_handles is not in order , a better solution is this.

first switch to the first tab using the shortcut Control + X to switch to the 'x' th tab in the browser window .

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "1");
# goes to 1st tab

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "4");
# goes to 4th tab if its exists or goes to last tab.

SQL UPDATE with sub-query that references the same table in MySQL

Some reference for you http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE user_account student 
INNER JOIN user_account teacher ON
   teacher.user_account_id = student.teacher_id 
   AND teacher.user_type = 'ROLE_TEACHER'
SET student.student_education_facility_id = teacher.education_facility_id

Compare two Lists for differences

I think you're looking for a method like this:

public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
    IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
    var enum1 = seq1.GetEnumerator();
    var enum2 = seq2.GetEnumerator();

    while (enum1.MoveNext() && enum2.MoveNext())
    {
        yield return comparer(enum1.Current, enum2.Current);
    }
}

It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.

This solution of course assumes that you want to compare the nth item of seq1 with the nth item in seq2. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.

Edit: Here's an example of how you might use the CompareSequences method with the comparer function you originally posted.

// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;    

foreach(var element in results)
{
    Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

Wordpress - Images not showing up in the Media Library

How did you upload those images; via FTP or through WP uploader? You have to upload images THROUGH WP uploader in order to show them in the image library.

Getting results between two dates in PostgreSQL

To have a query working in any locale settings, consider formatting the date yourself:

SELECT * 
  FROM testbed 
 WHERE start_date >= to_date('2012-01-01','YYYY-MM-DD')
   AND end_date <= to_date('2012-04-13','YYYY-MM-DD');

Can we have multiple <tbody> in same <table>?

Martin Joiner's problem is caused by a misunderstanding of the <caption> tag.

The <caption> tag defines a table caption.

The <caption> tag must be the first child of the <table> tag.

You can specify only one caption per table.

Also, note that the scope attribute should be placed on a <th> element and not on a <tr> element.

The proper way to write a multi-header multi-tbody table would be something like this :

_x000D_
_x000D_
<table id="dinner_table">_x000D_
    <caption>This is the only correct place to put a caption.</caption>_x000D_
    <tbody>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">First Half of Table (British Dinner)</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">1</th>_x000D_
            <td>Fish</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">2</th>_x000D_
            <td>Chips</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">3</th>_x000D_
            <td>Peas</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">4</th>_x000D_
            <td>Gravy</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">Second Half of Table (Italian Dinner)</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">5</th>_x000D_
            <td>Pizza</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">6</th>_x000D_
            <td>Salad</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">7</th>_x000D_
            <td>Oil</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">8</th>_x000D_
            <td>Bread</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I create a carriage return in my C# string

You can put \r\n in your string.

Git: How to find a deleted file in the project commit history?

Below is a simple command, where a dev or a git user can pass a deleted file name from the repository root directory and get the history:

git log --diff-filter=D --summary | grep filename | awk '{print $4; exit}' | xargs git log --all -- 

If anybody, can improve the command, please do.

Read/write to file using jQuery

If you want to do this without a bunch of server-side processing within the page, it might be a feasible idea to blow the text value into a hidden field (using PHP). Then you can use jQuery to process the hidden field value.

Whatever floats your boat :)

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

What do Clustered and Non clustered index actually mean?

With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.

With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.

It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.

Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.

Is there anyway to exclude artifacts inherited from a parent POM?

I really needed to do this dirty thing... Here is how

I redefined those dependencies with scope test. Scope provided did not work for me.

We use spring Boot plugin to build fat jar. We have module common which defines common libraries, for example Springfox swagger-2. My super-service needs to have parent common (it does not want to do so, but company rules force!)

So my parent or commons has pom.

<dependencyManagement>

    <!- I do not need Springfox in one child but in others ->

    <dependencies>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-bean-validators</artifactId>
            <version>${swagger.version}</version>
        </dependency>

       <!- All services need them ->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${apache.poi.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

And my super-service pom.

<name>super-service</name>
<parent>
    <groupId>com.company</groupId>
    <artifactId>common</artifactId>
    <version>1</version>
</parent>

<dependencies>

    <!- I don't need them ->

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-core</artifactId>
        <version>2.8.0</version>
        <scope>test</scope>
    </dependency>

    <!- Required dependencies ->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
     <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
    </dependency>
</dependencies>

This is size of the final fat artifact

82.3 MB (86,351,753 bytes) - redefined dependency with scope test
86.1 MB (90,335,466 bytes) - redefined dependency with scope provided
86.1 MB (90,335,489 bytes) - without exclusion

Also this answer is worth mentioning - I wanted to do so, but I am lazy... https://stackoverflow.com/a/48103554/4587961

Get integer value from string in swift

A more general solution could be a extension

extension String {
    var toFloat:Float {
        return Float(self.bridgeToObjectiveC().floatValue)
    }
    var toDouble:Double {
        ....
    }
    ....
}

this for example extends the swift native String object by toFloat

C# Inserting Data from a form into an access Database

 private void Add_Click(object sender, EventArgs e) {
 OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
 OleDbCommand cmd = con.CreateCommand();
 con.Open();
 cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
 cmd.ExecuteNonQuery();
 MessageBox.Show("Record Submitted", "Congrats");
 con.Close();
} 

How can strip whitespaces in PHP's variable?

Any possible option is to use custom file wrapper for simulating variables as files. You can achieve it by using this:

1) First of all, register your wrapper (only once in file, use it like session_start()):

stream_wrapper_register('var', VarWrapper);

2) Then define your wrapper class (it is really fast written, not completely correct, but it works):

class VarWrapper {
  protected $pos = 0;
  protected $content;
  public function stream_open($path, $mode, $options, &$opened_path) {
    $varname = substr($path, 6);
    global $$varname;
    $this->content = $$varname;
    return true;
  }
  public function stream_read($count) {
    $s = substr($this->content, $this->pos, $count);
    $this->pos += $count;
    return $s;
  }
  public function stream_stat() {
    $f = fopen(__file__, 'rb');
    $a = fstat($f);
    fclose($f);
    if (isset($a[7])) $a[7] = strlen($this->content);
    return $a;
  }
}

3) Then use any file function with your wrapper on var:// protocol (you can use it for include, require etc. too):

global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');

Note: Don't forget to have your variable in global scope (like global $__myVar)

How can I String.Format a TimeSpan object with a custom format in .NET?

I used the code below. It is long, but still it is one expression, and produces very friendly output, as it does not outputs days, hours, minutes, or seconds if they have value of zero.

In the sample it produces output: "4 days 1 hour 3 seconds".

TimeSpan sp = new TimeSpan(4,1,0,3);
string.Format("{0}{1}{2}{3}", 
        sp.Days > 0 ? ( sp.Days > 1 ? sp.ToString(@"d\ \d\a\y\s\ "): sp.ToString(@"d\ \d\a\y\ ")):string.Empty,
        sp.Hours > 0 ? (sp.Hours > 1 ? sp.ToString(@"h\ \h\o\u\r\s\ ") : sp.ToString(@"h\ \h\o\u\r\ ")):string.Empty,
        sp.Minutes > 0 ? (sp.Minutes > 1 ? sp.ToString(@"m\ \m\i\n\u\t\e\s\ ") :sp.ToString(@"m\ \m\i\n\u\t\e\ ")):string.Empty,
        sp.Seconds > 0 ? (sp.Seconds > 1 ? sp.ToString(@"s\ \s\e\c\o\n\d\s"): sp.ToString(@"s\ \s\e\c\o\n\d\s")):string.Empty);

Run cmd commands through Java

Once you get the reference to Process, you can call getOutpuStream on it to get the standard input of the cmd prompt. Then you can send any command over the stream using write method as with any other stream.

Note that it is process.getOutputStream() which is connected to the stdin on the spawned process. Similarly, to get the output of any command, you will need to call getInputStream and then read over this as any other input stream.

How do I delete an entity from symfony2

Symfony is smart and knows how to make the find() by itself :

public function deleteGuestAction(Guest $guest)
{
    if (!$guest) {
        throw $this->createNotFoundException('No guest found');
    }

    $em = $this->getDoctrine()->getEntityManager();
    $em->remove($guest);
    $em->flush();

    return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}

To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

How to open standard Google Map application from my application?

This is written in Kotlin, it will open the maps app if it's found and place the point and let you start the trip:

  val gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=" + adapter.getItemAt(position).latitud + "," + adapter.getItemAt(position).longitud)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        mapIntent.setPackage("com.google.android.apps.maps")
        if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
            startActivity(mapIntent)
        }

Replace requireActivity() with your Context.

AJAX reload page with POST

By using jquery ajax you can reload your page

$.ajax({
    type: "POST",
    url: "packtypeAdd.php",
    data: infoPO,
    success: function() {   
        location.reload();  
    }
});

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

Android Room - simple select query - Cannot access database on the main thread

With lambda its easy to run with AsyncTask

 AsyncTask.execute(() -> //run your query here );

How to update Android Studio automatically?

On the startup screen you can use the configure button to check for updates.

1) Choose configure > Check for Update enter image description here

2) Download the latest updates

enter image description here

Check if string contains \n Java

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
        if(!StringUtils.isEmpty(str)){
            Scanner scanner = new Scanner(str);
            scanner.nextLine();
            boolean hasNextLine =  scanner.hasNextLine();
            scanner.close();
            return hasNextLine;
        }
        return false;
    }

How to get the file path from HTML input form in Firefox 3

Actually, just before FF3 was out, I did some experiments, and FF2 sends only the filename, like did Opera 9.0. Only IE sends the full path. The behavior makes sense, because the server doesn't have to know where the user stores the file on his computer, it is irrelevant to the upload process. Unless you are writing an intranet application and get the file by direct network access!

What have changed (and that's the real point of the bug item you point to) is that FF3 no longer let access to the file path from JavaScript. And won't let type/paste a path there, which is more annoying for me: I have a shell extension which copies the path of a file from Windows Explorer to the clipboard and I used it a lot in such form. I solved the issue by using the DragDropUpload extension. But this becomes off-topic, I fear.

I wonder what your Web forms are doing to stop working with this new behavior.

[EDIT] After reading the page linked by Mike, I see indeed intranet uses of the path (identify a user for example) and local uses (show preview of an image, local management of files). User Jam-es seems to provide a workaround with nsIDOMFile (not tried yet).

How do I use HTML as the view engine in Express?

Comment out the middleware for html i.e.

//app.set('view engine', 'html');

Instead use:

app.get("/",(req,res)=>{
    res.sendFile("index.html");
});

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

A solution I came up with is to use a vis.js instance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page

A small notebook to illustrate this: demo

The code itself:

from IPython.core.display import display, HTML
import json

def plot3D(X, Y, Z, height=600, xlabel = "X", ylabel = "Y", zlabel = "Z", initialCamera = None):

    options = {
        "width": "100%",
        "style": "surface",
        "showPerspective": True,
        "showGrid": True,
        "showShadow": False,
        "keepAspectRatio": True,
        "height": str(height) + "px"
    }

    if initialCamera:
        options["cameraPosition"] = initialCamera

    data = [ {"x": X[y,x], "y": Y[y,x], "z": Z[y,x]} for y in range(X.shape[0]) for x in range(X.shape[1]) ]
    visCode = r"""
       <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" type="text/css" rel="stylesheet" />
       <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
       <div id="pos" style="top:0px;left:0px;position:absolute;"></div>
       <div id="visualization"></div>
       <script type="text/javascript">
        var data = new vis.DataSet();
        data.add(""" + json.dumps(data) + """);
        var options = """ + json.dumps(options) + """;
        var container = document.getElementById("visualization");
        var graph3d = new vis.Graph3d(container, data, options);
        graph3d.on("cameraPositionChange", function(evt)
        {
            elem = document.getElementById("pos");
            elem.innerHTML = "H: " + evt.horizontal + "<br>V: " + evt.vertical + "<br>D: " + evt.distance;
        });
       </script>
    """
    htmlCode = "<iframe srcdoc='"+visCode+"' width='100%' height='" + str(height) + "px' style='border:0;' scrolling='no'> </iframe>"
    display(HTML(htmlCode))

How to input matrix (2D list) in Python?

you can accept a 2D list in python this way ...

simply

arr2d = [[j for j in input().strip()] for i in range(n)] 
# n is no of rows


for characters

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = list(input().strip())
print(a)

or

n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
    a[i].append(list(input().strip()))
print(a)

for numbers

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = [int(j) for j in input().strip().split(" ")]
print(a)

where n is no of elements in columns while m is no of elements in a row.

In pythonic way, this will create a list of list

jQuery's .on() method combined with the submit event

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:

$('form').on('submit',doFormStuff);

createNewForm();

// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){
    $('form').off('submit').on('submit',doFormStuff); 
    $('button').off('click').on('click',doButtonStuff);
}   

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.

createNewButton();
bindItems();

I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

How do you uninstall all dependencies listed in package.json (NPM)?

I recently found a node command that allows uninstalling all the development dependencies as follows:

npm prune --production

As I mentioned, this command only uninstalls the development dependency packages. At least it helped me not to have to do it manually.

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void);

That is the correct way to say "no parameters" in C, and it also works in C++.

But:

void foo();

Means different things in C and C++! In C it means "could take any number of parameters of unknown types", and in C++ it means the same as foo(void).

Variable argument list functions are inherently un-typesafe and should be avoided where possible.

How do I center an anchor element in CSS?

style="margin:0 auto; width:auto;" Try that.

Removing empty lines in Notepad++

  1. notepad++
  2. Ctrl-H
  3. Select Regular Expression
  4. Enter ^[ \t]*$\r?\n into find what, leave replace empty. This will match all lines starting with white space and ending with carriage return (in this case a windows crlf)
  5. Click the Find Next button to see for yourself how it matches only empty lines.

Run class in Jar file

Use java -cp myjar.jar com.mypackage.myClass.

  1. If the class is not in a package then simply java -cp myjar.jar myClass.

  2. If you are not within the directory where myJar.jar is located, then you can do:

    1. On Unix or Linux platforms:

      java -cp /location_of_jar/myjar.jar com.mypackage.myClass

    2. On Windows:

      java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass

Android Studio gradle takes too long to build

You could try the tips in this post Why your Android Studio takes forever to build - Part 2 One of the tips recommmends "Enable offline mode" among other things.

How to loop over grouped Pandas dataframe?

Here is an example of iterating over a pd.DataFrame grouped by the column atable. For this sample, "create" statements for an SQL database are generated within the for loop:

import pandas as pd

df1 = pd.DataFrame({
    'atable':     ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
    'column':     ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
    'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
    'is_null':    ['No', 'No', 'Yes', 'No', 'Yes'],
})

df1_grouped = df1.groupby('atable')

# iterate over each group
for group_name, df_group in df1_grouped:
    print('\nCREATE TABLE {}('.format(group_name))

    for row_index, row in df_group.iterrows():
        col = row['column']
        column_type = row['column_type']
        is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
        print('\t{} {} {},'.format(col, column_type, is_null))

    print(");")

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

How to calculate the median of an array?

The Arrays class in Java has a static sort function, which you can invoke with Arrays.sort(numArray).

Arrays.sort(numArray);
double median;
if (numArray.length % 2 == 0)
    median = ((double)numArray[numArray.length/2] + (double)numArray[numArray.length/2 - 1])/2;
else
    median = (double) numArray[numArray.length/2];

How do I register a DLL file on Windows 7 64-bit?

Finally I found the solution just run CMD as administrator then write

cd \windows\syswow64

then write this

regsvr32 c:\filename.dll

I hope that answer will help you

Check if any type of files exist in a directory using BATCH script

You can use this

@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
   echo Folder is NON empty
   goto :EOF
)
echo Folder is empty or does not exist

Taken from here.

That should do what you need.

How to escape a single quote inside awk

For small scripts an optional way to make it readable is to use a variable like this:

awk -v fmt="'%s'\n" '{printf fmt, $1}'

I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

Remove the title bar in Windows Forms

if by Blue Border thats on top of the Window Form you mean titlebar, set Forms ControlBox property to false and Text property to empty string ("").

here's a snippet:

this.ControlBox = false;
this.Text = String.Empty;

What evaluates to True/False in R?

If you think about it, comparing numbers to logical statements doesn't make much sense. However, since 0 is often associated with "Off" or "False" and 1 with "On" or "True", R has decided to allow 1 == TRUE and 0 == FALSE to both be true. Any other numeric-to-boolean comparison should yield false, unless it's something like 3 - 2 == TRUE.

How to enter newline character in Oracle?

begin   
   dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
end;

How to filter array when object key value is in array

You can do it with Array.prototype.filter(),

var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
var empIds = [1,4,5]
var filteredArray = data.records.filter(function(itm){
  return empIds.indexOf(itm.empid) > -1;
});

filteredArray = { records : filteredArray };

If? the ?callBack? returns a ?true? value, then the ?itm? passed to that particular callBack will be filtered out. You can read more about it here.??????

Running command line silently with VbScript and getting output?

I have taken this and various other comments and created a bit more advanced function for running an application and getting the output.

Example to Call Function: Will output the DIR list of C:\ for Directories only. The output will be returned to the variable CommandResults as well as remain in C:\OUTPUT.TXT.

CommandResults = vFn_Sys_Run_CommandOutput("CMD.EXE /C DIR C:\ /AD",1,1,"C:\OUTPUT.TXT",0,1)

Function

Function vFn_Sys_Run_CommandOutput (Command, Wait, Show, OutToFile, DeleteOutput, NoQuotes)
'Run Command similar to the command prompt, for Wait use 1 or 0. Output returned and
'stored in a file.
'Command = The command line instruction you wish to run.
'Wait = 1/0; 1 will wait for the command to finish before continuing.
'Show = 1/0; 1 will show for the command window.
'OutToFile = The file you wish to have the output recorded to.
'DeleteOutput = 1/0; 1 deletes the output file. Output is still returned to variable.
'NoQuotes = 1/0; 1 will skip wrapping the command with quotes, some commands wont work
'                if you wrap them in quotes.
'----------------------------------------------------------------------------------------
  On Error Resume Next
  'On Error Goto 0
    Set f_objShell = CreateObject("Wscript.Shell")
    Set f_objFso = CreateObject("Scripting.FileSystemObject")
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
      'VARIABLES
        If OutToFile = "" Then OutToFile = "TEMP.TXT"
        tCommand = Command
        If Left(Command,1)<>"""" And NoQuotes <> 1 Then tCommand = """" & Command & """"
        tOutToFile = OutToFile
        If Left(OutToFile,1)<>"""" Then tOutToFile = """" & OutToFile & """"
        If Wait = 1 Then tWait = True
        If Wait <> 1 Then tWait = False
        If Show = 1 Then tShow = 1
        If Show <> 1 Then tShow = 0
      'RUN PROGRAM
        f_objShell.Run tCommand & ">" & tOutToFile, tShow, tWait
      'READ OUTPUT FOR RETURN
        Set f_objFile = f_objFso.OpenTextFile(OutToFile, 1)
          tMyOutput = f_objFile.ReadAll
          f_objFile.Close
          Set f_objFile = Nothing
      'DELETE FILE AND FINISH FUNCTION
        If DeleteOutput = 1 Then
          Set f_objFile = f_objFso.GetFile(OutToFile)
            f_objFile.Delete
            Set f_objFile = Nothing
          End If
        vFn_Sys_Run_CommandOutput = tMyOutput
        If Err.Number <> 0 Then vFn_Sys_Run_CommandOutput = "<0>"
        Err.Clear
        On Error Goto 0
      Set f_objFile = Nothing
      Set f_objShell = Nothing
  End Function

How to subtract X day from a Date object in Java?

You may also be able to use the Duration class. E.g.

Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());

Java LinkedHashMap get first or last entry

For first element use entrySet().iterator().next() and stop iterating after 1 iteration. For last one the easiest way is to preserve the key in a variable whenever you do a map.put.

How to determine the screen width in terms of dp or dip at runtime in Android?

If you just want to know about your screen width, you can just search for "smallest screen width" in your developer options. You can even edit it.

Printing an int list in a single line python3

Try using join on a str conversion of your ints:

print(' '.join(str(x) for x in array))

For python 3.7

RegEx pattern any two letters followed by six numbers

[a-zA-Z]{2}\d{6}

[a-zA-Z]{2} means two letters \d{6} means 6 digits

If you want only uppercase letters, then:

[A-Z]{2}\d{6}

Oracle SqlPlus - saving output in a file but don't show on screen

Try This:

sqlplus -s ${ORA_CONN_STR} <<EOF >/dev/null

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

Python float to int conversion

>>> x = 2.51
>>> x*100
250.99999999999997

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

How do I restrict an input to only accept numbers?

you may also want to remove the 0 at the beginning of the input... I simply add an if block to Mordred answer above because I cannot make a comment yet...

  app.directive('numericOnly', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, modelCtrl) {

          modelCtrl.$parsers.push(function (inputValue) {
              var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;

              if (transformedInput!=inputValue) {
                  modelCtrl.$setViewValue(transformedInput);
                  modelCtrl.$render();
              }
              //clear beginning 0
              if(transformedInput == 0){
                modelCtrl.$setViewValue(null);
                modelCtrl.$render();
              }
              return transformedInput;
          });
      }
    };
  })

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

ERROR 1148: The used command is not allowed with this MySQL version

You can specify that as an additional option when setting up your client connection:

mysql -u myuser -p --local-infile somedatabase

This is because that feature opens a security hole. So you have to enable it in an explicit manner in case you really want to use it.

Both client and server should enable the local-file option. Otherwise it doesn't work.To enable it for files on the server side server add following to the my.cnf configuration file:

loose-local-infile = 1

Can't access Tomcat using IP address

Windows Firewall cause issue after uninstalling Oracle JDK and installing OpenJDK on Windows Server 2008 R2.

Tomcat 7 and Tomcat 8 not access on other machine after this.

Follow below path to add new rule

 --> Windows Firewall with Advanced Security on Local Computer
 --> Inbound Rule 
 -->Add New Rule 
      with specific port you have required for Tomcat application.

Move view with keyboard using Swift

So none of the other answers seems to get it right.

The Good Behaviored Keyboard on iOS should:

  • Resize automatically when the keyboard change sizes (YES IT CAN)
  • Animate at the same speed as the keyboard
  • Animate using the same curve as the keyboard
  • Respect safe areas if relevant.
  • Works on iPad/Undocked mode too

My code use a NSLayoutConstraint declared as an @IBOutlet

@IBOutlet private var bottomLayoutConstraint: NSLayoutConstraint!

You could also use transforms, view offsets, .... I think it's easier with the constraint tho. It works by setting a constraint to the bottom, you might need to alter the code if your constant is not 0/Not to the bottom.

Here is the code:

// In ViewDidLoad
    NotificationCenter.default.addObserver(self, selector: #selector(?MyViewController.keyboardDidChange), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)


@objc func keyboardDidChange(notification: Notification) {
    let userInfo = notification.userInfo! as [AnyHashable: Any]
    let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber
    let animationCurve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber
    bottomLayoutConstraint.constant = view.frame.height - endFrame.origin.y - view.safeAreaInsets.bottom // If your constraint is not defined as a safeArea constraint you might want to skip the last part.
    // Prevents iPad undocked keyboard.
    guard endFrame.height != 0, view.frame.height == endFrame.height + endFrame.origin.y else {
        bottomLayoutConstraint.constant = 0
        return
    }
    UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: animationCurve.intValue)!)
    UIView.animate(withDuration: animationDuration.doubleValue) {
        self.view.layoutIfNeeded()
        // Do additional tasks such as scrolling in a UICollectionView
    }
}

Leaflet changing Marker color

Leaflet Markers are stored as files unlike other objects (like Polylines, etc.)

If you want your own markers, you can find The official Leaflet Tutorial that explains how to do it.

EDIT :

After reading this conversation with the main developer I searched for the marker SVG and here it is.

With this you should be able to color the marker the way you want and randomly set their color.

EDIT AGAIN :

You can use MakiMarkers to set the color of a marker and use this extension to make some random stuffs. (It's simple and well explained)

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

Create local maven repository

If maven is not creating Local Repository i.e .m2/repository folder then try below step.

In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close

Regular Expressions- Match Anything

Try this:

I bought (.* )?sheep

or even

I bought .*sheep

shorthand c++ if else statement

try this:

bigInt.sign = number < 0 ? 0 : 1

Find a file in python

If you are working with Python 2 you have a problem with infinite recursion on windows caused by self-referring symlinks.

This script will avoid following those. Note that this is windows-specific!

import os
from scandir import scandir
import ctypes

def is_sym_link(path):
    # http://stackoverflow.com/a/35915819
    FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
    return os.path.isdir(path) and (ctypes.windll.kernel32.GetFileAttributesW(unicode(path)) & FILE_ATTRIBUTE_REPARSE_POINT)

def find(base, filenames):
    hits = []

    def find_in_dir_subdir(direc):
        content = scandir(direc)
        for entry in content:
            if entry.name in filenames:
                hits.append(os.path.join(direc, entry.name))

            elif entry.is_dir() and not is_sym_link(os.path.join(direc, entry.name)):
                try:
                    find_in_dir_subdir(os.path.join(direc, entry.name))
                except UnicodeDecodeError:
                    print "Could not resolve " + os.path.join(direc, entry.name)
                    continue

    if not os.path.exists(base):
        return
    else:
        find_in_dir_subdir(base)

    return hits

It returns a list with all paths that point to files in the filenames list. Usage:

find("C:\\", ["file1.abc", "file2.abc", "file3.abc", "file4.abc", "file5.abc"])

Is it possible to reference one CSS rule within another?

Just add the classes to your html

<div class="someDiv radius opacity"></div>

CSS-Only Scrollable Table with fixed headers

Surprised a solution using flexbox hasn't been posted yet.

Here's my solution using display: flex and a basic use of :after (thanks to Luggage) to maintain the alignment even with the scrollbar padding the tbody a bit. This has been verified in Chrome 45, Firefox 39, and MS Edge. It can be modified with prefixed properties to work in IE11, and further in IE10 with a CSS hack and the 2012 flexbox syntax.

Note the table width can be modified; this even works at 100% width.

The only caveat is that all table cells must have the same width. Below is a clearly contrived example, but this works fine when cell contents vary (table cells all have the same width and word wrapping on, forcing flexbox to keep them the same width regardless of content). Here is an example where cell contents are different.

Just apply the .scroll class to a table you want scrollable, and make sure it has a thead:

_x000D_
_x000D_
.scroll {_x000D_
  border: 0;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.scroll tr {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.scroll td {_x000D_
  padding: 3px;_x000D_
  flex: 1 auto;_x000D_
  border: 1px solid #aaa;_x000D_
  width: 1px;_x000D_
  word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.scroll thead tr:after {_x000D_
  content: '';_x000D_
  overflow-y: scroll;_x000D_
  visibility: hidden;_x000D_
  height: 0;_x000D_
}_x000D_
_x000D_
.scroll thead th {_x000D_
  flex: 1 auto;_x000D_
  display: block;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.scroll tbody {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
  height: 200px;_x000D_
}
_x000D_
<table class="scroll" width="400px">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Insert a new row into DataTable

// create table
var dt = new System.Data.DataTable("tableName");

// create fields
dt.Columns.Add("field1", typeof(int));
dt.Columns.Add("field2", typeof(string));
dt.Columns.Add("field3", typeof(DateTime));

// insert row values
dt.Rows.Add(new Object[]{
                123456,
                "test",
                DateTime.Now
           });

How to hide UINavigationBar 1px bottom line

Swift 4 Tested ONE LINE SOLUTION

In Viewdidload() Set Navigation controller's userdefault value true for key "hidesShadow"

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")

}

Row count with PDO

Have a look at this link: http://php.net/manual/en/pdostatement.rowcount.php It is not recommended to use rowCount() in SELECT statements!

How to get local server host and port in Spring Boot?

An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()

Have a look at this code:

@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO, 
    HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}

Filter by Dates in SQL

If your dates column does not contain time information, you could get away with:

WHERE dates BETWEEN '20121211' and '20121213'

However, given your dates column is actually datetime, you want this

WHERE dates >= '20121211'
  AND dates < '20121214'  -- i.e. 00:00 of the next day

Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:

WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'

Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

Open window in JavaScript with HTML inserted

You can use window.open to open a new window/tab(according to browser setting) in javascript.

By using document.write you can write HTML content to the opened window.

C# Encoding a text string with line breaks

Try this :

string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)

How do I redirect output to a variable in shell?

I guess compatible way:

hash=`genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5`

but I prefer

hash="$(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)"

sql delete statement where date is greater than 30 days

We can use this:

    DELETE FROM table_name WHERE date_column < 
           CAST(CONVERT(char(8), (DATEADD(day,-30,GETDATE())), 112) AS datetime)

But a better option is to use:

DELETE FROM table_name WHERE DATEDIFF(dd, date_column, GETDATE()) > 30

The former is not sargable (i.e. functions on the right side of the expression so it can’t use index) and takes 30 seconds, the latter is sargable and takes less than a second.

How do I create a datetime in Python from milliseconds?

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

Div Height in Percentage

There is the semicolon missing (;) after the "50%"

but you should also notice that the percentage of your div is connected to the div that contains it.

for instance:

<div id="wrapper">
  <div class="container">
   adsf
  </div>
</div>

#wrapper {
  height:100px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.

if you have:

adsf

#wrapper {
  height:400px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

then you .container will be 200px. 50% of the wrapper.

So you may want to look at the divs "wrapping" your ".container"...

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

Return list of items in list greater than some value

There is another way,

j3 = j2 > 4; print(j2[j3])

tested in 3.x

Make a negative number positive

Just call Math.abs. For example:

int x = Math.abs(-5);

Which will set x to 5.

Note that if you pass Integer.MIN_VALUE, the same value (still negative) will be returned, as the range of int does not allow the positive equivalent to be represented.

Git push won't do anything (everything up-to-date)

For my case, none of other solutions worked. I had to do a backup of new modified files (shown with git status), and run a git reset --hard. This allowed me to realign with the remote server. Adding new modified files, and running

git add .
git commit -am "my comment"
git push

Did the trick. I hope this helps someone, as a "last chance" solution.

Image is not showing in browser?

You need to import your image from the image folder. import name_of_image from '../imageFolder/name_of_image.jpg';

<img src={name_of_image} alt=''>

Please refer here. https://create-react-app.dev/docs/adding-images-fonts-and-files -

Get Selected value of a Combobox

If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:

Private Sub Worksheet_Change(ByVal Target As Range)

    MsgBox Target.Value

End Sub

If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.

Public WithEvents Cbx As MSForms.ComboBox

Private Sub Cbx_Change()

    MsgBox Cbx.Value

End Sub

Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.

Private mcolComboEvents As Collection

Private Sub Class_Initialize()
    Set mcolComboEvents = New Collection
End Sub

Private Sub Class_Terminate()
    Set mcolComboEvents = Nothing
End Sub

Public Sub Add(clsComboEvent As CComboEvent)

    mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name

End Sub

Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.

You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.

Public gclsComboEvents As CComboEvents

Public Sub AddCombox()

    Dim oleo As OLEObject
    Dim clsComboEvent As CComboEvent

    Set gclsComboEvents = New CComboEvents

    For Each oleo In Sheet1.OLEObjects
        If TypeName(oleo.Object) = "ComboBox" Then
            Set clsComboEvent = New CComboEvent
            Set clsComboEvent.Cbx = oleo.Object
            gclsComboEvents.Add clsComboEvent
        End If
    Next oleo

End Sub

Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.

You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm

Can I set up HTML/Email Templates with ASP.NET?

If you are able to allow the ASPNET and associated users permission to read & write a file, you can easily use an HTML file with standard String.Format() placeholders ({0}, {1:C}, etc.) to accomplish this.

Merely read in the file, as a string, using classes from the System.IO namespace. Once you have that string, pass it as the first argument to String.Format(), and provide the parameters.

Keep that string around, and use it as the body of the e-mail, and you're essentially done. We do this on dozens of (admittedly small) sites today, and have had no issues.

I should note that this works best if (a) you're not sending zillions of e-mails at a time, (b) you're not personalizing each e-mail (otherwise you eat up a ton of strings) and (c) the HTML file itself is relatively small.

Add key value pair to all objects in array

The map() function is a best choice for this case


tl;dr - Do this:

const newArr = [
  {name: 'eve'},
  {name: 'john'},
  {name: 'jane'}
].map(v => ({...v, isActive: true}))

The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.


Alternatives:

const initialArr = [
      {name: 'eve'},
      {name: 'john'},
      {name: 'jane'}
    ]

const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))

// Results of newArr1 and newArr2 are the same

Add a key value pair conditionally

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))

What if I don't want to add new field at all if the condition is false?

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr = arr.map(v => {
  return v.value > 1 ? {...v, isActive: true} : v 
})

Adding WITH modification of the initial array

const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});

This is probably not a best idea, but in a real life sometimes it's the only way.


Questions

  • Should I use a spread operator(...), or Object.assign and what's the difference?

Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)

  • Can I use function keyword instead of =>?

Sure you can. The fat arrow (=>) functions play a bit different with this, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.

  • What Actually happens inside map function: .map(v => ({...v, isActive: true})?

Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array. We tell to the .map() function following: take current value(v which is an object), take all key-value pairs away from v andput it inside a new object({...v}), but also add property isActive and set it to true ({...v, isActive: true}) and then return the result. Btw, if original object contains isActive filed it will be overwritten. Object.assign works in a similar way.

  • Can I add more then one field at a time

Yes.

[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
  • What I should not do inside .map() method

You shouldn't do any side effects[link 1, link 2], but apparently you can.

Also be noticed that map() iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).

  • Can I extract map's callback to a separate function?

Sure you can.

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr = arr.map(addIsActive)

function addIsActive(v) {
    return {...v, isActive: true}
}
  • What's wrong with old good for loop?

Nothing is wrong with for, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:

const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
 arr[i].isActive = true
}
  • What also i should learn

It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.

How to connect to LocalDB in Visual Studio Server Explorer?

The following works with Visual Studio 2017 Community Edition on Windows 10 using SQLServer Express 2016.

Open a PowerShell check what it is called using SqlLocalDB.exe info and whether it is Running with SqlLocalDB.exe info NAME. Here's what it looks like on my machine:

> SqlLocalDB.exe info
MSSQLLocalDB
> SqlLocalDB.exe info MSSQLLocalDB
Name:               mssqllocaldb
Version:            13.0.1601.5
Shared name:
Owner:              DESKTOP-I4H3E09\simon
Auto-create:        Yes
State:              Running
Last start time:    4/12/2017 8:24:36 AM
Instance pipe name: np:\\.\pipe\LOCALDB#EFC58609\tsql\query
>

If it isn't running then you need to start it with SqlLocalDB.exe start MSSQLLocalDB. When it is running you see the Instance pipe name: which starts with np:\\. Copy that named pipe string. Within VS2017 open the view Server Explorer and create a new connection of type Microsoft SQL Server (SqlClient) (don't be fooled by the other file types you want the full fat connection type) and set the Server name: to be the instance pipe name you copied from PowerShell.

I also set the Connect to database to be the same database that was in the connection string that was working in my Dotnet Core / Entity Framework Core project which was set up using dotnet ef database update.

You can login and create a database using the sqlcmd and the named pipe string:

sqlcmd -S np:\\.\pipe\LOCALDB#EFC58609\tsql\query 1> create database EFGetStarted.ConsoleApp.NewDb; 2> GO

There are instructions on how to create a user for your application at https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility

How to add a class with React.js?

Taken from their site.

render() {
  let className = 'menu';
  if (this.props.isActive) {
    className += ' menu-active';
  }
  return <span className={className}>Menu</span>
}

https://reactjs.org/docs/faq-styling.html

php: loop through json array

Use json_decode to convert the JSON string to a PHP array, then use normal PHP array functions on it.

$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);

var_dump($data[0]['var1']); // outputs '9'

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

UIButton action in table view cell

As Apple DOC

targetForAction:withSender:
Returns the target object that responds to an action.

You can't use that method to set target for UIButton.
Try addTarget(_:action:forControlEvents:) method

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

execute shell command from android

A modification of the code by @CarloCannas:

public static void sudo(String...strings) {
    try{
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

(You are welcome to find a better place for outputStream.close())

Usage example:

private static void suMkdirs(String path) {
    if (!new File(path).isDirectory()) {
        sudo("mkdir -p "+path);
    }
}

Update: To get the result (the output to stdout), use:

public static String sudoForResult(String...strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;
    try{
        Process su = Runtime.getRuntime().exec("su");
        outputStream = new DataOutputStream(su.getOutputStream());
        response = su.getInputStream();

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        res = readFully(response);
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        Closer.closeSilently(outputStream, response);
    }
    return res;
}
public static String readFully(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = is.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toString("UTF-8");
}

The utility to silently close a number of Closeables (So?ket may be no Closeable) is:

public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
    // Note: on Android API levels prior to 19 Socket does not implement Closeable
    for (Object x : xs) {
        if (x != null) {
            try {
                Log.d("closing: "+x);
                if (x instanceof Closeable) {
                    ((Closeable)x).close();
                } else if (x instanceof Socket) {
                    ((Socket)x).close();
                } else if (x instanceof DatagramSocket) {
                    ((DatagramSocket)x).close();
                } else {
                    Log.d("cannot close: "+x);
                    throw new RuntimeException("cannot close "+x);
                }
            } catch (Throwable e) {
                Log.x(e);
            }
        }
    }
}
}

Use space as a delimiter with cut command

I have an answer (I admit somewhat confusing answer) that involvessed, regular expressions and capture groups:

  • \S* - first word
  • \s* - delimiter
  • (\S*) - second word - captured
  • .* - rest of the line

As a sed expression, the capture group needs to be escaped, i.e. \( and \).

The \1 returns a copy of the captured group, i.e. the second word.

$ echo "alpha beta gamma delta" | sed 's/\S*\s*\(\S*\).*/\1/'
beta

When you look at this answer, its somewhat confusing, and, you may think, why bother? Well, I'm hoping that some, may go "Aha!" and will use this pattern to solve some complex text extraction problems with a single sed expression.

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

What's the difference between display:inline-flex and display:flex?

OK, I know at first might be a bit confusing, but display is talking about the parent element, so means when we say: display: flex;, it's about the element and when we say display:inline-flex;, is also making the element itself inline...

It's like make a div inline or block, run the snippet below and you can see how display flex breaks down to next line:

_x000D_
_x000D_
.inline-flex {_x000D_
  display: inline-flex;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
}
_x000D_
<body>_x000D_
  <p>Display Inline Flex</p>_x000D_
  <div class="inline-flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <div class="inline-flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <p>Display Flex</p>_x000D_
  <div class="flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <div class="flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Also quickly create the image below to show the difference at a glance:

display flex vs display inline-flex

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

Translating touch events from Javascript to jQuery

jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

how to split the ng-repeat data with three columns using bootstrap

Following is a more simple way:

<table>
    <tr ng-repeat="item in lists" ng-hide="$index%2!==0">
        <td>
            <label>{{ lists[$index].name}}</label>
        </td>
        <td ng-hide="!lists[$index+1]">
            <label>{{ lists[$index+1].name}}</label>
        </td>
    </tr>
</table>

Cumulo Nimbus's answer is useful for me but I want this grid wrapped by a div which can show the scrollbar when the list is too long.

To achieve this I added style="height:200px; overflow:auto" to a div around the table which causes it to show as a single column.

Now works for array length of one.

PHP Curl UTF-8 Charset

Simple: When you use curl it encodes the string to utf-8 you just need to decode them..

Description

string utf8_decode ( string $data )

This function decodes data , assumed to be UTF-8 encoded, to ISO-8859-1.

Renew Provisioning Profile

I went to the Program Portal on Apple's dev site, clicked on Provisioning, clicked on the "Renew" button next to my Profile, the status changed from 'expired' to 'pending', waited a few moments, clicked refresh, the new status was active until 3 months from now, I clicked on "Download", found the downloaded file in my downloads folder, and dragged it onto my XCode Icon. (I had Xcode running already, and had the iphone plugged in). The new profile showed up, and I deleted the old one (being careful because they had the same name, but when you mouse over them the expiration date appears).

I think because I had the phone plugged in already it automagically updated to the phone, because I didn't have to re-sync or anything.

Now my App works again!

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

ReactJS - Does render get called any time "setState" is called?

Another reason for "lost update" can be the next:

  • If the static getDerivedStateFromProps is defined then it is rerun in every update process according to official documentation https://reactjs.org/docs/react-component.html#updating.
  • so if that state value comes from props at the beginning it is overwrite in every update.

If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this

static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
   return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}

Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)

How can I output a UTF-8 CSV in PHP that Excel will read properly?

**This is 100% works fine in excel for both Windows7,8,10 and also All Mac OS.**
//Fix issues in excel that are not displaying characters containing diacritics, cyrillic letters, Greek letter and currency symbols.

function generateCSVFile($filename, $headings, $data) {

    //Use tab as field separator
    $newTab  = "\t";
    $newLine  = "\n";

    $fputcsv  =  count($headings) ? '"'. implode('"'.$newTab.'"', $headings).'"'.$newLine : '';

    // Loop over the * to export
    if (! empty($data)) {
      foreach($data as $item) {
        $fputcsv .= '"'. implode('"'.$newTab.'"', $item).'"'.$newLine;
      }
    }

    //Convert CSV to UTF-16
    $encoded_csv = mb_convert_encoding($fputcsv, 'UTF-16LE', 'UTF-8');

    // Output CSV-specific headers
    header('Set-Cookie: fileDownload=true; path=/'); //This cookie is needed in order to trigger the success window.
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
    header("Content-Transfer-Encoding: binary");
    header('Content-Length: '. strlen($encoded_csv));
    echo chr(255) . chr(254) . $encoded_csv; //php array convert to csv/excel
    exit;
}

Is there a way to access an iteration-counter in Java's for-each loop?

Using lambdas and functional interfaces in Java 8 makes creating new loop abstractions possible. I can loop over a collection with the index and the collection size:

List<String> strings = Arrays.asList("one", "two","three","four");
forEach(strings, (x, i, n) -> System.out.println("" + (i+1) + "/"+n+": " + x));

Which outputs:

1/4: one
2/4: two
3/4: three
4/4: four

Which I implemented as:

   @FunctionalInterface
   public interface LoopWithIndexAndSizeConsumer<T> {
       void accept(T t, int i, int n);
   }
   public static <T> void forEach(Collection<T> collection,
                                  LoopWithIndexAndSizeConsumer<T> consumer) {
      int index = 0;
      for (T object : collection){
         consumer.accept(object, index++, collection.size());
      }
   }

The possibilities are endless. For example, I create an abstraction that uses a special function just for the first element:

forEachHeadTail(strings, 
                (head) -> System.out.print(head), 
                (tail) -> System.out.print(","+tail));

Which prints a comma separated list correctly:

one,two,three,four

Which I implemented as:

public static <T> void forEachHeadTail(Collection<T> collection, 
                                       Consumer<T> headFunc, 
                                       Consumer<T> tailFunc) {
   int index = 0;
   for (T object : collection){
      if (index++ == 0){
         headFunc.accept(object);
      }
      else{
         tailFunc.accept(object);
      }
   }
}

Libraries will begin to pop up to do these sorts of things, or you can roll your own.

Django development IDE

PyCharm. It is best the IDE for Python,Django, and web development I've tried so far. It is totally worth the money.

How can I pass a member function where a free function is expected?

Not sure why this incredibly simple solution has been passed up:

#include <stdio.h>

class aClass
{
public:
    void aTest(int a, int b)
    {
        printf("%d + %d = %d\n", a, b, a + b);
    }
};

template<class C>
void function1(void (C::*function)(int, int), C& c)
{
    (c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
  function(1, 1);
}

void test(int a,int b)
{
    printf("%d - %d = %d\n", a , b , a - b);
}

int main (int argc, const char* argv[])
{
    aClass a;

    function1(&test);
    function1<aClass>(&aClass::aTest, a);
    return 0;
}

Output:

1 - 1 = 0
1 + 1 = 2

When to use "ON UPDATE CASCADE"

  1. Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10 all children parent_id's of 10 will also be updated to 20

  2. If you don't update the field the foreign key refers to, this setting is not needed

  3. Can't think of any other use.

  4. You can't do that as the foreign key constraint would fail.

Multiple bluetooth connection

You can take a look here ( this is not a solution but the idea is here)

sample multi client with the google chat example

what you have to change/do :

  • separate server and client logique in different classes

  • for the client you need an object to manage one connect thread and on connected thread

  • for the server you need an object to manage one listening thread per client, and one connected thread per client

  • the server open a listening thread on each UUID (one per client)

  • each client try to connect to each uuid (the uuid already taken will fail the connection => first come first served)

Any question ?

Eclipse IDE: How to zoom in on text?

Just by pressing Ctrl + Shift + '+' or '-'.

At least, it worked for me at Eclipse "2020-03" version.

Xcode - ld: library not found for -lPods

My way

  1. create new project and install pod it will can run without error.

  2. Copy text in "Other Linker Flags" in new project to old project. Make old project to same new project.

  3. Check "Header Search Paths" too.

How to find first element of array matching a boolean condition in JavaScript?

It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:

  1. Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.

  2. Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.

Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.

Both solutions above don't support offset searching either, so I've decided to write this:

(function(ns) {
  ns.search = function(array, callback, offset) {
    var size = array.length;

    offset = offset || 0;
    if (offset >= size || offset <= -size) {
      return -1;
    } else if (offset < 0) {
      offset = size - offset;
    }

    while (offset < size) {
      if (callback(array[offset], offset, array)) {
        return offset;
      }
      ++offset;
    }
    return -1;
  };
}(this));

search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3

How to execute a java .class from the command line

First, have you compiled the class using the command line javac compiler? Second, it seems that your main method has an incorrect signature - it should be taking in an array of String objects, rather than just one:

public static void main(String[] args){

Once you've changed your code to take in an array of String objects, then you need to make sure that you're printing an element of the array, rather than array itself:

System.out.println(args[0])

If you want to print the whole list of command line arguments, you'd need to use a loop, e.g.

for(int i = 0; i < args.length; i++){
    System.out.print(args[i]);
}
System.out.println();

Detect changed input text box

Text inputs do not fire the change event until they lose focus. Click outside of the input and the alert will show.

If the callback should fire before the text input loses focus, use the .keyup() event.

How do I declare a 2d array in C++ using new?

I'm using this when creating dynamic array. If you have a class or a struct. And this works. Example:

struct Sprite {
    int x;
};

int main () {
   int num = 50;
   Sprite **spritearray;//a pointer to a pointer to an object from the Sprite class
   spritearray = new Sprite *[num];
   for (int n = 0; n < num; n++) {
       spritearray[n] = new Sprite;
       spritearray->x = n * 3;
  }

   //delete from random position
    for (int n = 0; n < num; n++) {
        if (spritearray[n]->x < 0) {
      delete spritearray[n];
      spritearray[n] = NULL;
        }
    }

   //delete the array
    for (int n = 0; n < num; n++) {
      if (spritearray[n] != NULL){
         delete spritearray[n];
         spritearray[n] = NULL;
      }
    }
    delete []spritearray;
    spritearray = NULL;

   return 0;
  } 

How to check if ZooKeeper is running or up from command prompt?

From a Windows 10

  • Open Command Promt then type telnet localhost 2181and then you type srvr OR
  • From inside bin folder, open a PowerShell window and type zkServer.sh status

Bootstrap how to get text to vertical align in a div container

HTML:

First, we will need to add a class to your text container so that we can access and style it accordingly.

<div class="col-xs-5 textContainer">
     <h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>

CSS:

Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.

.textContainer { 
    height: 345px; 
    line-height: 340px;
}

.textContainer h3 {
    vertical-align: middle;
    display: inline-block;
}

All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.

WORKING EXAMPLE

Printing HashMap In Java

Java 8 new feature forEach style

import java.util.HashMap;

public class PrintMap {
    public static void main(String[] args) {
        HashMap<String, Integer> example = new HashMap<>();
        example.put("a", 1);
        example.put("b", 2);
        example.put("c", 3);
        example.put("d", 5);

        example.forEach((key, value) -> System.out.println(key + " : " + value));

//      Output:
//      a : 1
//      b : 2
//      c : 3
//      d : 5

    }
}

Playing mp3 song on python

So Far, pydub worked best for me. Modules like playsound will also do the job, But It has only one single feature. pydub has many features like slicing the song(file), Adjusting the volume etc...

It is as simple as slicing the lists in python.

So, When it comes to just playing, It is as shown as below.

from pydub import AudioSegment
from pydub.playback import play

path_to_file = r"Music/Harry Potter Theme Song.mp3"
song = AudioSegment.from_mp3(path_to_file)
play(song)

How do I copy a folder from remote to local using scp?

What I always use is:

scp -r username@IP:/path/to/server/source/folder/  .

. (dot) : it means current folder. so copy from server and paste here only.

IP : can be an IP address like 125.55.41.311 or it can be host like ns1.mysite.com.

How can I control the width of a label tag?

You can definitely try this way

.col-form-label{
  display: inline-block;
  width:200px;}

Xcode 6 iPhone Simulator Application Support location

To know where your .sqlite file is stored in your AppDelegate.m add the following code

- (NSURL *)applicationDocumentsDirectory
{
    NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory      inDomains:NSUserDomainMask] lastObject]);

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory     inDomains:NSUserDomainMask] lastObject];
 }

now call this method in AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  //call here
   [self applicationDocumentsDirectory];

}

Graphical HTTP client for windows

Update: For people that still come across this, Postman is your best bet now: https://www.getpostman.com/apps


RestClient is my favorite. It's Java based. I think it should meet your needs quite nicely. I particularly like the Auth suppport.

https://github.com/wiztools/rest-client

Screen Shot

Add alternating row color to SQL Server Reporting services report

Go to the table row's BackgroundColor property and choose "Expression..."

Use this expression:

= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

This trick can be applied to many areas of the report.

And in .NET 3.5+ You could use:

= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

Not looking for rep--I just researched this question myself and thought I'd share.

How to use Ajax.ActionLink?

Sure, a very similar question was asked before. Set the controller for ajax requests:

public ActionResult Show()
{
    if (Request.IsAjaxRequest()) 
    {
        return PartialView("Your_partial_view", new Model());
    }
    else 
    {
        return View();
    }
}

Set the action link as wanted:

@Ajax.ActionLink("Show", 
                 "Show", 
                 null, 
                 new AjaxOptions { HttpMethod = "GET", 
                 InsertionMode = InsertionMode.Replace, 
                 UpdateTargetId = "dialog_window_id", 
                 OnComplete = "your_js_function();" })

Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.

How do I move a file from one location to another in Java?

Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.

// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
    File tDir = new File(targetPath);
    if (tDir.exists()) {
        String newFilePath = targetPath+File.separator+sourceFile.getName();
        File movedFile = new File(newFilePath);
        if (movedFile.exists())
            movedFile.delete();
        return sourceFile.renameTo(new File(newFilePath));
    } else {
        LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
        return false;
    }       
}

Adding image to JFrame

There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:

  1. As @Reimeus said: Use a JLabel with an icon.
  2. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:

    JImageComponent ic = new JImageComponent(myImageGoesHere);
    imagePanel.add(ic);
    

    where JImageComponent is a self created class that extends JComponent that overrides the paintComponent() method to draw the image.

Unable to load script from assets index.android.bundle on windows

If you are using Windows run the commands in the following way, or if you get an error "Cannot find entry file index.android.js"

  1. mkdir android\app\src\main\assets
  2. react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

  3. react-native run-android

How do I left align these Bootstrap form items?

"pull-left" is what you need, it looks like you are using Bootstrap 2, I am not sure if that is available, consider bootstrap 3, unless ofcourse it is a huge rework! ... for Bootstrap 3 but you need to make sure you have 12 columns in each row as well, otherwise you will have issues.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

How to make an inline-block element fill the remainder of the line?

When you give up the inline blocks

.post-container {
    border: 5px solid #333;
    overflow:auto;
}
.post-thumb {
    float: left;
    display:block;
    background:#ccc;
    width:200px;
    height:200px;
}
.post-content{
    display:block;
    overflow:hidden;
}

http://jsfiddle.net/RXrvZ/3731/

(from CSS Float: Floating an image to the left of the text)

How to put a Scanner input into an array... for example a couple of numbers

Scanner scan = new Scanner (System.in);

for (int i=0; i<=4, i++){

    System.out.printf("Enter value at index"+i+" :");

    anArray[i]=scan.nextInt();

}

how to run or install a *.jar file in windows?

To run usually click and it should run, that is if you have java installed. If not get java from here Sorry thought it was more general open a command prompt and type java -jar jbpm-installer-3.2.7.jar

What does ^M character mean in Vim?

:%s/\r//g 

worked for me today. But my situation may have been slightly different.

Easiest way to read from and write to files

private void Form1_Load(object sender, EventArgs e)
    {
        //Write a file
        string text = "The text inside the file.";
        System.IO.File.WriteAllText("file_name.txt", text);

        //Read a file
        string read = System.IO.File.ReadAllText("file_name.txt");
        MessageBox.Show(read); //Display text in the file
    }

CSS force new line

Use the display property

a{
    display: block;
}

This will make the link to display in new line

If you want to remove list styling, use

li{
    list-style: none;
}

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

If you have installed WAMP on your machine, please make sure that it is running. Do not EXIT the WAMP from tray menu since it will stop the MySQL Server.

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

Read files from a Folder present in project

For Xamarin.iOS you can use the following code to get contents of the file if file exists.

var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, "xyz.json");
if (File.Exists(filename))
{
var text =System.IO.File.ReadAllText(filename);
}

How do you get the string length in a batch file?

If you are on Windows Vista +, then try this Powershell method:

For /F %%L in ('Powershell $Env:MY_STRING.Length') do (
    Set MY_STRING_LEN=%%L
)

or alternatively:

Powershell $Env:MY_STRING.Length > %Temp%\TmpFile.txt
Set /p MY_STRING_LEN = < %Temp%\TmpFile.txt
Del %Temp%\TmpFile.txt

I'm on Windows 7 x64 and this is working for me.

How to find if element with specific id exists or not

You can simply use if(yourElement)

_x000D_
_x000D_
var a = document.getElementById("elemA");_x000D_
var b = document.getElementById("elemB");_x000D_
_x000D_
if(a)_x000D_
  console.log("elemA exists");_x000D_
else_x000D_
  console.log("elemA does not exist");_x000D_
  _x000D_
if(b)_x000D_
  console.log("elemB exists");_x000D_
else_x000D_
  console.log("elemB does not exist");
_x000D_
<div id="elemA"></div>
_x000D_
_x000D_
_x000D_

How can I wait for set of asynchronous callback functions?

Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).

If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all, without any external libraries:

function asyncAction(i) {
    return new Promise(function(resolve, reject) {
        var result = calculateResult();
        if (result.hasError()) {
            return reject(result.error);
        }
        return resolve(result);
    });
}

var promises = [];
for (var i=0; i < 10; i++) {
    promises.push(asyncAction(i));
}

Promise.all(promises).then(function AcceptHandler(results) {
    handleResults(results),
}, function ErrorHandler(error) {
    handleError(error);
});

intellij idea - Error: java: invalid source release 1.9

I've just had a similar issue. The project had opened using Java 9 but even after all the modules and project were set back to 1.8, I was still getting the error.

I needed to force Gradle to refresh the project and then everything ran as expected.

What is SuppressWarnings ("unchecked") in Java?

Simply: It's a warning by which the compiler indicates that it cannot ensure type safety.

JPA service method for example:

@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
    Query query = entitymanager.createQuery("SELECT u FROM User u");
    return (List<User>)query.getResultList();
}

If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList.

In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.

I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html

how to POST/Submit an Input Checkbox that is disabled?

Don't disable it; instead set it to readonly, though this has no effect as per not allowing the user to change the state. But you can use jQuery to enforce this (prevent the user from changing the state of the checkbox:

$('input[type="checkbox"][readonly="readonly"]').click(function(e){
    e.preventDefault();
});

This assumes that all the checkboxes you don't want to be modified have the "readonly" attribute. eg.

<input type="checkbox" readonly="readonly">

What's the best way to add a full screen background image in React Native

Oh God Finally I find a great way for React-Native V 0.52-RC and native-base:

Your Content Tag Should be something like this: //==============================================================

<Content contentContainerStyle={styles.container}>
    <ImageBackground
        source={require('./../assets/img/back.jpg')}
        style={styles.backgroundImage}>
        <Text>
            Some text here ...
        </Text>
    </ImageBackground>
</Content>

And Your essential style is : //==============================================================

container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
},
backgroundImage:{
    flex : 1,
    width : '100%'
}

It works fine friends ... have fun

Groovy executing shell commands

def exec = { encoding, execPath, execStr, execCommands ->

def outputCatcher = new ByteArrayOutputStream()
def errorCatcher = new ByteArrayOutputStream()

def proc = execStr.execute(null, new File(execPath))
def inputCatcher = proc.outputStream

execCommands.each { cm ->
    inputCatcher.write(cm.getBytes(encoding))
    inputCatcher.flush()
}

proc.consumeProcessOutput(outputCatcher, errorCatcher)
proc.waitFor()

return [new String(outputCatcher.toByteArray(), encoding), new String(errorCatcher.toByteArray(), encoding)]

}

def out = exec("cp866", "C:\\Test", "cmd", ["cd..\n", "dir\n", "exit\n"])

println "OUT:\n" + out[0]
println "ERR:\n" + out[1]

SQL Query - how do filter by null or not null

How about statusid = statusid. Null is never equal to null.

ECONNREFUSED error when connecting to mongodb from node.js

you can go to mongoDB compass client and follow these steps: 1.Click Fill in connection fields individually: enter image description here

2.In hostname type : 127.0.0.1 enter image description here

3. Click CONNECT.

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new FileChooserEx().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();
                saveFile.showSaveDialog(null);
            }
        });

        openBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();
                openFile.showOpenDialog(null);
            }
        });

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

How to get main div container to align to centre?

The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:

body {
     margin: 0;
     padding: 0;
     text-align: center;
}
#main_container {
     margin: 0 auto;
     text-align: left;
}

How to set a default entity property value with Hibernate

The above suggestion works, but only if the annotation is used on the getter method. If the annotations is used where the member is declared, nothing will happen.

public String getStringValue(){
     return (this.stringValue == null) ? "Default" : stringValue;
}